Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions spec/interro_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ struct UserQuery < Interro::QueryBuilder(User)
do: Interro::Update.new(set: {name: name, updated_at: Time.utc})
end

def upsert!(user_templates : Array(Template), name_on_conflict : String) : Int32
insert! user_templates.map(&.to_named_tuple),
on_conflict: Interro::ConflictHandler.new("email",
do: Interro::Update.new(set: {name: name_on_conflict}))
end

def destroy(user : User)
self
.where(id: user.id)
Expand Down Expand Up @@ -457,6 +463,22 @@ describe Interro do
UserQuery.new.find!(id: user.id).name.should eq "Bar"
end

it "can upsert multiple rows" do
templates = [
UserQuery::Template.new(email: "ivy-#{UUID.random}@example.com", name: "Ivy"),
UserQuery::Template.new(email: "jack-#{UUID.random}@example.com", name: "Jack"),
]

# No rows exist yet, so this only inserts; the conflict update does not run.
query.upsert!(templates, name_on_conflict: "ignored").should eq 2
UserQuery.new.find!(email: templates[0].email).name.should eq "Ivy"

# Every row now conflicts on email, so the handler updates each name.
query.upsert!(templates, name_on_conflict: "Updated").should eq 2
UserQuery.new.find!(email: templates[0].email).name.should eq "Updated"
UserQuery.new.find!(email: templates[1].email).name.should eq "Updated"
end

it "can find a row" do
email = "finduser-#{UUID.random}@example.com"
created_user = UserQuery.new.create(email: email, name: "Find User")
Expand Down
3 changes: 2 additions & 1 deletion src/create_many_operation.cr
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ module Interro
if conflict_handler
if (action = conflict_handler.action) && (handler_params = action.params)
if handler_params.responds_to? :each_value
start = params.size
# The VALUES lists consume one placeholder per row per column.
start = params.size * params.first.size
handler_params.each_value do |value|
args << Interro::Any.new(value)
end
Expand Down
Loading