-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
51 lines (43 loc) · 1.04 KB
/
database.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
package main
import (
"gorm.io/driver/postgres"
"gorm.io/gorm"
"log"
)
type Todo struct {
gorm.Model
Title string `json:"title"`
Done bool `json:"done"`
Explanation string `json:"explanation"`
}
var dsn string = "host=localhost user=user password=password dbname=todolist port=5433 sslmode=disable TimeZone=Asia/Tehran"
func pgConnection() *gorm.DB {
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
name := db.Migrator().CurrentDatabase()
_ = name
err = db.AutoMigrate(&Todo{})
if err != nil {
log.Fatal("Database migration failed : ", err)
}
return db
}
func retriveToDos(db *gorm.DB) ([]Todo, error) {
var Todos []Todo
result := db.Find(&Todos)
if result.Error != nil {
log.Fatal("Database migration failed : ", result.Error)
return nil, result.Error
}
return Todos, nil
}
func addToDo(db *gorm.DB, Todo Todo) error {
result := db.Create(&Todo)
if result.Error != nil {
log.Fatal("Database migration failed : ", result.Error)
return result.Error
}
return nil
}