Skip to content

Commit

Permalink
Fix id default value with sequences
Browse files Browse the repository at this point in the history
  • Loading branch information
etagwerker committed Sep 11, 2024
1 parent a503ac3 commit 316702c
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 36 deletions.
43 changes: 43 additions & 0 deletions db/migrate/20240911015959_add_missing_sequences.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class AddMissingSequences < ActiveRecord::Migration[7.1]
def up
up_sequence('gemmies')
up_sequence('compats')
up_sequence('github_notifications')
up_sequence('lockfiles')
up_sequence('rails_releases')
end

def down
down_sequence('gemmies')
down_sequence('compats')
down_sequence('github_notifications')
down_sequence('lockfiles')
down_sequence('rails_releases')
end

def down_sequence(_table_name)
# In case of rollback, remove the sequence and reset the column default
execute <<-SQL
ALTER TABLE #{_table_name} ALTER COLUMN id DROP DEFAULT;
SQL

execute <<-SQL
DROP SEQUENCE IF EXISTS #{_table_name}_id_seq;
SQL
end

def up_sequence(_table_name)
execute <<-SQL
CREATE SEQUENCE IF NOT EXISTS #{_table_name}_id_seq;
SQL

execute <<-SQL
ALTER TABLE #{_table_name} ALTER COLUMN id SET DEFAULT nextval('#{_table_name}_id_seq');
SQL

# If you have existing data, set the sequence value to the maximum current id to avoid conflicts
execute <<-SQL
SELECT setval('#{_table_name}_id_seq', COALESCE((SELECT MAX(id) FROM #{_table_name}), 1));
SQL
end
end
62 changes: 26 additions & 36 deletions db/schema.rb

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 316702c

Please sign in to comment.