Rails migration rollback mistake - how to update schema? - ruby-on-rails

I royally screwed up with version control and deleted a bunch of files including migrations. I tried then to rails generate the files with the same names but then got (error, record already exists). I realized the table must already exist in the database.
If I run rake db:migrate:status I get the following:
up 20150426172505 Remove columns from businesses categories sub categories
up 20150426172902 Change pdf name
up 20150520193556 ********** NO FILE **********
up 20150520194841 ********** NO FILE **********
up 20150527194215 ********** NO FILE **********
How do I get rid of the missing migrations and get the schema to use 20150426172902?

Well, there are two ways you can get rid of those lost migration files.
One is to run the following command:
rake db:migrate:reset db:seed
This will completely drop down your database, re-run all the migration, and run the seeds if you have any.
Second is to run the following query, and directly deleting the lost migration files that you do not want to see around.
DELETE FROM `schema_migrations` WHERE version='<MIGRATION_ID>';

Related

Rails 6, Schema file not matching migration files after switching Git branch

Rails 6, development with sqlite3.
My schema.rb has a file that shouldn't be there: no migration files (On current git branch) says it should be generated. By it's name I can see it's from an earlier branch that I abandoned, and wen't back to try a different approach to building my rails app.
To double check: I get a name error when I try to access the table in the Rails Console, so it's only there in the schema file, but not in the Database itself.
Can I force rails to run and or confirm that current schema is matching the migration files and if not matching, would run the migration?
Edit/Update:
I need to clarify that I have 6 migration files, that I went over to make sure none of them were from the earlier abandoned branch.
(admins is the table at issue)
ActiveRecord::Base.connection.tables
in the rails commandline generates:
["schema_migrations", "ar_internal_metadata", "events", "admins", "details"]
When I do Event I get the columns name and type. But when I do Admin I get
Traceback (most recent call last):
1: from (irb):3
NameError (uninitialized constant Admin)
So the issue is: How do I correctly reset the database to
The schema.rb file is auto-generated from the current state of the database, so just run rails db:migrate to re-generate schema.rb file
running rails db:migrate:reset removed seem to have fixed the issue:
My schema file does not have the 'admins' in it, and it does not show up when running ActiveRecord::Base.connection.tables in rails commandline.
I believe this was caused by Git, as it has the DB in the files: /db/*.sqlite3 and that 'admins' was created on a branch I abandoned earlier and never merged. So it was kept in the database, but the migration files were removed when I went back and created a new branch earlier on the timeline.

Migrations are pending error while everything is up to date

I have a strange issue with migrations. The last migration file is: 20190826113704_add_percentage_account_to_contacts.rb.
The timestamp in schema.rb is ActiveRecord::Schema.define(version: 2019_08_26_113704).
So you would say everything is up to date. When I start the server and go to the site I get the Migrations are pending error. So when I run rails db:migrate I get an error relation "study_agreements" already exists which is correct, there are no migrations pending.
So how can I solve this?
The issue is your database reflects that migration is loaded but somehow the entry in schema_migrations either got deleted(accidentally or through migration rollback).
Steps to solve this issue:
Identify the migration(migration number) from db/migrations where study_agreements relation was introduced. Let's say it is 1234
Now manually create an entry in schema_migrations table in your DB. For example in MySQL you can do "INSERT INTO schema_migrations (version) values(1234)".
Another solution is: Run rake db:migrate after commenting the change or up method of your migration in which study_agreements relation was introduced.
It seems you have already have a table in DB and you have down migrated file in your migrate folder. you can do 2 things here:
Run rails db:schema:load
OR
If you don't have data in your db then run rails db:reset

Ruby on Rails. Why schema.rb builded on existing data through db:schema:dump is almost empty?

I am trying to find the correct (any) method to create an application in Ruby on Rails having an existing database (PostgreSQL) with data and fresh app made with:
rails new --database=postgresql -J --skip-coffee .
I found https://github.com/frenesim/schema_to_scaffold but first I need to have a file with a database structure: schema.rb. I’m looking for a way to do it automatically.
In result of rake db:schema:dumpfile schema.rb is generated, but only with content like that:
ActiveRecord::Schema.define(version: 0) do
enable_extension "plpgsql"
end
And I stuck here. Why that file is empty? Why are there no tables here?
I have a connection with DB and no errors. I did rake db:create before to test. Creation of bases described in database.yml is successful.
At the beginning I used Docker containers and this is my goal. But to exclude the probability of error, I installed the environment in the system (macOS Mojave) based on the socket. And I’ve got the same effect.
How to generate schema.rb with structure of existing database? Or is there different way to build RoR app based on the existing data structure?
Update: Connection with the new database I only did for testing purposes. To verify configuration.
Here's what else I did:
Dump existing structure with
pg_dump --schema-only app_development > db/structure.sql
I changed name in database.yml to have fresh place to import.
rake db:setup created new DB
rake db:structure:load create tables from db/structure.sql file in DB correctly.
But rake db:schema:dump still generate empty file as earlier.
If you have set proper db config you can use rake db:migrate to regenerate the schema file.
edit:
Ok so lets check if I understood correctly:
you have an existing db with tables and data in it
you have brand new rails app
you want to reflect db structure in you schema.rb file
Is that correct? If yes then like I wrote before - without adding any new migrations to your codebase, run rake db:migrate. That task not only applies changes from the migration file but also updates your schema file to be in sync with the actual database.
I've got it! Two days of my life.
File used to import PostgreSQL database has at the beginning:
CREATE SCHEMA employees;
-- and later
CREATE TABLE employees.department;
I thought that since Rails generates database by rake db:structure:load , the file's syntax is correct.
But when I create manually table users in new empty database and then pg_dump that new base I don't have CREATE SCHEMA query there.
And finally rake db:schema:dump fills schema.rb with tables as I want:
create_table "users", id: :serial, force: :cascade do |t|
t.text "name"
end
Because that fresh pg_dumped file has CREATE TABLE public.users query. public.
I think the key is in comments in database.yml file:
# Schema search path. The server defaults to $user,public
#schema_search_path: myapp,sharedapp,public
One picture is more valuable than a thousand words: that's the differences Table users on the right goes to schema.rb after rake db:schema:dump
Thanks guys for the comments. It's made sure me that I do not make a terrible mistake.
It sounds like you did rake db:create which creates a new database for you and then did rake db:schema:dump which generated a schema.rb file for you from the newly created (empty) database.
If you have an existing database that you want to use you will need to modify your database.yml file to connect to it.
If you want to create a new database you will need to generate Active Record database migrations e.g.) rails generate migration CreateProducts name:string part_number:string and then run them rake db:migrate to update your database and generate your schema.rb.

clean up rake db:migrate:status

I'm looking at a production server that gives a lot of output from rake db:migrate:status like
database: important_production
Status Migration ID Migration Name
--------------------------------------------------
.
.
.
up 20140317065716 ********** NO FILE **********
up 20140317070243 Add userid to activities
.
.
.
I feel like it's bad practice to have this kind of 'no file' error since it prevents migrations downwards. But it's also bad practice to mess up someone's production machine, isn't it. Those two migrations listed above, the missing file one actually had it's migration deleted because it was a duplicate of the next down migration.
My resolution for this is to log into the db shell on the production machine, and run:
DELETE FROM schema_migrations WHERE version = 20140317065716;
I'm not 100% this will work or not though and I can't find any supporting documentation on the process of repairing the migration chain for rails apps out there. What are some advisements, caveats, and best practices here?

Why is Rails running a migration that is prior to the schema version?

I have a migration with version number 20120926232105. My schema is at version 20121003190827.
My site is hosted on Heroku, and when I run
heroku run rake db:migrate -a my-app
I get an error that the table it is trying to create in migration 20120926232105 already exists (as it should). I don't get it - isn't the whole point of the schema_migration table to record which was the last successful migration?
This guy explains it pretty well.
Basically, there's a table somewhere called "schema_migrations". Your migration's "version number" is actually just a time stamp. Further, there's no record of a migration with that timestamp in your 'schema_migrations' table. Since the migration exists, and its timestamp wasn't found in the 'schema_migrations' table, Rake knows to run it.
Try grep -r "table_name" db/migrate and see if it's in there twice.

Resources