@@ -367,28 +367,35 @@ defmodule AshPostgres.MigrationGenerator do
367367name: name
368368} ,
369369table: table
370- } = add ,
371- % AshPostgres.MigrationGenerator.Operation.AlterAttribute {
372- new_attribute: % {
373- name: name ,
374- references: references
375- } ,
376- old_attribute: % {
377- name: name
378- } ,
379- table: table
380- }
370+ } = add
381371| rest
382372] ,
383373acc
384- )
385- when not is_nil ( references ) do
386- new_attribute = Map . put ( add . attribute , :references , references )
374+ ) do
375+ rest
376+ |> Enum . take_while ( fn op ->
377+ op . table == table
378+ end )
379+ |> Enum . with_index ( )
380+ |> Enum . find ( fn
381+ { % Operation.AlterAttribute {
382+ new_attribute: % { name: ^ name , references: references } ,
383+ old_attribute: % { name: ^ name }
384+ } , _ }
385+ when not is_nil ( references ) ->
386+ true
387+
388+ _ ->
389+ false
390+ end )
391+ |> case do
392+ nil ->
393+ streamline ( rest , [ add | acc ] )
387394
388- streamline (
389- rest ,
390- [ % { add | attribute: new_attribute } | acc ]
391- )
395+ { alter , index } ->
396+ new_attribute = Map . put ( add . attribute , :references , alter . new_attribute . references )
397+ streamline ( List . delete_at ( rest , index ) , [ % { add | attribute: new_attribute } | acc ] )
398+ end
392399end
393400
394401defp streamline ( [ first | rest ] , acc ) do
@@ -418,15 +425,15 @@ defmodule AshPostgres.MigrationGenerator do
418425
419426defp group_into_phases (
420427[ % Operation.AlterAttribute { table: table } = op | rest ] ,
421- % { table: table } = phase ,
428+ % Phase.Alter { table: table } = phase ,
422429acc
423430) do
424431group_into_phases ( rest , % { phase | operations: [ op | phase . operations ] } , acc )
425432end
426433
427434defp group_into_phases (
428435[ % Operation.RenameAttribute { table: table } = op | rest ] ,
429- % { table: table } = phase ,
436+ % Phase.Alter { table: table } = phase ,
430437acc
431438) do
432439group_into_phases ( rest , % { phase | operations: [ op | phase . operations ] } , acc )
@@ -445,9 +452,8 @@ defmodule AshPostgres.MigrationGenerator do
445452end
446453
447454defp group_into_phases ( [ operation | rest ] , nil , acc ) do
448- group_into_phases ( rest , nil , [
449- % Phase.Alter { operations: [ operation ] , table: operation . table } | acc
450- ] )
455+ phase = % Phase.Alter { operations: [ operation ] }
456+ group_into_phases ( rest , phase , acc )
451457end
452458
453459defp group_into_phases ( operations , phase , acc ) do