super basic TODO cli program
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
1.8 KiB

package main
import (
"fmt"
"log"
"os"
"strings"
_ "github.com/mattn/go-sqlite3"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type Task struct {
ID uint `gorm:"primaryKey"`
Task string
}
var path string = "/tmp/godo.db"
func InitDb(forced bool) bool {
if _, err := os.Stat(path); err == nil {
log.Printf("DB %s already exists\n", path)
if forced {
log.Println("Removing db...")
err := os.Remove(path)
if err != nil {
return false
}
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
log.Printf("DB created as %s:\n", path)
err = db.AutoMigrate(&Task{})
if err != nil {
return false
}
log.Println("DB migration complete")
}
} else if os.IsNotExist(err) {
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
log.Printf("DB created as %s:\n", path)
err = db.AutoMigrate(&Task{})
if err != nil {
return false
}
log.Println("DB migration complete")
}
return true
}
func AddTask(addTask []string) {
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{})
if err != nil {
log.Fatalln(err)
}
fmtTask := strings.Join(addTask, " ")
task := Task{Task: fmtTask}
result := db.Create(&task)
log.Println(result.Error)
log.Println(result.RowsAffected)
}
func LsTask() {
var tasks []Task
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{})
if err != nil {
log.Fatalln(err)
}
db.Find(&tasks)
for i := range tasks {
fmt.Printf("Task id: %+v\nTask: %+v\n", tasks[i].ID, tasks[i].Task)
}
}
func RmTask(taskID []string) {
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{})
if err != nil {
log.Fatalln(err)
}
for i := range taskID {
db.Delete(&Task{}, taskID[i])
}
}