-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.go
91 lines (79 loc) · 1.85 KB
/
store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"log"
)
type Store interface {
Open() error
Close() error
GetMovies() ([]*Movie, error)
GetMovieById(id int64) (*Movie, error)
CreateMovie(m *Movie) error
FindUser(username string, password string) (bool, error)
}
type dbStore struct {
db *sqlx.DB
}
var schema = `
CREATE TABLE IF NOT EXISTS movie
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
release_date TEXT,
duration INTEGER,
trailer_url TEXT
);
CREATE TABLE IF NOT EXISTS user
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT,
password TEXT
);
`
func (store *dbStore) Open() error {
db, err := sqlx.Connect("sqlite3", "goflix.db")
if err != nil {
return err
}
log.Println("Connected to DB")
db.MustExec(schema)
store.db = db
return nil
}
func (store *dbStore) Close() error {
return store.db.Close()
}
func (store *dbStore) GetMovies() ([]*Movie, error) {
var movies []*Movie
err := store.db.Select(&movies, "SELECT * FROM movie")
if err != nil {
return movies, err
}
return movies, nil
}
func (store *dbStore) GetMovieById(id int64) (*Movie, error) {
var movie = &Movie{}
err := store.db.Get(movie, "SELECT * FROM movie WHERE id=$1", id)
if err != nil {
return movie, nil
}
return movie, nil
}
func (store *dbStore) CreateMovie(m *Movie) error {
res, err := store.db.Exec("INSERT INTO movie (title, release_date, duration, trailer_url) VALUES (?, ?, ?, ?)",
m.Title, m.ReleaseDate, m.Duration, m.TrailerURL)
if err != nil {
return err
}
m.ID, err = res.LastInsertId()
return err
}
func (store *dbStore) FindUser(username string, password string) (bool, error) {
var count int
err := store.db.Get(&count, "SELECT COUNT(id) FROM user WHERE username=$1 AND password=$2", username, password)
if err != nil {
return false, err
}
return count == 1, nil
}