🚀 Get 25% off access to all my premium courses - use discount code FUNCMAIN at checkout - view the pricing page now!

Video:

The Database Package

April 22, 2021

Course Instructor: Elliot Forbes

Hey Gophers! My name is Elliot and I'm the creator of TutorialEdge and I've been working with Go systems for roughly 5 years now.

Running Postgres Locally with Docker

Before we set about implementing the database package, we’ll need a database running somewhere to connect to and create our tables on. Let’s kick off a locally running database using docker:

$ docker run --name rocket-inventory-db -e POSTGRES_PASSWORD=postgres -p 5432:5432 -d postgres

Awesome, if we do docker ps we should now be able to see our locally running docker container running our Postgres database!

Implementing our DB package

package db

import (
	"fmt"
	"os"

	"github.com/TutorialEdge/go-grpc-services-course/internal/rocket"

	"github.com/jmoiron/sqlx"
)

// DB
type Store struct {
	db *sqlx.DB
}

// New - returns a new Store
func New() (Store, error) {
	dbUsername := os.Getenv("DB_USERNAME")
	dbPassword := os.Getenv("DB_PASSWORD")
	dbHost := os.Getenv("DB_HOST")
	dbTable := os.Getenv("DB_TABLE")
	dbPort := os.Getenv("DB_PORT")

	connectString := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=disable", dbHost, dbPort, dbUsername, dbTable, dbPassword)

	db, err := sqlx.Connect("postgres", connectString)
	if err != nil {
		return Store{}, err
	}
	return Store{
		db: db,
	}, nil
}

// GetRocketByID - returns a rocket from the database by a given ID
func (s Store) GetRocketByID(id string) (rocket.Rocket, error) {
	return rocket.Rocket{}, nil
}

// InsertRocket - inserts a new rocket into the database
func (s Store) InsertRocket(rkt rocket.Rocket) (rocket.Rocket, error) {
	return rocket.Rocket{}, nil
}

// DeleteRocket - deletes a rocket from the database by it's ID
func (s Store) DeleteRocket(id string) error {
	return nil
}

Awesome, let’s now look at how we can instantiate a new Store within the main.go file and wire this into a Rocket service.

Conclusion

Awesome, in this video, we’ve been able to succesfully implement our database package and wire it into our rocket service within the main.go file.

With the business critical section of our application out of the way, we can now start to focus on the transport layer of our application!