Created
October 1, 2018 21:17
-
-
Save berfarah/f3e018c1ffe83bce05a7cd6df07f3616 to your computer and use it in GitHub Desktop.
Iterative Optimization on Hot Paths: Storing JSON in the database
This file contains hidden or 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
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"` | |
} |
This file contains hidden or 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
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