12
\$\begingroup\$

Today I've implemented a database helper in Go. I'm new in Go world so I just wanted someone with more experience to take a look and tell me what is good and especially, what is bad (and why, if possible).

package clinic

import (
    "fmt"
    "github.com/astaxie/beego/orm"
    _ "github.com/go-sql-driver/mysql"
)

func init() {
    orm.RegisterDriver("mysql", orm.DR_MySQL)
    orm.RegisterDataBase("default", "mysql", "user@pass/db-name?charset=utf8")
}

func NewPet(pet *Pet){
    id, err := orm.NewOrm().Insert(pet)
    if err == nil {
        fmt.Println(id)
    }
}

func UpdatePet(pet *Pet){
    if num, err := orm.NewOrm().Update(pet); err == nil {
     fmt.Println(num)
    }
}

func DeletePet(pet *Pet){
    if num, err := orm.NewOrm().Delete(pet); err == nil {
     fmt.Println(num)
    }
}

func AllPets() []interface{} {
    var pets []Pet
    all, err := orm.NewOrm().QueryTable("pet").All(&pets)
    fmt.Printf("Returned Rows Num: %s, %s", all, err)
    result := make([]interface{}, len(pets))
    for i, s := range pets {
        r := s;
        result[i] = &r
    }
    return result;
}

This code works and I am able to use it in the main package, for example, using clinic.NewPet(&Pet{field: "value"}). I am just wondering if this can be improved.

\$\endgroup\$
1
\$\begingroup\$

What do you think about error handling? I think that's good idea to provide some log messages for main operation with db (CRUD).

As example for Delete function:

func DeletePet(pet *Pet) {
    num, err := orm.NewOrm().Delete(pet)

    if err != nil {
        log.Println("DELETE", err)
    } else {
        fmt.Println(num)
    }
}
\$\endgroup\$
  • \$\begingroup\$ could you please expand your description of what you are doing here to make the review a little meatier, please? \$\endgroup\$ – Malachi May 27 '16 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy