简体   繁体   中英

Ruby on Rails and Oracle sequences

I am trying to move my application from Postgres to Oracle, and I am facing some surprises with Oracle sequence management during seeding of initial data.

=> the objective is to run the same application on various databases (PostGres, Oracle, MSSQL), and this initial data (Admin user, parameters ...) are supposed to have specific id's, starting from 1, assigned regarding the order of creation. Of course, for this specific purpose I could hardcode the id's.

=> Migration and seeding are done by

rake db:migrate RAILS_ENV=ORACLE 
rake db:seed RAILS_ENV=ORACLE

Environments have nothing specific, but the relevant ActiveRecord adapter. With Oracle, seeded data id's do not start from 1 as expected (behaviour in Postgres or in MS SQL), but they start with 10000.

Having a look at sequences created during db migration, they all start with 10000 (LAST_NUMBER).

Is it an Oracle way, or is it an activerecord-oracle_enhanced-adapter way of doing things ?

Why is it set like this ?

Is there a way to start numbering from 1 ?

Thanks for your help,

Best regards,

Fred

Is it an Oracle way, or is it an activerecord-oracle_enhanced-adapter way of doing things ?

This is the adapter's way of doing things. Oracle will by default use the min value of the sequence that is created (so typically 1).

The adapter, as of version 1.6.7 , is setting this in oracle_enhanced_adapter.rb :

self.default_sequence_start_value = 10000

Is there a way to start numbering from 1 ?

You can override this. Passing the :sequence_start_value option to the create_table method allows you to specify your own.

In a migration this might look like:

create_table :table_name, primary_key_trigger: true, sequence_start_value: 1 do |t|
  ...

ID's should have no business value. I would change your approach so that you don't care what the dbms uses.

I would consider adding an additional key that is populated manually by a trigger and/or stored procedures that populate the field, starting at one and incrementing by 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM