Skip to content

Instantly share code, notes, and snippets.

@berfarah
Created October 1, 2018 21:17
Show Gist options
  • Save berfarah/f3e018c1ffe83bce05a7cd6df07f3616 to your computer and use it in GitHub Desktop.
Save berfarah/f3e018c1ffe83bce05a7cd6df07f3616 to your computer and use it in GitHub Desktop.
Iterative Optimization on Hot Paths: Storing JSON in the database
type User struct {
ID int64 `sql:",primary"`
Name string
// The go struct representation of our data.
Configuration Configuration `sql:"-"`
// The JSON blob to be stored in and fetched from the database.
ConfigurationBlob []byte `graphql:"-" sql:"configuration"`
}
func (s *UserRepository) Update(ctx context.Context, u *User) error {
// Serialize the configuration struct into JSON
b, err := json.Marshal(u.Configuration)
if err != nil {
return err
}
// Set the blob to be saved to the database
u.ConfigurationBlob = b
return s.DB.Update(ctx, &u)
}
func (s *UserRepository) ById(ctx context.Context, id int64) (*User, error) {
var user *User
if err := s.DB.QueryRow(ctx, &user); err != nil {
return nil, err
}
// De-serialize the JSON from the database into the Go struct
if err := json.Unmarshal(user.ConfigurationBlob, &user.Configuration); err != nil {
return nil, err
}
return user, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment