Git reset and delete branch not reverting back properly - ruby-on-rails

I created a new branch called user-microposts. I proceeded to mess something up on creating a model. I tried going back to the last commit using:
git reset --hard cb166caa1c70004f77eed6229168b06ad249a4ba
which gave back:
HEAD is now at cb166ca Eliminate an unnecessary assignment
So I tried redoing the Migrate, which gave me this error:
SQLite3::SQLException: table "microposts" already exists: CREATE TABLE "microposts"
....
I was surprised because I thought if I went back to the previous commit, it would be like nothing happened.
So I reverted back to master branch and deleted the branch in which I made any changes.
I then created a new branch, and tried to create another model and run rake db:migrate. Again I got the same error
SQLite3::SQLException: table "microposts" already exists: CREATE TABLE "microposts"
....
I recently tried to manually delete any file with microposts in it. Again with no such luck.
I keep getting the same error. I thought the purpose of both the git branch and/or git reset would prevent this scenario, so I am very confused. Any help would be appreciated

It would be unusual for your database to be under source control. Thus, if you revert your source you will likely have inconsistencies between the database and the source. The solution has a few options:
delete the database and recreate it
rollback the database to match the source
For both of the above you'd use the typical 'rake db' type commands.

Related

Can I delete an empty EF Migration safely

I've just reviewed a colleague's work and there is an empty EF migration in his PR (up and down methods contain no code). There is another migration after this with DB modifications.
I believe that this empty migration can be deleted on the basis that it does absolutely nothing. There should be a corresponding entry in the _MigrationHistory table, which can also be deleted safely, in my opinion.
My colleagues believe that it should be left in there "just in case".
Are there any EF experts who can say which approach is best, and why?
Тhe truth is somewhere in the middle. You can delete it, but do not delete the migration file directly.
-> Removing A Migration
The following command removes a migration:
[Command Line]
dotnet ef migrations remove
[Package Manager Console]
remove-migration
You will use this command to remove the latest migration. This will remove the class file that was generated for the latest migration and it will also revert the ModelSnapshot file back to the state of the previous migration. If there are no pending migrations, an exception will be raised. If you want to remove a migration that has been committed, you must reverse the migration first (see below).
You should always use commands to remove a migration instead of simply deleting the migration code file, otherwise the snapshot and migrations will fall out of sync with eachother. Then future migrations will be based on a model that is incorrect. Nevertheless, the remove command will recognise if migration files have been deleted and will revert the snapshot accordingly.
If you need to remove a migration that was generated before the most recent one, you must remove all sunsequent migrations first, then adjust the model and then create a new migration to cater for the changes.
Sores: https://www.learnentityframeworkcore.com/migrations

Deleted Migration Files and Heroku

I asked about this once already, but I didn't get a working response, and I may have a better way of asking this question.
Long story short, I've deleted some problematic migration files, (the problem is coming from out-of-order migration files; there is an add_column_to_stocks before a create_stocks file), but for whatever reason, heroku continues to want to migrate these old, deleted files. I have no idea where these files are being stored.
If I do a heroku db:migrate:status, this is the response:
Status Migration ID Migration Name
--------------------------------------------------
up 20171231042756 Create articles
up 20171231044214 Add description to articles
up 20180116183526 Create users
up 20180116191414 Add user to articles
up 20180116195212 Add password digest to users
up 20180305082108 Create categories
up 20180305090315 Create article categories
down 20180515064500 Add latest price to stocks
down 20180517202216 Add timetables to stock
down 20180517205823 Add updatedtime to stocks
down 20180521021514 Create user stocks
The problems start at the first down file.
My local migration folder looks more like this:
20171231042756 Create articles
20171231044214 Add description to articles
20180116183526 Create users
20180116191414 Add user to articles
20180116195212 Add password digest to users
20180305082108 Create categories
20180305090315 Create article categories
20180515064499 Create stocks.rb
20180521021514 Create user stocks.rb
No matter what changes I make to my local migration files, it continues to want to migrate these problematic files, so I always get back the response:
PG::UndefinedTable: ERROR: relation "stocks" does not exist
: ALTER TABLE "stocks" ADD "latest_price" decimal
I tried getting into the heroku psql console and deleting them manually, but a delete from schema_migrations where version = 20180515064500 brings back a DELETE 0 response, meaning it hasn't deleted anything.
I'm friggen stumped and I've spent about a week and a half beating my head in over this.
Thank you all in advance!! Any help is appreciated.
File with migration number 20180515064500 should be gone as it is attempting to modify the table which doens't exist.
Remove the files which are breaking the migrations:
git rm db/migrate/20180515064500*.rb
and deploy on heroku.
Look if in your db files, your version of rails is indicated there (5.2 for example):
In your files that are in down mode.
class CurrencyCreateUsers <ActiveRecord :: Migration [5.2]
then rake db: migrate

Reorder/change timestamp on migration files

One of my migration files is referencing another table/model that will will be created further down the migration sequence.
Postgres doesn't like that:
PG::UndefinedTable: ERROR: relation "users" does not exist
So I wonder if there are any potential problems to manually reorder the migration files (by inventing new timestamps/prefixes)?
The affected tables are already down migrated.
When you run rake db:migrate command it compares schema_migrations table and migration files located in db/migrate folder. All the migrations which were not executed receive MigrationClass#up call then.
So starting from the point when your code is already published and/or migrations are run by other users, changing your migrations timestamps/names may lead to unprocessable migration procedure (as schema_migrations will treat a migration with changed timestamp as new, unprocessed one, and try to process it "again"). Possible workaround for this would be to comment the contents of up method for a while and uncomment it back after migrations are done. For fun you can also manipulate schema_migrations table directly from your db console (adding or removing necessary records). Both of these ways smells like a hack though.
Until then... Everything should work flawlessly.
This is what worked for me for this same situation, even though it's a hack.
Rails runs migrations in order of the timestamp, and Rails tracks which migrations have been run by the timestamp part of the migration file name, but not by the rest of the file name. So if you need to change the order of two migrations because the earlier one references the later one you can simply switch the 14 digit timestamp portion of the filenames by renaming both migration files. If the timestamp is off by even one digit Rails will think it's a new migration so write them down before changing them.

Heroku deployment issue with deleted table

I am trying to deploy to Heroku for the first time. During database migration I get error:
PG::UndefinedTable: ERROR: table "new_shops" does not exist
: DROP TABLE "new_shops"/app/vendor/bundle/ruby/2.1.0/gems/activerecord-new4.1.6/lib/active_record/connection_adapters/postgresql/database_statements.rb:128:
in `async_exec'
new_shops is a table I thought I deleted with everything related to it (I followed instructions I've found here, although don't remember exactly what I did), but obviously I didn't.
Table itself is dropped, but something else is there. I am a newbie, so I have no idea what to do now or where to look.
What is the best way to destroy everything related to this table?
The table probably doesn't exist. You can check by running:
heroku pg:psql
\d new_shops
If it doesn't exist you should comment or remove the migration that is trying to drop the table.

Rails DB Migration Error: relation already exists

I am getting an error when I try to migrate my db. I don't entirely remember how I got here, but I believe I:
created new branch, scaffolded 'Requests', db:migrated, switched back to master, and merged branch
created another branch, did some stuff, db:migrated, and everything was working fine.
pulled from heroku postgres database so i could test out if things worked with actual data. then tried db migrating, but gave me this error:
rake db:migrate
== CreateRequests: migrating =================================================
-- create_table(:requests)
NOTICE: CREATE TABLE will create implicit sequence "requests_id_seq1" for serial column "requests.id"
rake aborted!
An error has occurred, this and all later migrations canceled:
PG::Error: ERROR: relation "requests" already exists
: CREATE TABLE "requests" ("id" serial primary key, "title" character varying(255), "content" text, "category" character varying(255), "status" character varying(255), "requested_track_id" integer, "created_at" timestamp, "updated_at" timestamp)
Any ideas?
I'm not sure exactly what pull strategy you used, but if we make two reasonable assumptions about your pull strategy:
it doesn't drop the database but just overwrites tables, since this requires less permissions.
it is operating in a sort of 'archive mode', meaning it doesn't drop tables on the destination just because they don't exist on the source. Think rsync; you have to specify --delete to get what might be your expected behavior with that utility.
If your steps are correct, then what happened is you overwrote the schema_migrations table, so Rails thinks you haven't added the table yet, but neither did your heroku pull drop the table because of #2 above.
Don't create another migration!!! This will fail on everyone elses' computer except yours, but will only run on yours once.
Instead, run rails dbconsole and execute something like DROP TABLE 'requests' (I forget the postgres syntax, might not be exactly that). Then you can run your migrations.
There is another way to avoid dropping a table with data in it.
What I do in those cases is to check which migration is failing.
Suppose you have a file db/migrate/20130908214222_create_requests.rb, and for some reason, ActiveRecord failed in the past when stored this migration in its "tracking system".
To be sure that this is the case, just find, in the schema_migrations table, a row containing a number like this example: 20130908214222
If that row does not exist, you just have to insert a new one:
INSERT INTO schema_migrations(
version
) VALUES (
20130908214222
);
Next time you run rake db:migrate, ActiveRecord will omit this step, and will continue migrating to end without complications.

Resources