Skip to content

Commit

Permalink
Add option regexp_function_cache_class in sqlite adapter
Browse files Browse the repository at this point in the history
This uses an WeakKeyMap (Ruby 3.3+) if available, with Hash as fallback.
  • Loading branch information
paddor committed Jan 5, 2024
1 parent 434f085 commit 3e6d19b
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions lib/sequel/adapters/sqlite.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ def initialize(opts = OPTS)
# it will be called with a string for the regexp and a string
# for the value to compare, and should return whether the regexp
# matches.
# :regexp_function_cache_class :: Defaults to ObjectSpace::WeakKeyMap (avoids
# memory leaks) if available. Hash otherwise.
def connect(server)
opts = server_opts(server)
opts[:database] = ':memory:' if blank_object?(opts[:database])
Expand All @@ -133,7 +135,7 @@ def connect(server)
connection_pragmas.each{|s| log_connection_yield(s, db){db.execute_batch(s)}}

if typecast_value_boolean(opts[:setup_regexp_function])
setup_regexp_function(db, opts[:setup_regexp_function])
setup_regexp_function(db, opts[:setup_regexp_function], opts[:regexp_function_cache_class])
end

class << db
Expand Down Expand Up @@ -208,13 +210,23 @@ def adapter_initialize
set_integer_booleans
end

def setup_regexp_function(db, how)
def setup_regexp_function(db, how, cache_class)
case how
when Proc
# nothing
when :cached, "cached"
cache = Hash.new{|h,k| h[k] = Regexp.new(k)}
how = lambda{|regexp_str, str| cache[regexp_str].match(str)}
cache_class ||= defined?(ObjectSpace::WeakKeyMap) ? ObjectSpace::WeakKeyMap : Hash
cache_class = Object.const_get(cache_class) if cache_class.is_a?(String)
cache = cache_class.new
how = lambda do |regexp_str, str|
if regexp = cache[regexp_str]
regexp.match(str)
else
regexp = Regexp.new(regexp_str)
cache[regexp_str] = regexp
regexp.match(str)
end
end
else
how = lambda{|regexp_str, str| Regexp.new(regexp_str).match(str)}
end
Expand Down

0 comments on commit 3e6d19b

Please sign in to comment.