The Phonebook Database

Creating a database for out phonebook application is an essential task. It's an essential task for any application that needs to store data. We need to be able to create and recreate the database as the application evolves. Once you get that out of the way, you can focus on building your actual application.

To create the database, we'll utilize the concept of migrations. We'll use the gorm package to create the migrations, while using the go-migrate package to manage the migrations and keep track of the ones that have been applied.

Migration Structure

Migrations

file: pkg/db/migrations/01_create_contacts_table.go
func init() {
	m := &gormigrate.Migration{}

	m.ID = "yyyyMMdd01_migration_name"

	m.Migrate = func(db *gorm.DB) error {

		...

		return nil
	}

	m.Rollback = func(db *gorm.DB) error {

		...

		return nil
	}

	AddMigration(m)
}

The Model


Separation of concerns


Complete Code

Migrations

file: pkg/db/migrations/01_create_contacts_table.go
func init() {
	m := &gormigrate.Migration{}

	m.ID = "yyyyMMdd01_migration_name"

	m.Migrate = func(db *gorm.DB) error {

		type Contact struct {
				models.ModelBase
				FirstName string `gorm:"size:255"`
				LastName  string `gorm:"size:255"`
				Nickname  string `gorm:"size:255"`
				Email     string `gorm:"size:255"`
				Phone     string `gorm:"size:255"`
		}

		return nil
	}

	m.Rollback = func(db *gorm.DB) error {

		...

		return nil
	}

	AddMigration(m)
}

Applying migrations

Applying migrations means to create the actual database schema. This is generally something you do once, when you first set up your application or when you make changes to the database schema. To apply database migrations, all you have to do is run the following command:

Apply migrations

go run . db migrate

Was this page helpful?

Consider supporting my work if you find it useful

Buy me a coffee