Issues with rake db:migrate - mysql

I am beginner for this Rails . I am working hard
to fix the following error
C:\library>rake db:migrate --trace
(in C:/library)
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:migrate
== CreateBooks: migrating
====================================================
-- create_table(:books)
rake aborted!
An error has occurred, all later migrations canceled:
Mysql::Error: Table 'books' already exists: CREATE TABLE `books` (`id`
int(11) D
EFAULT NULL auto_increment PRIMARY KEY, `created_at` datetime,
`updated_at` date
time) ENGINE=InnoDB
I manual dropped all the tables that didn't fix the problem
Now used rake db:drop db:create db:migrate but still geting rake
aborted message..
C:\library>rake db:drop db:create db:migrate
(in C:/library)
rake aborted!
Mysql::Error: Specified key was too long; max key length is 767 bytes:
CREATE UN
IQUE INDEX `unique_schema_migrations` ON `schema_migrations` (`version`)
Also i dont have schema.rb file.

The first message is probably the result of a migration that failed but wasn't properly backed out. It's a good idea to take a snapshot of your database before you perform migrations so you can restore to a known-good configuration if it messes up.
The second message indicates you're trying to create an index on a field that's "too big" for MySQL to do this. Due to the way MySQL handles UTF-8 characters, each character is allocated three bytes of key space. This means anything longer than 255 characters needs to be given a length limit or it won't work, at least in versions of MySQL that complain about it.
What does seem odd is that it's trying to build the schema_migrations table and failing. Is there anything unusual about your MySQL configuration that might trigger this? Is it an older version? 5.5 or better is recommended.

Related

Localhost launch fails due to pending migration error

Issue: I am unable to launch localhost of the website we are developing in my local system. So I could play with it and write automated tests. Earlier it used to work.
The commands I run usually after Fetching Origin - of the Develop branch through Github app
bundle install
rake db:migrate
rails s
Now, the rake db:migrate is not working, giving me an error
Macs-iMac:mac$ bin/rails db:migrate RAILS_ENV=development
== 20180619223217 CreateCarts: migrating ======================================
-- create_table(:carts)
rails aborted!
StandardError: An error has occurred, all later migrations canceled:
Mysql2::Error: Table 'carts' already exists: CREATE TABLE carts
(id bigint NOT NULL AUTO_INCREMENT PRIMARY KEY, user_id int,
created_at datetime NOT NULL, updated_at datetime NOT NULL)
ENGINE=InnoDB
/Users/mac/.rvm/gems/ruby-2.4.1/gems/mysql2-0.4.10/lib/mysql2/client.rb:120:in
`_query'
/Users/mac/.rvm/gems/ruby-2.4.1/gems/mysql2-0.4.10/lib/mysql2/client.rb:120:in
`block in query'
/Users/mac/.rvm/gems/ruby-2.4.1/gems/mysql2-0.4.10/lib/mysql2/client.rb:119:in
`handle_interrupt'
/Users/mac/.rvm/gems/ruby-2.4.1/gems/mysql2-0.4.10/lib/mysql2/client.rb:119:in
`query'
.. many lines like this..
There are many tables at least 8 of them like "carts" already exists it says.
Following troubleshooting have been done.
I tried to do rake db:reset / rails db:reset - It gave me error like "You are attempting to run a destructive action"
imported new data for the dev table on Sequelpro, then ran rake db:migrate
None of these three commands also worked, same "destructive action" error. rails db:drop, rails db:schema:load, rails db:reset
I went into db/migrate folder, and in-commented the lines that create those 8 issue tables.
This seems to work, able to launch the app, but obviously some menus in the app don't work.
Switching through older versions of the app I had in the system in different feature branches I created months back, is working.
How do I solve this? and get on to launch the app :)
Use rails db:reset DISABLE_DATABASE_ENVIRONMENT_CHECK=1in (1)

Unknown column 'tokens.update_on' when importing mysql dump to new Redmine instance

I'm in the process of upgrading an installation of Redmine from 3.0.3 to 3.3.3.
The process I always follow for this is to install a fresh Redmine on a new machine, import and sqldump from the current one, then copy the important stuff (files/config.yml/database.yml, plugins) over and run all the necessary steps. This has generally worked well in the past.
At the moment, after importing the sqldump, Redmine isn't starting and I'm getting an error I'm not able to figure out.
The mysql import appears to work:
mysql -u 'user' -p'mypassword' redmine < /home/redmine20170608.sql
Then I do the usual steps which all run with no errors:
bundle exec rake redmine:plugins:migrate RAILS_ENV=production
bundle exec rake db:migrate RAILS_ENV=production
bundle exec rake tmp:sessions:clear
bundle exec rake tmp:cache:clear
sudo service httpd restart
When I navigate to myredmine.com I get the "Internal Error" message. Check the logs and the out put is:
ActiveRecord::StatementInvalid (Mysql2::Error: Unknown column 'tokens.updated_on' in 'field list': UPDATE `tokens` SET `tokens`.`updated_on` = '2017-06-09 07:10:56.515511' WHERE `tokens`.`user_id` = 1 AND `tokens`.`value` = '5a229e24fe73e8a43768c46af2275a8b4a60c9b3' AND `tokens`.`action` = 'session'):
app/models/user.rb:425:in `verify_session_token'
app/controllers/application_controller.rb:77:in `session_expired?'
app/controllers/application_controller.rb:67:in `session_expiration'
Migrating to CreateRolesManagedRoles (20150528092912)
Started GET "/" for 72.155.92.149 at 2017-06-09 07:16:14 +0000
Processing by WelcomeController#index as HTML
Completed 500 Internal Server Error in 25ms (ActiveRecord: 1.8ms)
ActiveRecord::StatementInvalid (Mysql2::Error: Unknown column 'tokens.updated_on' in 'field list': UPDATE `tokens` SET `tokens`.`updated_on` = '2017-06-09 07:16:14.896744' WHERE `tokens`.`user_id` = 1 AND `tokens`.`value` = '5a229e24fe73e8a43768c46af2275a8b4a60c9b3' AND `tokens`.`action` = 'session'):
app/models/user.rb:425:in `verify_session_token'
app/controllers/application_controller.rb:77:in `session_expired?'
app/controllers/application_controller.rb:67:in `session_expiration'
This is the code from line 425 of that file:
scope.update_all(:updated_on => Time.now) == 1
Which is inside this section:
# Returns true if token is a valid session token for the user whose id is user_id
def self.verify_session_token(user_id, token)
return false if user_id.blank? || token.blank?
scope = Token.where(:user_id => user_id, :value => token.to_s, :action => 'session')
if Setting.session_lifetime?
scope = scope.where("created_on > ?", Setting.session_lifetime.to_i.minutes.ago)
end
if Setting.session_timeout?
scope = scope.where("updated_on > ?", Setting.session_timeout.to_i.minutes.ago)
end
scope.update_all(:updated_on => Time.now) == 1
end
I usually find the error output for these to be relatively self explanatory but I don't know how to interpret this one.
I've deleted all of the plugins to make sure its not a compatibility issue and still getting the same problem.
The current Redmine is 3.0.3, running on Ruby 1.9.3-p551, Rails 4.2.1 and AWS Linux AMI 2010.03 (which I am advised to move away from).
The new Redmine is 3.3.3, running on Ruby 2.2.5-p319, Rails 4.2.7.1 and CentOS 7.
Any help greatly appreciated.
As discussed in the comments the error is
ActiveRecord::StatementInvalid (Mysql2::Error: Unknown column 'tokens.updated_on'
There's no column called updated_on in Token model and you are trying to update it on line 425
scope.update_all(:updated_on => Time.now) == 1
You need to add migration for that column.
run following command in your terminal from app's root folder,
rails g migration AddUpdatedOnToToken updated_on:datetime
rake db:migrate
The answer was to manually add the required column. The way described in the first answer didn't work - as noted I kept getting permission denied. This is weird because there are only two mysql users and both have access to that database.
So the way to fix this was to log into mysql as the Redmine user and run these commands:
USE mydatabase;
ALTER TABLE tokens ADD updated_on VARCHAR(60);
And the issue was resolved - I was able to continue and access Redmine with no issues.

Mysql2::Error: Table "Admin_Users" already exists

--------------------------EDIT #1--------------------------
I found a way around my problem:
The Problem:
I typo'd "admin_user", when it should have been "admin_users" in my migration, and ran rake db:migrate. Giving an ERROR before completing the migration.
A Solution:
rake db:drop #drops the database
rake db:create #re-creates the database
A Question:
How would I have fixed migrating a typo without dropping my whole database and re-creating it? Obviously I don't want to be deleting data with a real project.
EDIT #2
Answer to my question^:
You can go into your code and comment the code that has been already migrated, which will finish the rest of your migration when you run:
rake db:migrate
END OF EDIT #2
--------------------------END OF EDIT #1--------------------------
I'm coming across a noobie MySQL problem using Ruby On Rails 4.
class AlterUsers < ActiveRecord::Migration
def up
rename_table("users", "admin_users")
add_column("admin_users", "username", :string, :limit => 25, :after => "email")
change_column("admin_users", "email", :string, :limit => 100)
rename_column("admin_users", "password", "hashed_password")
puts "*** Adding an index is next ***"
add_index("admin_users", "username")
end
def down
remove_index("admin_users", "username")
rename_column("admin_users", "hashed_password", "password")
change_column("admin_users", "email", :string, :default => "", :null => false)
remove_column("admin_users", "username")
rename_table("admin_users", "users")
end
end
Then I ran:
rake db:migrate
Which then migrated "Create Users", but gave me an ERROR when hitting the Alter Users Migration:
*** Adding an index is next ***
-- add_index("admin_user", "username")
rake aborted!
StandardError: An error has occurred, all later migrations canceled:
Mysql2::Error: Table 'simple_cms_development.admin_user' doesn't exist: CREATE INDEX `index_admin_user_on_username` ON `admin_user` (`username`)
I then tried:
rake db:migrate:status
Which resulted in:
up 20150911203937 Do nothing yet
up 20150911204213 Create users
down 20150911212536 Alter users
So I figured if I just reverted back to all DOWN status by using:
rake db:migrate VERSION=0
But then gave me another Error:
Mysql2::Error: Unknown table 'users': DROP TABLE `users`
/db/migrate/20150911204213_create_users.rb:16:in `down'
Obviously this is just a practice Database and RoR Project in general, but how can I fix this Error and in the BEST possible way so I won't delete anything important (in future SQL projects).
I've read these threads before posting here:
http://stackoverflow.com/questions/24988889/mysql2error-table-conversations-already-exists
http://stackoverflow.com/questions/27876009/ruby-on-rails-mysql2error-table-pages-already-exists-create-table-pages
Thank you for any answers/advice!
Your question doesn't make sense, your error (and apparent db:migrate output) show a problem because there's no "admin_user" (singular) table, and yet your migration shows add_index("admin_users"... (plural). On top of that the error in the subject of your question is never mentioned in your post. Definitely seems like you've gotten yourself in a mess, my recommendation is to drop the database and start from scratch.

Migration error with devise

Hey I have a problem with my page here. I used a gem 'devise' to create a migration file for "users" I might have forgotten to rake db:migrate after that but I'm really not too sure what I did here to duplicate anything.
I ran the code rails g devise user I may have forgotten to db:migrate and then ran the code rails g devise:views
It's for a TeamTreeHouse project, and I'm sorry if I was too confusing with my question...anyway here is the error message.
== AddDeviseToUsers: migrating ===============================================
-- change_table(:users, :email)
rake aborted!
An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: duplicate column name: email: ALTER TABLE "users" ADD "email" varchar(255) DEFAULT '' NOT NULL
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
It seems you already have an "users" table
Try to run: rake db:reset to run your migrations after drop and recreate your database.
UPDATE
This command will clear all data you have stored (unless is present in your seeds.rb), be careful to use this if you have important data in your database.
his command will clear all data you have stored (unless is present in your seeds.rb), be careful to use this if you have important data in your database.

db:seed not loading models

I'm trying to seed my database with the standard db/seeds.rb method. This works fine on my development machine, but on my server, I get:
$ sudo rake db:seed RAILS_ENV=production --trace
** Invoke db:seed (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:seed
rake aborted!
uninitialized constant Permission
/usr/local/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:2503:in `const_missing'
/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:92:in `const_missing'
/path/.../.../.../.../db/seeds.rb:4
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.4/lib/tasks/databases.rake:215:in `load'
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.4/lib/tasks/databases.rake:215
/usr/local/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake.rb:636:in `call'
...
But when I check in the console, the model does exist:
$ script/console production
Loading production environment (Rails 2.3.4)
>> Permission
=> Permission(id: integer, ..., created_at: datetime, updated_at: datetime)
What am I forgetting?
In a comment to the blog posted linked to above and here again: http://www.builtfromsource.com/2011/02/09/getting-rake-dbseed-and-config-threadsafe-to-play-nice/
Bruce Adams mentions that one can call:
config.threadsafe! unless $rails_rake_task
to only turn on threadsafe when not running a rake task.
But as the issue is really that threadsafe turns off dependency_loading, you can simply add this line after config.threadsafe! to leave it enabled, but still load your environment as you expect.
config.dependency_loading = true if $rails_rake_task
It can be fixed by disabling threadsafe! in the environment configuration.
I just ran across a good approach to this problem in this article. I'll summarize here so people can (hopefully) find it quicker.
The idea is to turn off threadsafe in the production environment, first by editing config/environments/production.rb:
config.threadsafe! unless ENV['THREADSAFE'] == 'off'
You then set THREADSAFE=off when running rake tasks.