Database

Before we jump into implementing GraphQL schema we need to setup database to save users and links, This is not supposed to be tutorial about databases in go but here is what we are going to do:

  • setup MySQL
  • define our models and create migrations

Setup MySQL

If you have docker you can run Mysql image from docker and use it.

Models and migrations

We need to create migrations for our app so every time our app runs it creates tables it needs to work properly, we are going to use golang-migrate package. create a folder structure for our database files:

go-graphql-hackernews
--internal
----pkg
------db
--------migrations
----------mysql

Install go mysql driver and golang-migrate packages then create migrations:

migrate command will create two files for each migration ending with .up and .down; up is responsible for applying migration and down is responsible for reversing it. open create_users_table.up.sql and add table for our users:

in create_links_table.up.sql:

We need one table for saving links and one table for saving users, Then we apply these to our database using migrate command.

  migrate -database mysql://root:dbpass@(172.17.0.2:3306)/hackernews -path internal/pkg/db/migrations/mysql up

Last thing is that we need a connection to our database, for this we create a mysql.go under mysql folder(We name this file after mysql since we are now using mysql and if we want to have multiple databases we can add other folders) with a function to initialize connection to database for later use.

InitDB Function creates a connection to our database and Migrate function runs migrations file for us. In `Migrate function we apply migrations just like we did with command line but with this function your app will always apply the latest migrations before start.

Then call InitDB and Migrate(Optional) In main func to create database connection at the start of the app:

Next Chapter

Create and Retrieve Links

Enable Users to create Links and see them

Go to next chapter