Skip to content
Select documentation version
Navigation
On this page

Seed a Database

A database is as useful as the data that it contains: a fresh, empty database isn’t always the best starting point. We can add a few rows from our migrations using SQL, but we might need to use JavaScript from time to time.

The the Watt’s $db:seed command allows us to run a script that will populate — or “seed” — our database (where $db is the id of your Platformatic DB service).

Example

Our seed script should export a Function that accepts an argument: an instance of @platformatic/sql-mapper.

'use strict'

module.exports = async function seed ({ entities, db, sql }) {
  await entities.graph.save({ input: { name: 'Hello' } })
  await db.query(sql`
    INSERT INTO graphs (name) VALUES ('Hello 2');
  `)
}

For Typescript use the following stub

import { Entities } from '@platformatic/sql-mapper'

const movies: object[] = [{ title: 'Harry Potter' }, { title: 'The Matrix' }]

export async function seed (opts: { entities: Entities }) {
  for (const movie of movies) {
    await opts.entities.movie.save({ input: movie })
  }
}

We can then run the seed script with the Platformatic CLI:

npx wattpm db:seed seed.js
Reading time
1 min read
View as
Markdown
Contribute
Edit this page