Skip to content

Instantly share code, notes, and snippets.

@matjam
Created October 8, 2019 19:13
Show Gist options
  • Save matjam/d31b370f93660b2588b179e941952931 to your computer and use it in GitHub Desktop.
Save matjam/d31b370f93660b2588b179e941952931 to your computer and use it in GitHub Desktop.
Example GORM model
package model
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
// this is shared by all goroutines accessing the database. Note it is NOT
// exported as any database access code should be in this package. This creates
// clean separation of concerns.
//
// GORM by default uses a sync.Pool under the hood for this handle, so you
// don't need to worry about concurrent access, mutex locking etc.
var db *gorm.DB
// User is a simple example of a User database table.
type User struct {
gorm.Model
FirstName string
LastName string
Age int
}
// ConnectDatabase is called by the main() during startup of your application, once. I
// do not recommend doing this in an init() function - you want to connect to databases
// once you're ready, which might be after you've read configuration files, etc.
func ConnectDatabase() error {
var err error
db, err = gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
if err != nil {
return fmt.Errorf("error in connectDatabase(): %v", err)
}
db.AutoMigrate(&User{}) // ok for development, suggest using Goblin for more complex requirements.
}
// GetByID is an example function to get a row from the User table defined above. You
// would typically declare a `var u model.User` in your code, and then call this method
// to populate that structure you declared.
func (user *User) GetByID(id int) error {
err := db.First(user, id).Error
if err != nil {
return fmt.Errorf("error in GetByID() for id %v: %v", id, err)
}
// at this point the structure pointed to by `user` is filled in with the row data.
return nil
}
// You can see how the above pattern could be generalized using interfaces. I generally
// prefer putting all the DB access in it's own package simply because I would rather the
// users of the data not need to manage the DB handle etc.
// I have not tested any of this gist so it might require some fixing to compile :-)
@giou-k
Copy link

giou-k commented Jun 12, 2020

Hello, is there a way to run the equilavent of create database dbname using gorm mysql? db.Open is successful only if the database is already created...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment