@@ -1539,36 +1539,35 @@ defmodule AshPostgres.MigrationGenerator do
15391539 ) ,
15401540 do: false
15411541
1542- # Place AddUniqueIndex after the last AddAttribute for the same table so it
1543- # appears before AlterAttributes (issue #236).
1542+ # Place AddUniqueIndex after a specific attribute (by source) for the same
1543+ # table so it appears before AlterAttributes (issue #236).
15441544 defp after? (
15451545 % Operation.AddUniqueIndex {
1546- insert_after_attribute_order: max_order ,
1546+ insert_after_attribute_source: source ,
15471547 table: table ,
15481548 schema: schema
15491549 } ,
15501550 % Operation.AddAttribute {
15511551 table: table ,
15521552 schema: schema ,
1553- attribute: % { order: order }
1553+ attribute: % { source: source }
15541554 }
15551555 )
1556- when not is_nil ( max_order ) and order == max_order ,
1556+ when not is_nil ( source ) ,
15571557 do: true
15581558
15591559 defp after? (
15601560 % Operation.AddUniqueIndex {
1561- insert_after_attribute_order: max_order ,
1561+ insert_after_attribute_source: source ,
15621562 table: table ,
15631563 schema: schema
15641564 } ,
15651565 % Operation.AddAttribute {
15661566 table: table ,
1567- schema: schema ,
1568- attribute: % { order: order }
1567+ schema: schema
15691568 }
15701569 )
1571- when not is_nil ( max_order ) and order != max_order ,
1570+ when not is_nil ( source ) ,
15721571 do: false
15731572
15741573 defp after? (
@@ -2333,22 +2332,26 @@ defmodule AshPostgres.MigrationGenerator do
23332332 end )
23342333 end
23352334 |> Enum . map ( fn identity ->
2336- orders =
2335+ { insert_after_attribute_source , _best_index } =
23372336 identity . keys
2338- |> Enum . map ( & Enum . find_index ( snapshot . attributes , fn attr -> attr . source == & 1 end ) )
2339- |> Enum . reject ( & is_nil / 1 )
2337+ |> Enum . reduce ( { nil , - 1 } , fn key , { best_source , best_index } ->
2338+ case Enum . find_index ( snapshot . attributes , & ( & 1 . source == key ) ) do
2339+ nil ->
2340+ { best_source , best_index }
23402341
2341- insert_after_attribute_order =
2342- case orders do
2343- [ ] -> nil
2344- _ -> Enum . max ( orders )
2345- end
2342+ idx when idx > best_index ->
2343+ { key , idx }
2344+
2345+ _ ->
2346+ { best_source , best_index }
2347+ end
2348+ end )
23462349
23472350 % Operation.AddUniqueIndex {
23482351 identity: identity ,
23492352 schema: snapshot . schema ,
23502353 table: snapshot . table ,
2351- insert_after_attribute_order: insert_after_attribute_order ,
2354+ insert_after_attribute_source: insert_after_attribute_source ,
23522355 concurrently: opts . concurrent_indexes
23532356 }
23542357 end )
0 commit comments