@@ -450,6 +450,115 @@ defmodule AshPostgres.MigrationGeneratorTest do
450450end
451451end
452452
453+ describe "references" do
454+ setup do
455+ on_exit ( fn ->
456+ File . rm_rf! ( "test_snapshots_path" )
457+ File . rm_rf! ( "test_migration_path" )
458+ end )
459+ end
460+
461+ test "references are inferred automatically" do
462+ defposts do
463+ attributes do
464+ uuid_primary_key ( :id )
465+ attribute ( :title , :string )
466+ attribute ( :foobar , :string )
467+ end
468+ end
469+
470+ defposts Post2 do
471+ attributes do
472+ uuid_primary_key ( :id )
473+ attribute ( :name , :string )
474+ end
475+
476+ relationships do
477+ belongs_to ( :post , Post )
478+ end
479+ end
480+
481+ defapi ( [ Post , Post2 ] )
482+
483+ AshPostgres.MigrationGenerator . generate ( Api ,
484+ snapshot_path: "test_snapshots_path" ,
485+ migration_path: "test_migration_path" ,
486+ quiet: true ,
487+ format: false
488+ )
489+
490+ assert [ file ] = Path . wildcard ( "test_migration_path/**/*_migrate_resources*.exs" )
491+
492+ assert File . read! ( file ) =~
493+ ~S[ references(:posts, column: :id, name: "posts_post_id_fkey")]
494+ end
495+
496+ test "when modified, the foreign key is dropped before modification" do
497+ defposts do
498+ attributes do
499+ uuid_primary_key ( :id )
500+ attribute ( :title , :string )
501+ attribute ( :foobar , :string )
502+ end
503+ end
504+
505+ defposts Post2 do
506+ attributes do
507+ uuid_primary_key ( :id )
508+ attribute ( :name , :string )
509+ end
510+
511+ relationships do
512+ belongs_to ( :post , Post )
513+ end
514+ end
515+
516+ defapi ( [ Post , Post2 ] )
517+
518+ AshPostgres.MigrationGenerator . generate ( Api ,
519+ snapshot_path: "test_snapshots_path" ,
520+ migration_path: "test_migration_path" ,
521+ quiet: true ,
522+ format: false
523+ )
524+
525+ defposts Post2 do
526+ postgres do
527+ references do
528+ reference :post , name: "special_post_fkey" , on_delete: :delete , on_update: :update
529+ end
530+ end
531+
532+ attributes do
533+ uuid_primary_key ( :id )
534+ attribute ( :name , :string )
535+ end
536+
537+ relationships do
538+ belongs_to ( :post , Post )
539+ end
540+ end
541+
542+ AshPostgres.MigrationGenerator . generate ( Api ,
543+ snapshot_path: "test_snapshots_path" ,
544+ migration_path: "test_migration_path" ,
545+ quiet: true ,
546+ format: false
547+ )
548+
549+ assert file =
550+ "test_migration_path/**/*_migrate_resources*.exs"
551+ |> Path . wildcard ( )
552+ |> Enum . sort ( )
553+ |> Enum . at ( 1 )
554+
555+ assert File . read! ( file ) =~
556+ ~S[ references(:posts, column: :id, name: "special_post_fkey", on_delete: :delete_all, on_update: :update_all)]
557+
558+ assert File . read! ( file ) =~ ~S[ drop constraint(:posts, "posts_post_id_fkey")]
559+ end
560+ end
561+
453562describe "polymorphic resources" do
454563setup do
455564on_exit ( fn ->