Skip to content

Commit f33e112

Browse files
committed
Fixed screen repository to use atomic upsert
Ensures the upsert happens only if there isn't a conflict. This also prevents unique constraint issues with duplicate key value. This, unfortunately, introduces code that is a bit more complex and isn't ideal. Leaving these comments in for now in order to address in the future because I think this can be extracted further. Issue: 339 Milestone: patch
1 parent 5e9ab0c commit f33e112

1 file changed

Lines changed: 13 additions & 7 deletions

File tree

‎app/repositories/screen.rb‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,21 @@ def search key, value
4040
.to_a
4141
end
4242

43+
# :reek:TooManyStatements
44+
# rubocop:todo Metrics/AbcSize
4345
def upsert_with_image path, mold, struct
44-
record = find_by name: mold.name, model_id: mold.model_id
45-
record ? update_with_image(path, mold, record) : create_with_image(path, mold, struct)
46+
path.open { |io| struct.upload io, metadata: {"filename" => mold.file_name} }
47+
48+
attributes = {image_data: Sequel.pg_jsonb(struct.image_attributes), **mold.image_attributes}
49+
50+
update = attributes.each_key
51+
.with_object({updated_at: Sequel.function(:now)}) do |column, all|
52+
all[column] = Sequel[:excluded][column]
53+
end
54+
55+
find screen.dataset.insert_conflict(target: %i[model_id name], update:).insert(attributes)
4656
end
57+
# rubocop:enable Metrics/AbcSize
4758

4859
def where(**)
4960
with_associations.where(**)
@@ -54,11 +65,6 @@ def where(**)
5465
private
5566

5667
def with_associations = screen.combine :model
57-
58-
def update_with_image path, mold, record
59-
path.open { |io| record.replace io, metadata: {"filename" => mold.file_name} }
60-
update record.id, image_data: record.image_attributes, **mold.image_attributes
61-
end
6268
end
6369
end
6470
end

0 commit comments

Comments
 (0)