Aral Balkan

Mastodon icon RSS feed icon

JSDB Migrations

I’m busy working on Basil, the Small Web host, and while it’s nowhere near ready to use yet, I thought I’d try my hand at writing a database migration as they will be necessary once other people start using it.

Basil runs on Site.js and Site.js uses JSDB – JavaScript Database — as its database.

True to its name, JSDB is 100% JavaScript, so, of course, you write your migrations in JavaScript also.

Here’s what the migration I wrote ended up looking like:1

// Migration of Settings table from version 1 to version 2.
//
// Payment providers is now an array instead of an object
// and is pre-populated with the defaults for the None and Token
// provider types.
//
// Also, adds the version attribute for the first time, thereby
// enabling future migrations.

const JSDB = require('@small-tech/jsdb')

const db = JSDB.open('.db')
const settings = db.settings

// Is migration necessary?
if (db.settings.version && db.settings.version >= 2) {
  console.log('Already migrated, exiting.')
  process.exit()
}

// Add version to settings table.
settings.version = 2

// Migrate the payment object to an array, copying over
// the Stripe-related details in version 1.
const payment = settings.payment

settings.payment = {
  // Set the payment provider to the new index of the only one
  // that existed previously (Stripe).
  provider: 2,

  // Create the providers array.
  providers: [
    {
      name: 'None',
      modes: null
    },
    {
      name: 'Tokens',
      modes: null,
      codes: []
    },
    {
      name: 'Stripe',
      modes: [ 'test', 'live' ],
      mode: payment.mode,
      modeDetails: payment.modeDetails,
      currency: payment.currency,
      price: payment.price,
      amount: payment.amount
    }
  ]
}

Neither Site.js nor JSDB has any built-in support for migrations yet so this is something you would write into the logic of your own applications at the moment.

As Basil is still under heavy initial development, I just made it a script and ran it directly.

I’m going to keep experimenting with migrations as I work on Basil and I wouldn’t be surprised if they work their way into JSDB and/or Site.js in time.

Like this? Fund us!

Small Technology Foundation is a tiny, independent not-for-profit.

We exist in part thanks to patronage by people like you. If you share our vision and want to support our work, please become a patron or donate to us today and help us continue to exist.


  1. The actual migration script has some more code to back up the table and handle errors, etc., but this is the gist of it. ↩︎