Skip to content

Instantly share code, notes, and snippets.

View hernanhrm's full-sized avatar
🏠
Working from home

Hernan Reyes hernanhrm

🏠
Working from home
View GitHub Profile
// Meal model a record of meals table
type Meal struct {
ID uint
Name string
Description string
DrinkID uint
Drink Drink
}
type Meals []Meal
type Waitress struct {
db *sql.DB
}
// getMeals gets 20 meals from the db
func (b Waitress) getMeals() (Meals, error) {
// this method has the logic to query from the db, if you want to see
// the actual code, you can go the repo
func (b Waitress) ListMenu() (Meals, error) {
// the `1` of our `N+1`
meals, err := b.getMeals()
if err != nil {
return nil, err
}
// here is our waitress going back and forth
// from floor 1 to 10, this will be the `N` of our `N+1`
for i, meal := range meals {
SELECT m.id, m.name, m.description, d.name, d.description
FROM meals AS m
INNER JOIN drinks AS d ON d.id = m.drink_id
type Solution1 struct {
db *sql.DB
}
func (s Solution1) ListMenu() (Meals, error) {
// this method will execute the previous SQL
// SELECT
// m.id,
// m.name,
// m.description,
func (s Solution2) ListMenu() (Meals, error) {
meals, err := s.getMeals()
if err != nil {
return nil, err
}
// this is our waitress bringing everything in a bussing cart
drinks, err := s.getDrinksByIDsIn(meals.GetUniqueDrinkIDs())
if err != nil {
// to query the drinks, we need to know their IDs, for that
// we add this method to our `Meals` slice
func (m Meals) GetUniqueDrinkIDs() []uint {
var ids []uint
drinks := make(map[uint]struct{}, 0)
for _, v := range m {
_, ok := drinks[v.DrinkID]
if ok {
continue
CREATE TABLE users
(
id SERIAL NOT NULL,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100),
email VARCHAR(100) NOT NULL,
password VARCHAR(256) NOT NULL
);
@hernanhrm
hernanhrm / 20220618222143_create_users_table.go
Created June 19, 2022 20:36
hernanreyes.dev/database-migrations
func init() {
goose.AddMigration(upCreateUsersTable, downCreateUsersTable)
}
func upCreateUsersTable(tx *sql.Tx) error {
_, err := tx.Exec(`
CREATE TABLE users
(
id SERIAL NOT NULL,
first_name VARCHAR(100) NOT NULL,
// PaymentMethodStrategy will let us interchange
// the payment method in the context
type PaymentMethodStrategy interface {
Pay() error
}