From 6ed97f5fe87f4be92e814e03dd2ae69d8172f680 Mon Sep 17 00:00:00 2001 From: Rebecca Le Date: Thu, 4 Dec 2025 14:38:54 +0800 Subject: [PATCH] bugfix: Re-add `bulk_create_index` metadata when running bulk creates This is necessary when running bulk create actions with the `sorted?: true` option, and also retains consistency with other built-in data layers Related to https://github.com/ash-project/ash/issues/2452 --- lib/data_layer.ex | 16 ++++++++++++---- test/bulk_create_test.exs | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/lib/data_layer.ex b/lib/data_layer.ex index 095f2f62..673d3932 100644 --- a/lib/data_layer.ex +++ b/lib/data_layer.ex @@ -2142,8 +2142,12 @@ defmodule AshPostgres.DataLayer do end # Compatibility fallback - Ash.Resource.put_metadata( - result_for_changeset, + result_for_changeset + |> Ash.Resource.put_metadata( + :bulk_create_index, + changeset.context[:bulk_create][:index] + ) + |> Ash.Resource.put_metadata( :bulk_action_ref, changeset.context[:bulk_create][:ref] ) @@ -2159,8 +2163,12 @@ defmodule AshPostgres.DataLayer do end # Compatibility fallback - Ash.Resource.put_metadata( - result, + result + |> Ash.Resource.put_metadata( + :bulk_create_index, + changeset.context[:bulk_create][:index] + ) + |> Ash.Resource.put_metadata( :bulk_action_ref, changeset.context[:bulk_create][:ref] ) diff --git a/test/bulk_create_test.exs b/test/bulk_create_test.exs index c18d8d1a..e24f32e0 100644 --- a/test/bulk_create_test.exs +++ b/test/bulk_create_test.exs @@ -579,4 +579,21 @@ defmodule AshPostgres.BulkCreateTest do end) end end + + describe "bulk_create with sorted?: true" do + test "works without error" do + # This test reproduces https://github.com/ash-project/ash/issues/2452 + # generate_many uses sorted?: true which requires bulk_create_index metadata + results = + Ash.bulk_create!( + [%{title: "post_1"}, %{title: "post_2"}, %{title: "post_3"}], + Post, + :create, + return_records?: true, + sorted?: true + ) + + assert length(results.records) == 3 + end + end end