Search code examples
rubysinatradatabase-migrationsequelrake-task

`Sequel::Error: mismatched number of keys` when migration run from rake


I have a Sinatra app using Sequel and a rake task to perform migrations. When I run rake db:migrate I get the following error:

rake aborted!
Sequel::Error: mismatched number of keys: [:rows, :cols] vs [:id]
<path_to_project>/models/grid_pattern.rb:4:in `<class:GridPattern>'

The workaround is to temporarily comment out this line requiring my models in my app file:

Dir.glob('./{models}/*.rb').each { |file| require file }

I know in Sequel I should not depend on models in migrations, but how can I avoid this, as my app needs the models and the rake task needs the app?

My model looks like this:

# grid pattern
class GridPattern < Sequel::Model
  unrestrict_primary_key
  one_to_many :widgets, key: [:rows, :cols]
end

Associated Widgets model:

class Widget < Sequel::Model
  many_to_one :grid_pattern, key: [:rows, :cols]
...

Rakefile:

namespace :db do
  desc 'Migrate DB [to version]'
  task :migrate, [:version] do |_t, args|
    ARGV.each { |a| task a.to_sym }
    RACK_ENV = ARGV[1] if ARGV[1]
    require_relative 'app' # DB now set as per RACK_ENV
    db_name = URI(settings.database).path[1..-1]
    if args[:version]
      puts "Migrating '#{db_name}' to version #{args[:version]}"
      Sequel::Migrator.run(DB, 'db/migrations', target: args[:version].to_i)
    else
      puts "Migrating '#{db_name}' to latest"
      Sequel::Migrator.run(DB, 'db/migrations')
    end
  end
end

Migration file:

...
create_table :grid_patterns do
  Integer :row
  Integer :col
  primary_key [:row, :col], name: :grids_pk
end

create_table :widgets do
  primary_key :id
  Integer :rows
  Integer :cols
  foreign_key [:rows, :cols], :grid_patterns, name: 'challenges_grid_fkey'
end
...

How can I fix this?


Solution

  • You migrations should not require your application/model code, they should only require that DB is set correctly. Modify your application code so that you can require a separate file that sets up DB, and then load only that file when running your migrations.