Can't rake migrations: Mysql2::Error: Table doesn't exist - ruby-on-rails

I'm setting up an existing rails app on a new workstations. When I try to rake db:migrate, I get this strange error before any attempt to even create the first table (yes, I started with rake db:create):
$ bundle exec rake db:migrate
rake aborted!
Mysql2::Error: Table 'myapp_dev.usage_roles' doesn't exist: SHOW FULL FIELDS FROM `usage_roles`
# ... followed by a long stack trace
I can't guess why the rake task is trying to show fields from any table before any should exist. I don't even see much mention of this table in the app. Here's the complete grep:
$ grep -r usage_roles .
Binary file ./.git/index matches
./app/models/usage/role.rb: self.table_name = 'usage_roles'
./app/models/usage/user.rb: where(" usage_roles.name in (?)", Usage::Role::SUPPORT_ROLES)
./coverage/index.html: <code class="ruby"> self.table_name = 'usage_roles'</code>
./coverage/index.html: <code class="ruby"> where(" usage_roles.name in (?)", Usage::Role::SUPPORT_ROLES)</code>
./db/migrate/20130112104233_create_usage_roles.rb: execute('CREATE VIEW usage_roles AS SELECT
./db/migrate/20130112104233_create_usage_roles.rb: * FROM clu_enums.usage_roles;')
./db/migrate/20130112104233_create_usage_roles.rb: execute('DROP VIEW IF EXISTS usage_roles;')

I think your issue is directly related to how Factorygirl handles databases. When you set factory_girl_rails to require:false that seems to be the solution.
Take a look at this FactoryGirl screws up rake db:migrate process

Related

Migration not executed from rspec

I created the following migration script (using bundle exec rails generate migration CreateSequenceStudentId):
class CreateSequenceStudentId < ActiveRecord::Migration[6.0]
def change
# Based on: https://schmijos.medium.com/execute-sql-in-rails-migrations-cdb26f51c683
execute 'CREATE SEQUENCE IF NOT EXISTS student_id;'
end
end
Then executed bundle exec rails db:migrate RAILS_ENV=test and it completed. I can access the sequence using psql student_test -c"select nextval('student_id')". Running psql student_test -c"select * from schema_migrations sm" lists 20201122013457 at the very last. No problems so far.
I then wrote the following spec to access the sequence:
sql = "select nextval('student_id')"
p Student.connection.select_all(sql)
And it failed:
# --- Caused by: ---
# PG::UndefinedTable:
# ERROR: relation "student_id" does not exist
# LINE 1: select nextval('student_id')
And I executed psql student_test -c"select nextval('student_id')" one more time and got:
ERROR: relation "student_id" does not exist
LINE 1: select nextval('student_id')
bundle exec rails db:migrate:status RAILS_ENV=test gives:
Status Migration ID Migration Name
--------------------------------------------------
...
up 20201122013457 Create sequence student
So it indicates the migration executed successfully.
psql student_test -c"select * from schema_migrations sm" gives:
version
----------------
20201122013457
20191209013052
20191220005953
20191225001051
20191225001255
20191225001458
...
The new script was executed first. This smells fishy.
Sounds like the migration ran successfully when using db:migrate but not when running rspec. Appreciate any pointers on what I could be doing wrong.
PS: Based on this solution, I have checked if the script name is unique and it is.
I was able to fix your issue by running exact below commands. I found the answer here.
RAILS_ENV=test rake db:drop
RAILS_ENV=test rake db:create
RAILS_ENV=test rake db:migrate
UPDATE:
I found also the way to fix rails db:reset command, you just need to add line config.active_record.schema_format = :sql in your application.rb so info about sequence will be stored in structure.sql. Please take a look that with default schema dump :ruby info about seqeunce is not stored in schema.rb file.
Important: make sure to firstly create structure.sql with rails db:migrate and then run rails db:reset. After just rails db:migrate I'm still getting the error you want to fix.

Migration with SQL sequence is not applied in test environment

I have the current migration
class CreateSlugSequence < ActiveRecord::Migration[5.2]
def up
execute <<-SQL
CREATE SEQUENCE slug_sequence
SQL
end
def down
execute <<-SQL
DROP SEQUENCE slug_sequence
SQL
end
end
I run rails db:migrate
Enter rails c (development mode)
Run ActiveRecord::Base.connection.exec_query("select nextval('slug_sequence')")[0]['nextval']
And get the expected value
But if I enter rails c in test mode, for some reason, the sequence table does not exist
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "slug_sequence" does not exist
I ran ActiveRecord::Migrator.current_version, to check what was the last migration applied and it returns the latest version.
Thanks for the help in advance.
I recommended dropping the test db and recreating it. Although these should remain in sync they sometimes do not and you have to do manual steps to get them together.
RAILS_ENV=test rake db:reset
Weird that it is not working with that, would be interesting to drop a pry debugger in that task and see what is going on. https://github.com/rails/rails/blob/master/activerecord/lib/active_record/railties/databases.rake#L122
Manual steps
RAILS_ENV=test rake db:drop
RAILS_ENV=test rake db:create
RAILS_ENV=test rake db:migrate
I found the way to fix rails db:reset command, you just need to add line config.active_record.schema_format = :sql in your application.rb so info about sequence will be stored in structure.sql. Please take a look that with default schema dump :ruby info about seqeunce is not stored in schema.rb file.
Important: make sure to firstly create structure.sql with rails db:migrate and then run rails db:reset. After just rails db:migrate I'm still getting the error you want to fix.

Pending Migration Error | Cannot Remove Dupe Migrations

I am trying to run a rails server and am coming across this error:
Migrations are pending. To resolve this issue, run: bin/rake db:migrate RAILS_ENV=development
The DB in question is currently empty so no worries of losing data. When I run the code:
bundle exec rake db:migrate
RAILS_ENV=development rake db:migrate
rake db:migrate
I am returned the error:
rake aborted!
ActiveRecord::DuplicateMigrationNameError:
Multiple migrations have the name CreatePosts
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
When running the server, this is returned to my terminal:
Started GET "/" for ::1 at 2015-09-22 11:30:34 -0400
ActiveRecord::PendingMigrationError (
Migrations are pending. To resolve this issue, run:
bin/rake db:migrate RAILS_ENV=development
):
And finally, running rake db:migrate:status returns:
Schema migrations table does not exist yet.
What could possibly be going on? Any help is greatly appreciated!
Output of migrate:status after bin/rake command
Status Migration ID Migration Name
--------------------------------------------------
up 20150922142819 Devise create users
up 20150922143253 Create posts
down 20150922143414 Create posts
down 20150922145906 Acts as votable migration
down 20150922150209 Create comments
down 20150922151035 Acts as follower migration
You must create the database schema/structure before you run migrations. db:schema:load will do this for you:
bin/rake db:schema:load
As for the error "Multiple migrations have the name CreatePosts" - it's as it says. Look in the contents your db/migrate folder for two files that have the same name class CreatePosts within the files - they should be named differently, or the second one should be removed if they are duplicates.
It seems like you have more than one migration with the same name. This is not allowed. If your database is empty, no tables, the best plan is to rename the second one so they don't conflict any more.
Obviously the filenames are unique, but each migration file defines a class, and these classes must be unique as well, plus should match the filename.
Having 201509201949343_create_posts and 201509220293910_create_posts would be a typical conflict here.
You may want to investigate how this came to pass, as having your development schema diverge from the production one is generally a bad idea. Once you resolve the conflict locally, try and update the schema tracking table on production accordingly.

How to resolve db:migrate error SQLite3::SQLException: no such table:

I am trying to use the social network gem inkwell.
I am following the simple instructions here .
I have created a Post, User, Category and Community model using rails generate model
I then configure the models and run
$ rake inkwell:install:migrations
$ rake db:migrate
but end up with the error
SQLite3::SQLException: no such table: posts:
There is a migrate file for this model and I always thought that once you'd created the model then following a migrate it would create a table so I'm a bit confused. Certainly when I rails console Post.all there is no table so this migration isn't happening.
As it is said in the instructions you have to create before the model for users and posts.
So if we assume you have just created the models with a generator, run the migrations for them:
$ rake db:migrate
Creating so the required tables and then:
$ rake inkwell:install:migrations
$ rake db:migrate
Did you try a rake db:reset?
Or delete the database file and:
rake db:create
rake db:migrate

PG::Error: ERROR: relation does not exist (rails 3.1.3) on development vs production

I've blown away my database and am now having problems migrating back to a working database.
The error looks the same as other questions already posted, but I can't figure out how to solve it. What can I change to get my environment back? How did it get like this?
I've verified the database does indeed exist, but the tables are not being created by the migrations step.
The error looks like:
$ RAILS_ENV="development" bundle exec rake db:test:prepare
rake aborted!
PG::Error: ERROR: relation "documents" does not exist
LINE 4: WHERE a.attrelid = '"documents"'::regclass
^
Note: I get the same result attempting any of:
$ bundle exec spec
$ RAILS_ENV="development" bundle exec rake db:migrate
$ RAILS_ENV="development" bundle exec rake db:test:prepare
$ RAILS_ENV="development" bundle exec rake db:schema:load
THEORY ONE:
It may have to do with the way my migrations are written: I have a class Paragraph:
class Paragraph < ActiveRecord::Base
belongs_to :document
validates_presence_of :document, :document_index
validates_uniqueness_of :document_index, scope: [:document_id]
However, originally when developing this I added the model "document" LAST. Should I somehow change the order of the migrations?
THEORY TWO:
When I run any of these with "production" they work fine (except for my tests of course).
Therefore the config error is influenced in some way by the database configuration.
What say you?
Before migrations are run, the whole Rails environment is initialized. So probably there is code executed during initialization process that tries to use the missing relation.
Run the rake task with --trace option to track this code down.

Resources