-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql.go
123 lines (102 loc) · 2.54 KB
/
sql.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"database/sql"
"errors"
"fmt"
_ "github.com/mattn/go-sqlite3"
"log"
"os"
)
func findIng(name string, db *sql.DB) {
rows, _ := db.Query("SELECT recipeID FROM ingredients WHERE name = ?", name) // \""+name+"\""
defer rows.Close()
for rows.Next() {
var recipeID string
err := rows.Scan(&recipeID)
if err != nil {
log.Fatal(err)
}
fmt.Println(recipeID)
}
}
func rmvRecipe(name string, db *sql.DB) {
stmt, err := db.Prepare("DELETE FROM recipes where name = ?")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
_, err = stmt.Exec(name)
if err != nil {
log.Fatal(err)
}
stmt, err = db.Prepare("DELETE FROM ingredients where recipeID = ?")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
_, err = stmt.Exec(name)
if err != nil {
log.Fatal(err)
}
}
func addRecipe(rec *recipe, db *sql.DB) {
stmt, _ := db.Prepare("INSERT INTO recipes (name, time, instructions) VALUES (?, ?, ?)")
stmt.Exec(rec.name, rec.time, rec.instructions)
for _, ing := range rec.ingredients {
stmt, _ := db.Prepare("INSERT INTO ingredients (recipeID, name, quantity) VALUES (?, ?, ?)")
stmt.Exec(rec.name, ing.name, ing.quantity)
}
defer stmt.Close()
}
func getRecipe(name string, db *sql.DB) (rec recipe, err error) {
row := db.QueryRow("SELECT name, time, instructions FROM recipes WHERE name=?", name)
err = row.Scan(&rec.name, &rec.time, &rec.instructions)
if err != nil {
return
}
rows, _ := db.Query("SELECT name, quantity FROM ingredients WHERE recipeID = ?", name) // \""+name+"\""
defer rows.Close()
for rows.Next() {
var ing ingredient
err = rows.Scan(&ing.name, &ing.quantity)
if err != nil {
return
}
rec.ingredients = append(rec.ingredients, ing)
}
return rec, nil
}
func createTable(db *sql.DB) {
const create string = `
CREATE TABLE IF NOT EXISTS ingredients (
id INTEGER NOT NULL,
recipeID INTEGER NOT NULL,
name TEXT NOT NULL,
quantity TEXT,
PRIMARY KEY(id AUTOINCREMENT)
);
CREATE TABLE IF NOT EXISTS recipes (
name TEXT NOT NULL PRIMARY KEY,
time INTEGER,
instructions TEXT
);`
if _, err := db.Exec(create); err != nil {
log.Fatal(err)
}
}
// opens database if none then errors
func readDB(filename string) (*sql.DB, error) {
return sql.Open("sqlite3", filename)
}
// opens database if none then creates
func openDB(filename string) (*sql.DB, error) {
if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) {
file, err := os.Create(filename)
if err != nil {
return nil, err
}
file.Close()
}
db, err := readDB(filename)
return db, err
}