What would cause this migration to hang? - ruby-on-rails

I'm trying to upgrade an old 1.2.6 Rails application to 2.3.8, and I'm running into a bit of a snag with migrations. Namely, if I have something like ModelName.create(:foo => "bar") in the migration, the migration doesn't complete. It doesn't hit an infinite loop or anything. It just refuses to complete that migration.
Here's some sample code.
This works:
class CreateNewsArticles < ActiveRecord::Migration
def self.up
create_table :news_articles, :force => true do |t|
t.string "name"
t.string "image"
t.text "body"
t.boolean "featured", :default => "0"
t.integer "position"
t.timestamps
end
# Section.create(:name => 'News Articles', :controller => 'news_articles', :description => 'Add, edit, and delete news articles.')
end
def self.down
drop_table :news_articles
Section.find_by_name('News Articles').destroy
end
end
Uncommenting the Section.create(...) means the migration never completes.
Here's the output from rake db:migrate --trace:
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:migrate
== CreateNewsArticles: migrating =============================================
-- create_table(:news_articles, {:force=>true})
-> 0.0531s
And after commenting out the Section.create
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:migrate
== CreateNewsArticles: migrating =============================================
-- create_table(:news_articles, {:force=>true})
-> 0.0479s
== CreateNewsArticles: migrated (0.0481s) ====================================
** Invoke db:schema:dump (first_time)
** Invoke environment
** Execute db:schema:dump
I've tried this on another computer, and it works. Same version of rake, same version of ruby, and rails is frozen.
rake --VERSION: rake, version 0.8.7, ruby -v: ruby 1.8.6 (2010-02-05 patchlevel 399) [i686-darwin10.3.0], rails -v: Rails 2.3.8
Anyone have any ideas?

You can see the same symptom from a different cause: a migration can hang if you are running:
$ rails console --sandbox
in another process. Quitting the console process allows the migration to complete.

I had same problem .. I found out that there was idle transaction which blocked further queries on this table ..
Run:
heroku pg:ps
To view database processes. You will have to kill idle process:
heroku pg:kill 913 --force -a
(913 is ID of idle process -> change it to your needs

Apparently using ruby 1.8.6-p399 was the culprit. Switching to 1.8.6-p369 solved it.

You might also try defining a bar-bones section model in the migration.

Related

Rake Not Creating Tables

Problem
rake db:migrate is not creating tables in my MySQL database. (Yes, I have read all similar posts, and implemented their suggestions, please continue reading.)
Code
database.yml:
default: &default
adapter: mysql2
encoding: utf8
pool: 5
username: root
password:
host: localhost
port: /tmp/mysql.sock
development:
<<: *default
database: asreport
Line from gemfile (yes, I already gem install'd it too):
gem 'mysql2', '~> 0.3.20'
/appfile/db/migrate/create_users.rb (I've also tried making the second line 'def up'):
class CreateUsers < ActiveRecord::Migration
def up
create_table :users do |t|
t.string :username
t.string :password
t.integer :usertype
t.string :salt
t.timestamps
end
end
end
After I run rake db:drop, rake db:create to refresh, rake db:migrate --trace reads (after this output, 'show tables' in mysql still only shows schema_migrations):
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config (first_time)
** Execute db:load_config
** Execute db:migrate
** Invoke db:_dump (first_time)
** Execute db:_dump
** Invoke db:schema:dump (first_time)
** Invoke environment
** Invoke db:load_config
** Execute db:schema:dump
What I've Tried
First of all, I know that I am connecting to MySQL via Ruby, as db:drop create does indeed create the database itself, just not the table.
I've read all the relevant stack overflow posts I could find on the issue. I've tried rollback, dropping my database directly on SQL, and db:drop/create.
I've tried deleting and recreating my migration script too.
I've run db:migrate multiple times (by itself and after db:drop/create's, rollback's, resets), but the schema_migrations always has 0 entries and my schema.rb file is on version: 0.
You're not following the naming conventions outlined in the Rails Guides.
Specifically, this:
2.1
Creating a Standalone Migration Migrations are stored as files in the db/migrate directory, one for each migration class. The name of
the file is of the form YYYYMMDDHHMMSS_create_products.rb, that is to
say a UTC timestamp identifying the migration followed by an
underscore followed by the name of the migration. The name of the
migration class (CamelCased version) should match the latter part of
the file name. For example 20080906120000_create_products.rb should
define class CreateProducts and
20080906120001_add_details_to_products.rb should define
AddDetailsToProducts. Rails uses this timestamp to determine which
migration should be run and in what order, so if you're copying a
migration from another application or generate a file yourself, be
aware of its position in the order.
Go ahead and try a dummy migration to see the file name convention.
$ bin/rails generate migration AddPartNumberToProducts part_number:string

rake db:migrate not working, no errors

I'm trying to run rake db:migrate on a migration I made to drop a few columns and add a few others.
Here is the migration I'm trying to run:
class Demographics < ActiveRecord::Migration
def change
change_table :demographics do |t|
t.remove_column :demographics, :race
t.remove_column :demographics, :other_race
t.integer :race_id
t.integer :other_race_id
t.remove :demographics, :education
t.integer :education_id
t.remove :other_education
t.integer :other_education_id
end
end
end
Here is the output of: rake db:migrate status --trace
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config (first_time)
** Execute db:load_config
** Execute db:migrate
** Invoke db:_dump (first_time)
** Execute db:_dump
** Invoke db:schema:dump (first_time)
** Invoke environment
** Invoke db:load_config
** Execute db:schema:dump
rake aborted!
Don't know how to build task 'status'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/task_manager.rb:49:in `[]'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:148:in `invoke_task'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:106:in `block (2 levels) in top_level'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:106:in `each'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:106:in `block in top_level'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:115:in `run_with_threads'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:100:in `top_level'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:78:in `block in run'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:165:in `standard_exception_handling'
/var/lib/gems/2.0.0/gems/rake-10.1.1/lib/rake/application.rb:75:in `run'
/var/lib/gems/2.0.0/gems/rake-10.1.1/bin/rake:33:in `<top (required)>'
/usr/local/bin/rake:23:in `load'
/usr/local/bin/rake:23:in `<main>'`enter code here`
You don't need status in the migrate command:
rake db:migrate
should be enough.
You are actually getting an error from rake because of having status in the command:
rake aborted!
Don't know how to build task 'status'
EDIT
Following our discussion I now understand more.
The migration Demographics has already been applied to the database in the past. This is proved by its 14 digit datetime being included in the schema_migrations table.
Migrations are designed to be run once only. They make a change to the database (schema and/or data) and you move on.
When you run rake db:migrate it finds any migration not yet applied to the database (in datetime order from the migration filename), applies it, then puts an entry for the datatime in schema_migrations. Any migration which already has an entry in schema_migrations is ignored.
If you want to make a further change to the database - even to a table created in a previous migration - you should create a new migration, and then use bin rake db:migrate to apply it.
Yes you can backout a previously applied migration - rake db:rollback. Rollbacks will apply in the reverse order the migrations were applied, ie. working backwards from the end of schema_migrations. By default it will only back out the last migration, although you can use the STEP parameter to do more (rake db:rollback STEP=3 for example).
You can also redo a previously applied migraton - rake db:migrate:redo - again with optional STEP parameter. This is really just a shortcut for rollback followed by migrate.
RECOMMENDATION
My recommendation to you would be to put the Demographics migration file back to the way it was before you made the change. This is important in case the migrations need to be all reapplied in the future.
I would now create a new migration to apply the changes to your table:
rails generate migration UseForiegnKeysInDemographics
Make the required alterations; you only need mention the changes to the table:
e.g.
class UseForiegnKeysInDemographics < ActiveRecord::Migration
def change
remove_column :demographics, :race
remove_column :demographics, :other_race
remove_column :demographics, :education
remove_column :demographics, :other_education
add_column :demographics, :race_id, :integer
add_column :demographics, :other_race_id, :integer
add_column :demographics, :education_id, :integer
add_column :demographics, :other_education_id, :integer
end
end
And apply this new migration:
rake db:migrate
I suggest you have a read of the Rails guide on migrations; http://guides.rubyonrails.org/migrations.html as it explains everything better than my brief summary.
Footnote:
As you want to add foreign keys to the demographics table, you might want to consider add_reference instead of add_column. I didn't include this in my example above because I don't know the details of your other tables, but it's well documented in the Rails guide.
I see an issue with your command : rake db:migrate status --trace
You are trying to achieve two things with one command i.e., run the migrations as well as check the status of the migrations with the detailed steps performed.
You can do it in two ways:
1. First Way
To perform the migrations use
rake db:migrate --trace
And then check the status of all your migrations within the application, use
rake db:migrate:status
2. Alternatively
rake db:migrate db:migrate:status --trace
You almost had that but status task is within db:migrate namespace so you need to use db:migrate:status. Here, the first db:migrate will perform the pending migrations whereas db:migrate:status will give the status of all migrations and --trace will give you full backtrace.

Rails migration stops & hangs

I have the following migration:
class AddHyphenatedNameToMenus < ActiveRecord::Migration
def up
add_column :menus, :hyphenated_name, :string, null: false, required: true
end
def down
remove_column :menus, :hyphenated_name
end
end
The rails migration stops mysteriously and hangs.
$ rake db:migrate --trace
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config (first_time)
** Execute db:load_config
** Execute db:migrate
== AddHyphenatedNameToMenus: migrating =======================================
-- add_column(:menus, :hyphenated_name, :string, {:null=>false, :required=>true})
On pressing 'ctrl+c' I get the following error trace:
undefined method `result' for Interrupt:Interrupt/home/.rvm/gems/ruby-1.9.3-p194#abc/gems/activerecord-3.2.13/lib/active_record/connection_adapters/postgresql_adapter.rb:1147:in `translate_exception'
I am unable to find the reason for the same. Any help would be much appreciated. Thanks.

Ruby on Rails - error running server

am currently working on a rails project. When i tried to start rails server its throwing the following error:
=> Booting WEBrick
=> Rails 3.1.3 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
Exiting
/var/lib/gems/1.9.1/gems/activerecord-3.1.3/lib/active_record/connection_adapters
/sqlite_adapter.rb:439:in `table_structure': Could not find table 'dbrick'
(ActiveRecord::StatementInvalid)
My table name is 'dbrick'. I also Tried to rake db:drop and rake db:mirgrate. While migrating its throwing the following error:
rake aborted!
Could not find table 'dbrick'
Tasks: TOP => db:migrate => environment
(See full trace by running task with --trace)
This is my migrate file:
class CreateDbricks < ActiveRecord::Migration
def self.up
create_table :dbricks do |t|
t.text :description
t.string :video
t.string :video_html
t.string :image_id
t.string :option_id
t.boolean :choice
t.string :reach
t.integer :category_id
t.string :user_id
t.datetime :deleted_at
t.timestamps
end
end
def self.down
drop_table :dbricks
end
end
It will be so much help full if any one help me out of this.
Thanks in advance.
I would try :
rake db:schema:load
To load your schema ( to which I believe its finding the error against your DB ).
If that fails, I would manually find the migration that creates your dbrick, locate the name of the file and copy and paste the number in the filename to produce this :
rake db:migrate:down VERSION=123412341234 # <-- where the number is the number you pasted
Look for errors. Occasionally one thing exists already, or doesn't exist already and prevents the migration from running all the way, and consequentially that would be the source of your error. If it goes successfully then rake it back up :
rake db:migrate:up VERSION=123412341234 # <-- where the number is the number you pasted
If it doesn't go successfully, then you'll have to put on your miner's helmet, and get your hands dirty with :
rails dbconsole
Which will take you into your database and you'll have to manually delete whatever table/column is preventing the migration from occurring. Once that is fixed, exit out and rake db:migrate:up!
Have you migrated your database? rake db:migrate
If you have, drop your database (this deletes all data, so be careful - do it if you do not care about losing data in your db)
rake db:drop
This will clear out your database, and your schema. Then
rake db:migrate
This will re-migrate your schema.

Problems running migrations against users table with Postgresql

I am trying to update some default values for new columns set in a migration. However I am getting a Postgres error whenever I try to do anything with the records of users table (except modify its structure). I am using Rails 3.0.7, ruby 1.9.2 and the pg gem version 0.11.0
Here is the migration:
def self.up
add_column :users, :state_machine, :string
add_column :users, :wizard_steps_completed, :integer, :default => "1"
add_column :users, :activated_at, :datetime
User.reset_column_information
User.all.each do |u|
u.update_attributes(:state_machine => "activated", :wizard_steps_completed => 3, :activated_at => u.created_at)
end
end
The columns are added with no problems. however the changes to existing records all fail with the following error:
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:migrate
== AddUserSignupInfo: migrating ==============================================
rake aborted!
An error has occurred, this and all later migrations canceled:
PGError: ERROR: current transaction is aborted, commands ignored until end of transaction block
: SELECT COUNT(*)
FROM pg_tables
WHERE tablename = 'users'
If I attempt to update any orecord it seems to work, I can only make structural changes...
Any ideas?
Turn on postgres logging (Configured in /var/lib/pgsql/data/postgresql.conf and grep for "ERROR REPORTING AND LOGGING"). Or you might want to take the SQL and run it yourself to see what error happens. It could be a constraint thats failing because of your update.

Resources