Skip to content

Instantly share code, notes, and snippets.

@spacebat
Created February 9, 2025 06:27
Show Gist options
  • Save spacebat/88f4ea95a4dccb18305f9a0758436bb1 to your computer and use it in GitHub Desktop.
Save spacebat/88f4ea95a4dccb18305f9a0758436bb1 to your computer and use it in GitHub Desktop.
Ash bulk_create upsert does not return an empty stream when the input list is empty
Mix.install(
[
{:ash, "~> 3.0"}
],
consolidate_protocols: false
)
defmodule Accounts.Profile do
use Ash.Resource,
domain: Accounts,
data_layer: Ash.DataLayer.Ets
actions do
defaults [:read, :destroy, create: [:name], update: [:name]]
end
attributes do
uuid_primary_key :id
attribute :name, :string
end
end
defmodule Accounts do
use Ash.Domain, validate_config_inclusion?: false
resources do
resource Accounts.Profile do
define :all_profiles, action: :read
define :profile_by_id, action: :read, get_by: [:id]
define :create_profile, args: [:name], action: :create
define :update_profile, args: [:name], action: :update
define :delete_profile, action: :destroy
end
end
end
IO.puts(
"#{IO.ANSI.yellow()}\nAsh: Bulk upsert multiple records with `return_stream?: true` gives a stream"
)
profile_data = [
%{name: "Neil Armstrong"},
%{name: "Buzz Aldrin"}
]
# This gives a keword list like [ok: <record>, ok: <record>]
profile_data
|> Ash.bulk_create(
Accounts.Profile,
:create,
upsert?: true,
upsert_fields: [:name],
return_stream?: true,
return_records?: true,
domain: Accounts
)
|> Enum.to_list()
|> IO.inspect()
IO.puts(
"#{IO.ANSI.yellow()}\nAsh: Bulk upsert no records with `return_stream?: true` does not give an empty stream"
)
# The following errors out with:
# ** (Protocol.UndefinedError) protocol Enumerable not implemented for type Ash.BulkResult (a struct)
# Got value:
# %Ash.BulkResult{
# status: :success,
# errors: [],
# records: [],
# notifications: nil,
# error_count: 0
# }
[]
|> Ash.bulk_create(Accounts.Profile, :create,
upsert?: true,
upsert_fields: [:name],
return_stream?: true,
return_records?: true,
domain: Accounts
)
|> Enum.to_list()
|> IO.inspect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment