Skip to content

Conversation

@BuonOmo
Copy link
Collaborator

@BuonOmo BuonOmo commented Oct 16, 2024

Fixes #347

Copy link

@mmalek-sa mmalek-sa left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still doesn't handle the indexes with where clauses, for example:

ActiveRecord::Schema.define do
  create_table :payments, force: true do |t|
    t.text 'name'
    t.timestamp 'deleted_at'
    t.index 'lower(name::STRING) ASC', name: 'lower_name_index_on_payments', unique: true
    t.index ['name'], name: 'index_payments_on_name', unique: true, where: '(deleted_at IS NULL)'
  end
end

Will result in a schema dump that lacks deleted_at IS NULL:

ActiveRecord::Schema[7.2].define(version: 0) do
  create_table "payments", force: :cascade do |t|
    t.text "name"
    t.datetime "deleted_at", precision: nil
    t.index "lower(name) ASC", name: "lower_name_index_on_payments", unique: true
    t.unique_constraint ["name"], name: "index_payments_on_name"
  end
end

deferrable: deferrable
}

UniqueConstraintDefinition.new(table_name, columns, options)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be:

Suggested change
UniqueConstraintDefinition.new(table_name, columns, options)
ActiveRecord::ConnectionAdapters::PostgreSQL::UniqueConstraintDefinition.new(table_name, columns, options)

@BuonOmo
Copy link
Collaborator Author

BuonOmo commented Oct 24, 2024

Columns with the UNIQUE constraint automatically have an index created with the name <table name>_<columns>_key. To avoid having two identical indexes, you should not create indexes that exactly match the UNIQUE constraint's columns and order.

(https://www.cockroachlabs.com/docs/stable/unique)

I think we can just consider every unique_constraint as an index then.

The UNIQUE constraint depends on the automatically created index, so dropping the index also drops the UNIQUE constraint. Conversely, dropping the UNIQUE constraint also drops the automatically created index.

@BuonOmo BuonOmo force-pushed the fix-unique-constraint branch from 61fdcef to c223ba1 Compare November 12, 2024 15:19
@BuonOmo BuonOmo requested a review from rafiss November 13, 2024 08:50
Copy link
Contributor

@rafiss rafiss left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for this fix!

@rafiss rafiss merged commit 7064053 into master Nov 13, 2024
4 checks passed
@BuonOmo BuonOmo deleted the fix-unique-constraint branch November 13, 2024 15:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Empty or incorrect unique_constraint generation

3 participants