Sven
Sven

Reputation: 5265

Getting syntax error: expecting token 'EOF', not 'end' and can't figure out why

So, I am trying to implement a way to add database migrations without an ORM/ODM for my SQLite3 database, and the error I'm getting (syntax error: expecting token 'EOF', not 'end') is for this code:

src/project/database/migration/migrations/1.cr:

require "../migration"

module Project
  ver = 1
  migration = Migration.new ver

  migration.register_up |db| do
    db.exec "create table version (version int)"
    db.exec "insert into version values (?)", ver
  end

  migration.register_down |db| do
    db.exec "drop table version"
  end

  Migrations[ver] = migration
end

I can't see any immediate issues with the syntax. This file imports the following file because it needs the class and the line Migrations = [] of Migration:

src/project/database/migration/migration.cr:

require "db"
require "sqlite3"

module Project

  Migrations = [] of Migration

  class Migration
    def initialize(@version : Int)
    end

    # Registers a callback that will be called when the `up`-method is called.
    # The callback must return either `true` for a successful migration,
    # or `false` for a failed migration. If an `up` migration has
    # failed, the `down` migration will be called to restore the database
    # back to its previous state.
    # The callback will receive an instance of `DB::Database`
    #
    # Example:
    #
    # ```
    # migration = Migration.new(1)
    #
    # migration.register_up |db| do
    #   # Advance migration
    # end
    #
    # migration.register_down |db| do
    #   # Recede migration
    # end
    # ```
    def register_up(&block : (DB::Database) -> Bool)
      @up = block
    end

    # Registers a callback that will be called when the `down`-method is called.
    # See the `register_up` method for more information
    def register_down(&block : (DB::Database) -> Bool)
      @down = block
    end

    # Advances DB to the next version
    def up(conn : DB::Database)
      result = @up.call(conn)
      unless result
        # Failed migration, rollback
        @down.call(conn)
        raise Exception.new(`Failed to migrate database to version: #{@version}. Rolling back.`)
      end
    end

    # Recedes DB to the previous version
    def down(conn : DB::Database)
      result = @down.call(conn)
      unless result
        # Failed migration, rollback
        @up.call(conn)
        raise Exception.new(`Failed to migrate database to version: #{@version - 1}. Rolling back.`)
      end
    end
  end

end

Any ideas?

Upvotes: 1

Views: 2068

Answers (1)

Vitalii Elenhaupt
Vitalii Elenhaupt

Reputation: 7326

Syntax mistake is here:

migration.register_up |db| do
  # ...
end

Should be:

migration.register_up do |db|
  # ...
end

And the same in register_down.

See "Yield arguments" section in Blocks and Procs.

Upvotes: 4

Related Questions