Skip to content

Instantly share code, notes, and snippets.

@dgmike
Last active November 18, 2021 12:09
Show Gist options
  • Save dgmike/f60b37b980c1caeebd09a463561e5d21 to your computer and use it in GitHub Desktop.
Save dgmike/f60b37b980c1caeebd09a463561e5d21 to your computer and use it in GitHub Desktop.
Migrations thinking

Looking a post from serokell about elixir's library called ecto.

In the post he presents an migration:

defmodule Blog.Repo.Migrations.Initial do
  use Ecto.Migration

  def change do
    create table ("users") do
      add :username, :string

      timestamps()
    end

    create table ("posts") do
      add :user_id, references (:users)
      add :post_text, :text

      timestamps()
    end

    create table ("comments") do
      add :user_id, references (:users)
      add :post_id, references (:posts)
      add :comment_text, :text

      timestamps()
    end
  end
end

⚠️ Attention This approach do not exists in any library yet.

How about transport it to nodejs/sequelize?

module.exports = {
  change({ createTable }) {
    createTable('users', ({ addColumn, timestamps }, { STRING }) => {
      addColumn('username', STRING)
      timestamps()
    })

    createTable('posts', ({ addColumn, timestamps, references }, { TEXT }) => {
      addColumn('user_id', references('users'))
      addColumn('post_text', TEXT)
      timestamps()
    })

    createTable('comments', ({ addColumn, timestamps, references }, { TEXT }) => {
      addColumn('user_id', references('users'))
      addColumn('post_id', references('posts'))
      addColumn('comment_text', TEXT)
      timestamps()
    })
  }
}

Hmmmm... sounds promissor, but if we make it more nodejs like, using chains?

module.exports = {
  change({ create, ref }, { STRING, TEXT }) {
    create('users')
      .add('username', STRING(32))
      .timestamps()

    create('posts')
      .add('user_id', ref('users'))
      .add('post_text', TEXT)
      .timestamps()

    create('comments')
      .add('user_id', ref('users'))
      .add('post_id', ref('users'))
      .add('comment_text', TEXT)
      .timestamps()
  }
}

The idea is exports migration and it only need to have change and not up/down only.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment