-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
83 lines (65 loc) · 1.69 KB
/
db.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
package main
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func ConnectDB() *gorm.DB {
db, err := gorm.Open(sqlite.Open(config.DBPath), &gorm.Config{})
if err != nil {
panic("Failed to connect to database!")
}
return db
}
func addTodo(user, content string) error {
newTodo := todo{User: user, Task: content, Completed: false}
result := db.Create(&newTodo)
if result.Error != nil {
return result.Error
}
return nil
}
func getTodos(user string) ([]todo, error) {
var todo []todo
result := db.Where("user = ? AND completed = ?", user, false).Find(&todo)
if result.Error != nil {
return nil, result.Error
}
return todo, nil
}
func getNumCompleted(user string) (int64, error) {
var count int64
result := db.Where("user = ? AND completed = ?", user, true).Table("todos").Count(&count)
if result.Error != nil {
return 0, result.Error
}
return count, nil
}
func getAllTodos() ([]todo, error) {
var todo []todo
result := db.Where("completed = ?", false).Find(&todo)
if result.Error != nil {
return nil, result.Error
}
return todo, nil
}
func completeTodoById(id int) (todo, error) {
var todoRes todo
result := db.Where("Id = ?", id).First(&todoRes)
if result.Error != nil {
return todo{}, result.Error
}
result = db.Model(&todo{}).Where("Id = ?", id).Update("completed", true)
if result.Error != nil {
return todo{}, result.Error
}
return todoRes, nil
}
func deleteTodos(user string) error {
return db.Where("user = ?", user).Delete(&todo{}).Error
}
func deleteTodoById(id int) error {
return db.Where("Id = ?", id).Delete(&todo{}).Error
}
func updateTodoById(id int, content string) error {
return db.Model(&todo{}).Where("Id = ?", id).Update("task", content).Error
}