Limiting Maximum Index Name Length in Ruby on Rails 7.1

In databases, the index plays an important role in improving query performance and speeding up data retrieval. In previous versions of Rails, auto-generated compound index name were allowed to grow quite long, and this could also lead to an Index name is too long error.

To overcome this issue, Rails 7.1 introduced a change which limits the auto-generated index name to a maximum of 62 bytes. If an index name exceeds this limit, it falls back to a new shorter format.

In the upcoming sections, we will explore this change and how it was handled in the previous versions.

Before

In the previous versions of Rails, if the index name exceeded the maximum length limit imposed by the database, it would throw an Index name is too long error. To illustrate this, we will use a Rails 7 app with Postgres as the database.

In the attached image below, we are trying to create a students_registration table and add a compound index on fields first_name, last_name and registration_date.

Now, Rails is attempting to generate the index name index_students_registration_on_first_name_and_last_name_and_registration_date which exceeds the maximimum limit supported by Postgres.

In the console, we can observe the error message

ArgumentError: Index name
'index_students_registration_on_first_name_and_last_name_and_registration_date' on table
'students_registration' is too long; the limit is 63 characters.

The solution to fix this problem was to add a name option to add_index method and give a custom index name that is kept under 63 characters.

So, we attempted to pass the name option while ensuring it stays within the maximum limit.

The migration proceeded smoothly, and the table was successfully created with the custom index name that we provided.

After

With the introduction of Rails 7.1, a new 62 byte limit has been specified. If the index name exceeds this limit, it will fallback to a short format, along with a hash that ensures uniqueness. Let’s try to run the above migration without providing the name option in a Rails 7.1 app.

The migration was successful, and an index was added with name idx_on_first_name_last_name_registration_date_dbcd383c83

We can observe the difference in the auto-generated index name. It is shorter in length as compared to of previous versions, and a hash is included in the end which will ensure uniqueness in the database.

Need help on your Ruby on Rails or React project?

Join Our Newsletter