Problems running migrations against users table with Postgresql - ruby-on-rails

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.

Related

Rails rake tasks aborting

I am having trouble running any rake task for my Rails application, and no matter what task I run (rake db:migrate, rake db:reset, etc), I get the following error:
rake aborted!
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: pages: SELECT "pages".* FROM "pages"
I continue getting this error - no matter what rake task I run, and also when I try to run the server:
rails s
gets the following error
Exiting
/Users/terencedevine/.rvm/gems/ruby-2.1.2/gems/sqlite3-1.3.11/lib/sqlite3/database.rb:91:in `initialize': SQLite3::SQLException: no such table: pages: SELECT "pages".* FROM "pages" (ActiveRecord::StatementInvalid)
Everything I find online suggests using rake db:reset but that returns the same error.
One of my more recent migrations I ran was a XXXX_create_pages.rb which has the following code:
class CreatePages < ActiveRecord::Migration
def change
create_table :pages do |t|
t.string :name, null: false, unique: true
t.string :title, null: false
t.text :body
t.timestamps null: false
end
end
end
Any help is greatly appreciated! Thanks!
UPDATE
You need to make sure you actually execute your migrations.
Try rake db:migrate then try to run your server or console again.
Make sure to run rake db:create and then rake db:migrate and that should work.
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: pages: SELECT "pages".* FROM "pages"
From the error message, it's obvious that the pages table does not exist in your database right now. It got deleted somehow even if you did not delete it knowingly.
So, you should create the pages table again by running the corresponding migration:
rake db:migrate
In case your schema version exceeded to migration XXXX_create_pages.rb then rename you migration with greatest timestamp.
Eg.
Your page migration is
20151130203912_create_pages.rb
If your current schema version is
ActiveRecord::Schema.define(:version => 20151211175046)
Then pages migration must be 20151230203912_create_pages.rb
I hope it would be helpful.

How to remove the cancelled migration from the db folder

I want to remove a migration from my application.
I have a migration file 20141105030942_removedate_fromexpense.rb
the class file for the migrations is
class RemovedateFromexpense < ActiveRecord::Migration
def change
remove_column :expenses, :date, :date
end
end
When I give this command:
rake db:migrate:down VERSION=20141105030942
I get the following error:
== 20141105030942 RemovedateFromexpense: reverting ============================
-- add_column(:expenses, :date, :date)
rake aborted!
StandardError: An error has occurred, this migration was canceled:
SQLite3::SQLException: duplicate column name: date: ALTER TABLE "expenses" ADD "date" date/home/sumyvps/.rvm/gems/ruby-1.9.3-p545#railstutorial_rails_4_0/gems/sqlite3-1.3.8/lib/sqlite3/database.rb:91:in `initialize'
db:migrate:status for migration file is as below
up 20141105030942 Removedate fromexpense
Has anyone an idea why this is happening?
You do not need to specify the column type in your migration file. Just the name of the table and the column is enough to remove the column from the table.
Edit your migration file to:
class RemovedateFromexpense < ActiveRecord::Migration
def change
remove_column :expenses, :date
end
end
And then run:
rake db:migrate
This should do the work.
A common task is to rollback the last migration. For example, if you made a mistake in it and wish to correct it. Rather than tracking down the version number associated with the previous migration you can run:
rake db:rollback
This will rollback the latest migration, either by reverting the change method or by running the down method. If you need to undo several migrations you can provide a STEP parameter:
rake db:rollback STEP=3
will revert the last 3 migrations.
First Run:
rails generate migration RemoveDateFromExpense date:date
then rake db:migrate
Hope this help!

heroku migration fails

In heroku I ran rake db:migrate and got the following error
== AlterBodyForDocuments: migrating ==========================================
-- change_column(:documents, :body, :mediumtext)
rake aborted!
An error has occurred, this and all later migrations canceled:
PGError: ERROR: type "mediumtext" does not exist
: ALTER TABLE "documents" ALTER COLUMN "body" TYPE mediumtext
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
this is my AlterBodyForDocuments migration:
class AlterBodyForDocuments < ActiveRecord::Migration
def change
change_column :documents, :body, :mediumtext
end
end
I think mediumtext is a mysql thing
heroku uses postgresql
use :text instead

Rails migration gives error when trying to also create a record in the self.up

I have the following migration:
def self.up
add_column :project_statuses, :system_sequence, :integer, :default => 0, :null => false
ProjectStatus.create :name => 'Declined', :sequence => 35, :system_sequence => 110
...
end
But when I do a rake db:create, rake db:migrate, I get the following error:
== NewProjectStatuses: migrating =============================================
-- add_column(:project_statuses, :system_sequence, :integer, {:default=>0, :null=>false})
-> 0.0029s
rake aborted!
An error has occurred, this and all later migrations canceled:
unknown attribute: system_sequence
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1753:in `block in assign_attributes'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1747:in `each'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1747:in `assign_attributes'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:1567:in `initialize'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:508:in `new'
/Users/ttt/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activerecord-3.1.1/lib/active_record/base.rb:508:in `create'
/[working dir]/db/migrate/20100816100139_new_project_statuses.rb:7:in `up'
The erroneous line number refers to the Project.create :name => ... line.
It seems like the add_column line isn't run at all, even though the output says it is run.
Running a rake db:migrate again runs through the migrations fine though.
Why is this?
Try calling ProjectStatus.reset_column_information after the add_column block.
Rails caches column information (including which columns exist), and I believe what you're hitting here is that you're creating a column, but that doesn't trigger Rails to reset its cache on the list of available columns. As a result, your following line fails, because it doesn't think the column exists.
I'm not sure why the caching is designed this way, but this sort of thing is explicitly mentioned in the example code regarding the use of reset_column_information. I think there's a pretty good chance that's the issue.
That being said, I also generally agree with Michael Durrant, regarding the use of filling the DB with values via migrations. The preferred method is to add your default/seed data to a rake task (which can be run at any arbitrary time), or your seeds.rb file. This is in contrast to a migration, which is only run when the current schema version is older than the specified migration.

What would cause this migration to hang?

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.

Resources