Encapsulated database for extracting common error patterns.

This commit is contained in:
Gergely Brautigam 2016-01-31 13:13:34 +01:00
parent 72906dd92b
commit 939ef68486
2 changed files with 86 additions and 132 deletions

View File

@ -7,15 +7,9 @@ import (
// AddFile is used to add the md5 of a file name which is uploaded to our application // AddFile is used to add the md5 of a file name which is uploaded to our application
// this will enable us to randomize the URL without worrying about the file names // this will enable us to randomize the URL without worrying about the file names
func AddFile(fileName, token string) error { func AddFile(fileName, token string) error {
SQL, err := database.Prepare("insert into files values(?,?)") SQL := database.prepare("insert into files values(?,?)")
if err != nil {
log.Println(err)
}
tx, err := database.Begin()
if err != nil { tx := database.begin()
log.Println(err)
}
_, err = tx.Stmt(SQL).Exec(fileName, token) _, err = tx.Stmt(SQL).Exec(fileName, token)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
@ -30,7 +24,7 @@ func AddFile(fileName, token string) error {
func GetFileName(token string) (string, error) { func GetFileName(token string) (string, error) {
sql := "select name from files where autoName=?" sql := "select name from files where autoName=?"
var fileName string var fileName string
rows, err := database.Query(sql, fileName) rows := database.query(sql, fileName)
if rows.Next() { if rows.Next() {
err := rows.Scan(&fileName) err := rows.Scan(&fileName)
if err != nil { if err != nil {
@ -38,9 +32,6 @@ func GetFileName(token string) (string, error) {
return "", err return "", err
} }
} }
if err != nil {
return "", err
}
return fileName, nil return fileName, nil
} }

View File

@ -2,27 +2,57 @@ package db
import ( import (
"database/sql" "database/sql"
_ "github.com/mattn/go-sqlite3" //we want to use sqlite natively "fmt"
md "github.com/shurcooL/github_flavored_markdown"
"github.com/thewhitetulip/Tasks/types"
"log"
"strings" "strings"
"time" "time"
_ "github.com/mattn/go-sqlite3" //we want to use sqlite natively
"github.com/thewhitetulip/Tasks/types"
) )
var database *sql.DB var database Database
var err error var err error
func init() { //Database encapsulates database
database, err = sql.Open("sqlite3", "./tasks.db") type Database struct {
db *sql.DB
}
func (db Database) begin() (tx *sql.Tx) {
tx, err := db.db.Begin()
if err != nil { if err != nil {
log.Println(err) fmt.Println(err)
}
return tx
}
func (db Database) prepare(q string) (stmt *sql.Stmt) {
stmt, err := db.db.Prepare(q)
if err != nil {
fmt.Println(err)
}
return stmt
}
func (db Database) query(q string, args ...interface{}) (rows *sql.Rows) {
rows, err := db.db.Query(q, args)
if err != nil {
fmt.Println(err)
}
return rows
}
func init() {
database = Database{}
database.db, err = sql.Open("sqlite3", "./tasks.db")
if err != nil {
fmt.Println(err)
} }
} }
//Close function closes this database connection //Close function closes this database connection
func Close() { func Close() {
database.Close() database.db.Close()
} }
//GetTasks retrieves all the tasks depending on the //GetTasks retrieves all the tasks depending on the
@ -34,32 +64,26 @@ func GetTasks(status string) types.Context {
var TaskTitle string var TaskTitle string
var TaskContent string var TaskContent string
var TaskCreated time.Time var TaskCreated time.Time
var TaskPriority string
var getTasksql string var getTasksql string
basicSQL := "select id, title, content, created_date, priority from task "
if status == "pending" { if status == "pending" {
getTasksql = basicSQL + " where finish_date is null and is_deleted='N' order by priority desc, created_date asc" getTasksql = "select id, title, content, created_date from task where finish_date is null and is_deleted='N' order by created_date asc"
} else if status == "deleted" { } else if status == "deleted" {
getTasksql = basicSQL + " where is_deleted='Y' order by priority desc, created_date asc" getTasksql = "select id, title, content, created_date from task where is_deleted='Y' order by created_date asc"
} else if status == "completed" { } else if status == "completed" {
getTasksql = basicSQL + " where finish_date is not null order by priority desc, created_date asc" getTasksql = "select id, title, content, created_date from task where finish_date is not null order by created_date asc"
} }
rows, err := database.Query(getTasksql) rows := database.query(getTasksql)
if err != nil {
log.Println(err)
}
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
err := rows.Scan(&TaskID, &TaskTitle, &TaskContent, &TaskCreated, &TaskPriority) err := rows.Scan(&TaskID, &TaskTitle, &TaskContent, &TaskCreated)
TaskContent = string(md.Markdown([]byte(TaskContent))) TaskContent = strings.Replace(TaskContent, "\n", "<br>", -1)
// TaskContent = strings.Replace(TaskContent, "\n", "<br>", -1)
if err != nil { if err != nil {
log.Println(err) fmt.Println(err)
} }
TaskCreated = TaskCreated.Local() TaskCreated = TaskCreated.Local()
a := types.Task{Id: TaskID, Title: TaskTitle, Content: TaskContent, Created: TaskCreated.Format(time.UnixDate)[0:20], Priority: TaskPriority} a := types.Task{Id: TaskID, Title: TaskTitle, Content: TaskContent, Created: TaskCreated.Format(time.UnixDate)[0:20]}
task = append(task, a) task = append(task, a)
} }
context = types.Context{Tasks: task, Navigation: status} context = types.Context{Tasks: task, Navigation: status}
@ -70,20 +94,19 @@ func GetTasks(status string) types.Context {
func GetTaskByID(id int) types.Context { func GetTaskByID(id int) types.Context {
var tasks []types.Task var tasks []types.Task
var task types.Task var task types.Task
var TaskID int
var TaskTitle string
var TaskContent string
getTasksql := "select id, title, content from task where id=?"
getTasksql := "select id, title, content, priority from task where id=?" rows := database.query(getTasksql, id)
rows, err := database.Query(getTasksql, id)
if err != nil {
log.Println(err)
}
defer rows.Close() defer rows.Close()
if rows.Next() { if rows.Next() {
err := rows.Scan(&task.Id, &task.Title, &task.Content, &task.Priority) err := rows.Scan(&TaskID, &TaskTitle, &TaskContent)
if err != nil { if err != nil {
log.Println(err) fmt.Println(err)
//send email to respective people
} }
task = types.Task{Id: TaskID, Title: TaskTitle, Content: TaskContent}
} }
tasks = append(tasks, task) tasks = append(tasks, task)
context := types.Context{Tasks: tasks, Navigation: "edit"} context := types.Context{Tasks: tasks, Navigation: "edit"}
@ -92,17 +115,11 @@ func GetTaskByID(id int) types.Context {
//TrashTask is used to delete the task //TrashTask is used to delete the task
func TrashTask(id int) error { func TrashTask(id int) error {
trashSQL, err := database.Prepare("update task set is_deleted='Y',last_modified_at=datetime() where id=?") trashSQL := database.prepare("update task set is_deleted='Y',last_modified_at=datetime() where id=?")
if err != nil { tx := database.begin()
log.Println(err)
}
tx, err := database.Begin()
if err != nil {
log.Println(err)
}
_, err = tx.Stmt(trashSQL).Exec(id) _, err = tx.Stmt(trashSQL).Exec(id)
if err != nil { if err != nil {
log.Println("doing rollback") fmt.Println("doing rollback")
tx.Rollback() tx.Rollback()
} else { } else {
tx.Commit() tx.Commit()
@ -112,17 +129,11 @@ func TrashTask(id int) error {
//CompleteTask is used to mark tasks as complete //CompleteTask is used to mark tasks as complete
func CompleteTask(id int) error { func CompleteTask(id int) error {
stmt, err := database.Prepare("update task set is_deleted='Y', finish_date=datetime(),last_modified_at=datetime() where id=?") stmt := database.prepare("update task set is_deleted='Y', finish_date=datetime(),last_modified_at=datetime() where id=?")
if err != nil { tx := database.begin()
log.Println(err)
}
tx, err := database.Begin()
if err != nil {
log.Println(err)
}
_, err = tx.Stmt(stmt).Exec(id) _, err = tx.Stmt(stmt).Exec(id)
if err != nil { if err != nil {
log.Println(err) fmt.Println(err)
tx.Rollback() tx.Rollback()
} else { } else {
tx.Commit() tx.Commit()
@ -132,17 +143,11 @@ func CompleteTask(id int) error {
//DeleteAll is used to empty the trash //DeleteAll is used to empty the trash
func DeleteAll() error { func DeleteAll() error {
stmt, err := database.Prepare("delete from task where is_deleted='Y'") stmt := database.prepare("delete from task where is_deleted='Y'")
if err != nil { tx := database.begin()
log.Println(err)
}
tx, err := database.Begin()
if err != nil {
log.Println(err)
}
_, err = tx.Stmt(stmt).Exec() _, err = tx.Stmt(stmt).Exec()
if err != nil { if err != nil {
log.Println("doing rollback") fmt.Println("doing rollback")
tx.Rollback() tx.Rollback()
} else { } else {
tx.Commit() tx.Commit()
@ -152,37 +157,11 @@ func DeleteAll() error {
//RestoreTask is used to restore tasks from the Trash //RestoreTask is used to restore tasks from the Trash
func RestoreTask(id int) error { func RestoreTask(id int) error {
restoreSQL, err := database.Prepare("update task set is_deleted='N',last_modified_at=datetime() where id=?") restoreSQL := database.prepare("update task set is_deleted='N',last_modified_at=datetime() where id=?")
if err != nil { tx := database.begin()
log.Println(err)
}
tx, err := database.Begin()
if err != nil {
log.Println(err)
}
_, err = tx.Stmt(restoreSQL).Exec(id) _, err = tx.Stmt(restoreSQL).Exec(id)
if err != nil { if err != nil {
log.Println("doing rollback") fmt.Println("doing rollback")
tx.Rollback()
} else {
tx.Commit()
}
return err
}
//RestoreTask is used to restore tasks from the Trash
func RestoreTaskFromComplete(id int) error {
restoreSQL, err := database.Prepare("update task set finish_date=null,last_modified_at=datetime() where id=?")
if err != nil {
log.Println(err)
}
tx, err := database.Begin()
if err != nil {
log.Println(err)
}
_, err = tx.Stmt(restoreSQL).Exec(id)
if err != nil {
log.Println("doing rollback")
tx.Rollback() tx.Rollback()
} else { } else {
tx.Commit() tx.Commit()
@ -192,17 +171,14 @@ func RestoreTaskFromComplete(id int) error {
//DeleteTask is used to delete the task from the database //DeleteTask is used to delete the task from the database
func DeleteTask(id int) error { func DeleteTask(id int) error {
deleteSQL, err := database.Prepare("delete from task where id = ?") deleteSQL := database.prepare("delete from task where id = ?")
tx := database.begin()
if err != nil { if err != nil {
log.Println(err) fmt.Println(err)
}
tx, err := database.Begin()
if err != nil {
log.Println(err)
} }
_, err = tx.Stmt(deleteSQL).Exec(id) _, err = tx.Stmt(deleteSQL).Exec(id)
if err != nil { if err != nil {
log.Println(err) fmt.Println(err)
tx.Rollback() tx.Rollback()
} else { } else {
tx.Commit() tx.Commit()
@ -211,15 +187,12 @@ func DeleteTask(id int) error {
} }
//AddTask is used to add the task in the database //AddTask is used to add the task in the database
func AddTask(title, content string, taskPriority int) error { func AddTask(title, content string) error {
restoreSQL, err := database.Prepare("insert into task(title, content, priority, created_date, last_modified_at) values(?,?,?,datetime(), datetime())") restoreSQL := database.prepare("insert into task(title, content, created_date, last_modified_at) values(?,?,datetime(), datetime())")
tx := database.begin()
_, err = tx.Stmt(restoreSQL).Exec(title, content)
if err != nil { if err != nil {
log.Println(err) fmt.Println(err)
}
tx, err := database.Begin()
_, err = tx.Stmt(restoreSQL).Exec(title, content, taskPriority)
if err != nil {
log.Println(err)
tx.Rollback() tx.Rollback()
} else { } else {
tx.Commit() tx.Commit()
@ -229,21 +202,14 @@ func AddTask(title, content string, taskPriority int) error {
//UpdateTask is used to update the tasks in the database //UpdateTask is used to update the tasks in the database
func UpdateTask(id int, title string, content string) error { func UpdateTask(id int, title string, content string) error {
SQL, err := database.Prepare("update task set title=?, content=? where id=?") SQL := database.prepare("update task set title=?, content=? where id=?")
if err != nil { tx := database.begin()
log.Println(err)
}
tx, err := database.Begin()
if err != nil {
log.Println(err)
}
_, err = tx.Stmt(SQL).Exec(title, content, id) _, err = tx.Stmt(SQL).Exec(title, content, id)
if err != nil { if err != nil {
log.Println(err) fmt.Println(err)
tx.Rollback() tx.Rollback()
} else { } else {
log.Println(tx.Commit()) fmt.Println(tx.Commit())
} }
return err return err
} }
@ -258,18 +224,15 @@ func SearchTask(query string) types.Context {
var TaskCreated time.Time var TaskCreated time.Time
var context types.Context var context types.Context
rows, err := database.Query(stmt, query, query) rows := database.query(stmt, query, query)
if err != nil {
log.Println(err)
}
for rows.Next() { for rows.Next() {
err := rows.Scan(&TaskID, &TaskTitle, &TaskContent, &TaskCreated) err := rows.Scan(&TaskID, &TaskTitle, &TaskContent, &TaskCreated)
if err != nil { if err != nil {
log.Println(err) fmt.Println(err)
} }
TaskTitle = strings.Replace(TaskTitle, query, "<span class='highlight'>"+query+"</span>", -1) TaskTitle = strings.Replace(TaskTitle, query, "<span class='highlight'>"+query+"</span>", -1)
TaskContent = strings.Replace(TaskContent, query, "<span class='highlight'>"+query+"</span>", -1) TaskContent = strings.Replace(TaskContent, query, "<span class='highlight'>"+query+"</span>", -1)
TaskContent = string(md.Markdown([]byte(TaskContent)))
a := types.Task{Id: TaskID, Title: TaskTitle, Content: TaskContent, Created: TaskCreated.Format(time.UnixDate)[0:20]} a := types.Task{Id: TaskID, Title: TaskTitle, Content: TaskContent, Created: TaskCreated.Format(time.UnixDate)[0:20]}
task = append(task, a) task = append(task, a)
} }