Skip to content

Commit

Permalink
Remove unnecessary object allocation in Model#exists?
Browse files Browse the repository at this point in the history
Use a private constant instead.

Update CHANGELOG for previous commit.
  • Loading branch information
jeremyevans committed Jan 19, 2024
1 parent c457c1e commit e296f6e
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
=== master

* Speed up validates_unique in validation_helpers plugin by using empty? instead of count == 0 (numbata) (#2122)

* Speed up regexp matches in sqlite adapter on Ruby 2.4+ (jeremyevans)

* Add sqlite adapter :regexp_function_cache option for specifying the cache object to use (paddor, jeremyevans) (#2116)
Expand Down
7 changes: 5 additions & 2 deletions lib/sequel/model/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1244,18 +1244,21 @@ def errors
@errors ||= errors_class.new
end

EXISTS_SELECT_ = SQL::AliasedExpression.new(1, :one)
private_constant :EXISTS_SELECT_

# Returns true when current instance exists, false otherwise.
# Generally an object that isn't new will exist unless it has
# been deleted. Uses a database query to check for existence,
# unless the model object is new, in which case this is always
# false.
#
# Artist[1].exists? # SELECT 1 FROM artists WHERE (id = 1)
# Artist[1].exists? # SELECT 1 AS one FROM artists WHERE (id = 1)
# # => true
# Artist.new.exists?
# # => false
def exists?
new? ? false : !this.get(SQL::AliasedExpression.new(1, :one)).nil?
new? ? false : !this.get(EXISTS_SELECT_).nil?
end

# Ignore the model's setter method cache when this instances extends a module, as the
Expand Down
2 changes: 1 addition & 1 deletion spec/model/record_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1425,7 +1425,7 @@ def set_column_value(c, v)
DB.sqls.must_equal ['SELECT 1 AS one FROM items WHERE (id = 1) LIMIT 1']
end

it "should return false when #this.count == 0" do
it "should return false when #this.empty?" do
@model.load(:id=>2).exists?.must_equal false
DB.sqls.must_equal ['SELECT 1 AS one FROM items WHERE (id = 2) LIMIT 1']
end
Expand Down

0 comments on commit e296f6e

Please sign in to comment.