DEV Community

loading...
Cover image for Database migrations with DB Migrate and a Laravel inspired Schema Builder for Node.js

Database migrations with DB Migrate and a Laravel inspired Schema Builder for Node.js

Loki
Self-taught Software Dev
・2 min read

I recently stopped using PHP/Laravel as my main stack and started using Nodejs.
As someone who comes from a Laravel background, I found myself trying to create migration files the same way i normally would if I was working on a Laravel project. However, this wasn't as easy as I thought it would be.

I did a bit of research, and found db-migrate, a npm library for creating, and running migrations in nodejs. I liked this tool but wasn't happy with the fact that I had to write my migrations schema as a JavaScript object. This isn't a real problem, I just wanted to write my migration schema the same way I did, when I was still using Laravel.

This then led to me creating a Eloquent-like schema builder that works almost the same way as Eloquent's schema builder.

I have published an npm package for the schema builder and hope to get contributions from the open source community.

Getting started

Install the package

npm i @harnessflex/schema-builder
Enter fullscreen mode Exit fullscreen mode

Basic usage

Create a migration file

db-migrate create create_users_table
Enter fullscreen mode Exit fullscreen mode

Define a migration schema

...

const {
    columns,
    id,
    string,
    timestamp,
    timestamps
} = require('@harnessflex/schema-builder');

...

exports.up = function (db) {
    return db.createTable('users', columns([
        id(),
        string('name'),
        string('email').unique(),
        string('password'),
        timestamp('email_verified_at').nullable(),
        timestamps(),
    ]));
};

...
Enter fullscreen mode Exit fullscreen mode

You can also add a foreign key by using the foreign helper method:

...

exports.up = function (db) {
    return db.createTable('posts', columns([
        id(),
        foreign('user_id').references('id').on('users').onDelete('cascade'),
        ...
Enter fullscreen mode Exit fullscreen mode

This adds a user_id column on the posts table that references the id column on the users table.


For the documentations and source code, visit the project repository: https://github.com/harnessflex/schema-builder.

Discussion (0)

Forem Open with the Forem app