Recenlty I wanted to write a small database seeding abstraction. Database seeding is a process in which an initial set of data is provided to a database when it is being set up or installed.
Yet, in true Go fashion my goal was to keep the abstraction tiny, yet provide some structure to folks that would write seeds in this application. This is absolutely not the only way you can achieve this, the options are plenty. Still, this is one approach that I have found to be working well.
We will have three different components:
- Create a
- Identify path for the seeds and how to collect them in a single
- Create a
seedercommand line tool that can run the seeds against a database.
First, to define a small
Seed type that would be coupled to the
Next, we need to define a path where we’ll store the seeds and how to collect them:
seeds package will contain all instances of
seed.Seed and collect them
All function. This will allow the third component, a CLI tool, to
iterate over them and execute them against a database. Additionally, in the same
seeds package we can have separate files for seeding various types of data.
The usage of the function in
The example above is contrived, but it can work really well if you have to compose seeds using multiple such functions.
Last, a very simple command line tool that can running the seeds we defined:
The binary produced by this is quite a simple one: loads all of the seeds using
seeds.All function, iterates over the collection and executes their
function. If an error occurs, the whole program bombs.
That’s it. Very thin and simple way to abstract away your database seeds using Gorm. Before you go, let me know in the comments how you approach database seeding.