Define order of code blocks being added to a migration

In my resource, I need to add a field that is generated automatically by postgres like this:
postgres do
...

custom_statements do
statement :create_normalized_full_name_field do
up """
alter table users add column normalized_full_name varchar (130) generated always as
(
lower(
btrim(
regexp_replace(
first_name || ' ' || surname, '\\s+', ' ', 'g'
)
)
)
)
stored;
"""

down "alter table users drop column normalized_full_name;"
end
end
end
postgres do
...

custom_statements do
statement :create_normalized_full_name_field do
up """
alter table users add column normalized_full_name varchar (130) generated always as
(
lower(
btrim(
regexp_replace(
first_name || ' ' || surname, '\\s+', ' ', 'g'
)
)
)
)
stored;
"""

down "alter table users drop column normalized_full_name;"
end
end
end
I also want to add a custom index for that field, so I also added this:
postgres do
...

custom_indexes do
index ["normalized_full_name gin_trgm_ops"],
using: "gin",
name: "users_normalized_full_name_gin_trgm_ops_index"
end
end
postgres do
...

custom_indexes do
index ["normalized_full_name gin_trgm_ops"],
using: "gin",
name: "users_normalized_full_name_gin_trgm_ops_index"
end
end
The problem is that ash_postgres will first add the custom index and then the custom statement, meaning that the migration file will fail since postgres can't add a index for a column that is yet to be created inside the table. My workaround for now is to break this into 2 migrations, I first comment the custom_indexes code block and generate a migration, and then I uncomment that block again and generate a new migration. That's fine, but it would be nicer if I could somehow define the order these code blocks are added to my migration file.
2 Replies
ZachDaniel
ZachDaniel2y ago
Id just suggest editing your migrations after generating them The migration generator can’t always figure out the proper order for custom things unfortunately
Blibs
BlibsOP2y ago
That's fine, I will do that

Did you find this page helpful?