Skip to content

Commit ffa9f09

Browse files
authored
Merge pull request #7 from rameerez/fix/postgresql-for-update-count
Fix PostgreSQL FOR UPDATE with COUNT aggregate error
2 parents 2f93f9b + f5bc7c1 commit ffa9f09

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

lib/api_keys/models/api_key.rb

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -312,13 +312,17 @@ def within_key_type_limit
312312
# Use pessimistic locking to prevent race conditions.
313313
# Lock the owner's existing keys of this type/environment while counting.
314314
# This ensures atomic check-then-create semantics.
315-
# Note: .lock(true) generates "FOR UPDATE" in SQL but is the Rails-idiomatic approach.
315+
#
316+
# Note: We use .ids.size instead of .count because PostgreSQL doesn't allow
317+
# FOR UPDATE with aggregate functions (COUNT). By selecting IDs with the
318+
# lock and counting in Ruby, we achieve the same race condition protection.
316319
existing_count = owner.api_keys
317-
.lock(true)
318320
.active
319321
.where(key_type: key_type.to_s)
320322
.where(environment: environment.to_s)
321-
.count
323+
.lock(true)
324+
.ids
325+
.size
322326

323327
if existing_count >= limit
324328
errors.add(:base, "Maximum number of #{key_type} keys (#{limit}) reached for #{environment} environment")

0 commit comments

Comments
 (0)