Created
November 19, 2015 09:04
-
-
Save alecha/7dc672df808136217854 to your computer and use it in GitHub Desktop.
Gist to reproduce the CreatedAt behaviour in Gorm library (GO)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"errors" | |
"time" | |
_ "github.com/go-sql-driver/mysql" | |
"github.com/jinzhu/gorm" | |
) | |
var db gorm.DB | |
func init() { | |
var err error | |
db, err = gorm.Open("mysql", "root:@/embrace?charset=utf8&parseTime=True") | |
if err != nil { | |
panic(err) | |
} | |
db.LogMode(true) | |
} | |
func main() { | |
db.SingularTable(true) | |
//create the user | |
var user = User{ID: 1, FirstName: "Alessio", LastName: "Cavaleri"} | |
if err := user.Create(); err != nil { | |
panic(err) | |
} | |
//simulate a json string received and consumed by an API | |
var updatedUserJSON = `{"id":1, "firstName" : "Alessio2", "lastName" : "Cavaleri2"}` | |
var updatedUser User | |
json.Unmarshal([]byte(updatedUserJSON), &updatedUser) | |
//update the user | |
if err := updatedUser.Update(); err != nil { | |
panic(err) | |
} | |
} | |
//User defines a user | |
type User struct { | |
ID int64 `json:"id"` | |
FirstName string `json:"firstName"` | |
LastName string `json:"lastName"` | |
CreatedAt time.Time `json:"createdAt"` | |
UpdatedAt time.Time `json:"updatedAt"` | |
} | |
//Create create a new user | |
func (u *User) Create() error { | |
db.NewRecord(*u) | |
return db.Create(u).Error | |
} | |
//Update update a user in DB | |
func (u *User) Update() error { | |
if u.ID <= 0 { | |
return errors.New("Cannot update a user without ID") | |
} | |
return db.Save(u).Error | |
} | |
/* | |
(/Users/alessiocavaleri/Documents/Code/go/src/github.com/alecha/gorm-created/main.go:57) | |
[2015-11-19 10:02:44] [0.76ms] INSERT INTO `user` (`first_name`,`last_name`,`created_at`,`updated_at`,`id`) VALUES ('Alessio','Cavaleri','2015-11-19T10:02:44+01:00','2015-11-19T10:02:44+01:00','1') | |
(/Users/alessiocavaleri/Documents/Code/go/src/github.com/alecha/gorm-created/main.go:65) | |
[2015-11-19 10:02:44] [1.59ms] UPDATE `user` SET `updated_at` = '2015-11-19T10:02:44+01:00', `first_name` = 'Alessio2', `last_name` = 'Cavaleri2', `created_at` = '0001-01-01T00:00:00Z' WHERE (`id` = '1') | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment