Skip to content

Commit 38d30b1

Browse files
committed
refactor: inline the create race into the lookup
Put the savepoint and the duplicate-key recovery in the one method that uses them. Bind the identity attributes once, so the same pair no longer repeats across three queries.
1 parent cfe6042 commit 38d30b1

2 files changed

Lines changed: 4 additions & 21 deletions

File tree

‎lib/solid_objects/mailbox.rb‎

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -107,29 +107,15 @@ def with_instance_retry
107107

108108
# @rbs (Reference, Class) -> Instance
109109
def find_or_create_instance(reference, actor_class)
110-
identifier = Instance
111-
.where(actor_type: reference.actor_type, actor_id: reference.actor_id)
112-
.pick(:id)
110+
identity = { actor_type: reference.actor_type, actor_id: reference.actor_id }
111+
identifier = Instance.where(identity).pick(:id)
113112
return lock_instance!(identifier) if identifier
114113

115-
create_locked_instance(reference, actor_class)
116-
end
117-
118-
# @rbs (Reference, Class) -> Instance
119-
def create_locked_instance(reference, actor_class)
120114
Instance.transaction(requires_new: true) do
121-
Instance.create!(
122-
actor_type: reference.actor_type,
123-
actor_id: reference.actor_id,
124-
state: {},
125-
state_version: actor_class.state_version
126-
)
115+
Instance.create!(**identity, state: {}, state_version: actor_class.state_version)
127116
end
128117
rescue ActiveRecord::RecordNotUnique
129-
identifier = database_adapter.share_locked(
130-
Instance.where(actor_type: reference.actor_type, actor_id: reference.actor_id)
131-
).pick(:id)
132-
lock_instance!(identifier)
118+
lock_instance!(database_adapter.share_locked(Instance.where(identity)).pick(:id))
133119
end
134120

135121
# @rbs (Integer?) -> Instance

‎sig/generated/lib/solid_objects/mailbox.rbs‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,6 @@ module SolidObjects
2828
# @rbs (Reference, Class) -> Instance
2929
def find_or_create_instance: (Reference, Class) -> Instance
3030

31-
# @rbs (Reference, Class) -> Instance
32-
def create_locked_instance: (Reference, Class) -> Instance
33-
3431
# @rbs (Integer?) -> Instance
3532
def lock_instance!: (Integer?) -> Instance
3633

0 commit comments

Comments
 (0)