Migration error with devise - mysql

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.

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.

Issues with rake db:migrate

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.

db:schema:load vs db:migrate with capistrano

I have a rails app that I'm moving to another server and I figure I should use db:schema:load to create the mysql database because it's recommended. My problem is that I'm using capistrano to deploy and it seems to be defaulting to rake db:migrate instead. Is there a way to change this or is capistrano using db:migrate for a good reason?
Why to use db:schema:load
I find that my own migrations eventually do some shuffling of data (suppose I combine first_name and last_name columns into a full_name column, for instance). As soon as I do any of this, I start using ActiveRecord to sift through database records, and your models eventually make assumptions about certain columns. My "Person" table, for instance, was later given a "position" column by which people are sorted. Earlier migrations now fail to select data, because the "position" column doesn't exist yet.
How to change the default behavior in Capistrano
In conclusion, I believe deploy:cold should use db:schema:load instead of db:migrate. I solved this problem by changing the middle step which Capistrano performs on a cold deploy. For Capistrano v2.5.9, the default task in the library code looks like this.
namespace :deploy do
...
task :cold do
update
migrate # This step performs `rake db:migrate`.
start
end
...
end
I overrode the task in my deploy.rb as follows.
namespace :deploy do
task :cold do # Overriding the default deploy:cold
update
load_schema # My own step, replacing migrations.
start
end
task :load_schema, :roles => :app do
run "cd #{current_path}; rake db:schema:load"
end
end
Climbing up on the shoulders of Andres Jaan Tack, Adam Spiers, and Kamiel Wanrooij, I've built the following task to overwrite deploy:cold.
task :cold do
transaction do
update
setup_db #replacing migrate in original
start
end
end
task :setup_db, :roles => :app do
raise RuntimeError.new('db:setup aborted!') unless Capistrano::CLI.ui.ask("About to `rake db:setup`. Are you sure to wipe the entire database (anything other than 'yes' aborts):") == 'yes'
run "cd #{current_path}; bundle exec rake db:setup RAILS_ENV=#{rails_env}"
end
My enhancements here are...
wrap it in transaction do, so that Capistrano will do a proper rollback after aborting.
doing db:setup instead of db:schema:load, so that if the database doesn't already exist, it will be created before loading the schema.
That's a great answer from Andres Jaan Tack. I just wanted to add a few comments.
Firstly, here's an improved version of Andres' deploy:load_schema task which includes a warning, and more importantly uses bundle exec and RAILS_ENV to ensure that the environment is set up correctly:
namespace :deploy do
desc 'Load DB schema - CAUTION: rewrites database!'
task :load_schema, :roles => :app do
run "cd #{current_path}; bundle exec rake db:schema:load RAILS_ENV=#{rails_env}"
end
end
I have submitted a feature request to have deploy:load_schema implemented in Capistrano. In that request, I noted that the 'db:schema:load vs. db:migrate' debate has already been covered in the Capistrano discussion group, and there was some reluctance to switch the deploy:cold task to using db:schema:load over db:migrate, since if run unintentionally, the former nukes the entire database whereas the latter would probably complain and bail harmlessly. Nevertheless db:schema:load is technically the better approach, so if the risk of accidental data loss could be mitigated, it would be worth switching.
In Capistrano 3 / Rails 4, the default deploy syntax has changed. You can do this instead:
desc 'Deploy app for first time'
task :cold do
invoke 'deploy:starting'
invoke 'deploy:started'
invoke 'deploy:updating'
invoke 'bundler:install'
invoke 'deploy:db_setup' # This replaces deploy:migrations
invoke 'deploy:compile_assets'
invoke 'deploy:normalize_assets'
invoke 'deploy:publishing'
invoke 'deploy:published'
invoke 'deploy:finishing'
invoke 'deploy:finished'
end
desc 'Setup database'
task :db_setup do
on roles(:db) do
within release_path do
with rails_env: (fetch(:rails_env) || fetch(:stage)) do
execute :rake, 'db:setup' # This creates the database tables AND seeds
end
end
end
end
If you're cautious of invoking the standard deploy tasks manually in the :cold task (as they may change in upcoming version or if you have a custom deploy task), you can also simply call deploy:db_setup before running deploy.
To perform db:schema:load instead of db:setup, you can simply change the rake task, like so:
desc 'Load DB Schema'
task :db_schema_load do
...
execute :rake, 'db:schema:load'
...
end