focus/backend/db/projects.go

89 lines
1.6 KiB
Go
Raw Normal View History

2023-12-27 22:23:10 +01:00
package db
2023-12-27 19:19:49 +01:00
import (
2023-12-27 22:23:10 +01:00
"git.bhasher.com/bhasher/focus/backend/types"
2023-12-27 19:19:49 +01:00
)
2023-12-27 22:23:10 +01:00
func CreateProject(p types.Project) (int, error) {
2023-12-27 19:19:49 +01:00
res, err := db.Exec("INSERT INTO projects (title) VALUES (?)", p.Title)
if err != nil {
return 0, err
}
id, err := res.LastInsertId()
if err != nil {
return 0, err
}
return int(id), nil
}
2023-12-27 22:23:10 +01:00
func GetAllProjects() ([]types.Project, error) {
2023-12-27 19:19:49 +01:00
rows, err := db.Query("SELECT * FROM projects")
if err != nil {
return nil, err
}
defer rows.Close()
2023-12-27 22:23:10 +01:00
var projects []types.Project
2023-12-27 19:19:49 +01:00
for rows.Next() {
2023-12-27 22:23:10 +01:00
var p types.Project
2023-12-27 19:19:49 +01:00
if err := rows.Scan(&p.ID, &p.Title); err != nil {
return nil, err
}
projects = append(projects, p)
}
if err = rows.Err(); err != nil {
return nil, err
}
return projects, nil
}
2023-12-27 22:23:10 +01:00
func GetProject(id int) (*types.Project, error) {
var p types.Project
2023-12-27 19:19:49 +01:00
2023-12-30 16:03:44 +01:00
rows, err := db.Query("SELECT * FROM projects WHERE id = ?", id)
2023-12-27 19:19:49 +01:00
if err != nil {
return nil, err
}
2023-12-30 16:03:44 +01:00
defer rows.Close()
if !rows.Next() {
return nil, nil
}
2023-12-27 19:19:49 +01:00
2023-12-30 16:03:44 +01:00
if err := rows.Scan(&p.ID, &p.Title); err != nil {
return nil, err
}
2023-12-27 19:19:49 +01:00
return &p, nil
2023-12-30 16:03:44 +01:00
2023-12-27 19:19:49 +01:00
}
2023-12-30 16:03:44 +01:00
func DeleteProject(id int) (int64, error) {
res, err := db.Exec("DELETE FROM projects WHERE id = ?", id)
if err != nil {
return 0, err
}
return res.RowsAffected()
2023-12-27 19:19:49 +01:00
}
2023-12-30 16:03:44 +01:00
func UpdateProject(p types.Project) (int64, error) {
res, err := db.Exec("UPDATE projects SET title = ? WHERE id = ?", p.Title, p.ID)
if err != nil {
return 0, err
}
return res.RowsAffected()
2023-12-27 19:19:49 +01:00
}
2023-12-30 04:07:53 +01:00
func ExistProject(id int) (bool, error) {
var count int
err := db.QueryRow("SELECT COUNT(*) FROM projects WHERE id = ?", id).Scan(&count)
if err != nil {
return false, err
}
return count > 0, nil
}