Creation of a sequence in migration is not reflected in the scheme

I have an application that requires the sequence to be present in the database. I have a migration that does the following:

class CreateSequence < ActiveRecord::Migration def self.up execute "CREATE SEQUENCE sequence" end def self.down execute "DROP SEQUENCE sequence" end end 

This does not modify schema.rb and thus breaks rake db:setup . How can I make a circuit turn on a sequence?

Note. After running rake db:migrate a sequence exists.

+6
source share
3 answers

Rails Migrations, because they are aimed at the table and field schema instead of a complete representation of the database, including stored procedures, functions, seed data.

When you run rake db: setup, this will create db, load the schema, and then load the seed data.

A few solutions for you:

Option 1: Create your own rake command that performs these migrations regardless of the up / down Rails migration. Rails Migrations are regular classes, and you can use them however you like. For instance:

 rake db:create_sequence 

Option 2: Perform your specific migration after loading the schema as follows:

 rake db:setup rake db:migrate:up VERSION=20080906120000 

Choice 3: Create your sequence as input, as it essentially provides data (rather than modifying the schema).

 db/seeds.rb 

Choice 4 and my personal preferences: Migrate to a known good point, including your sequence, and save this empty database. Modify rake db: setup to clone this empty database. This is a bit more complicated and it sacrifices some features - all migrations become reversible, and the migration works on several database providers, etc. In my experience, these are great compromises. For instance:

 rake db:fresh #=> clones the blank database, which you store in version control 
+5
source

All of the above suggestions are good. however, I think I have found a better solution. mostly in your development.rb put

  config.active_record.schema_format = :sql 

For more information, see my answer to this question - rake test does not copy postgres db development with sequences

+2
source

See pg_sequencer gem. It manages the Pg sequences for you as you wish. The only drawback that I see now is that it does not play well with db/schema.rb - Rails generates CREATE SEQUENCE for your tables with the serial field, and pg_sequencer will also generate a sequence. (We fix it.)

0
source

Source: https://habr.com/ru/post/907663/


All Articles