Skip to content

Commit

Permalink
Cache regexp objects only with option setup_regexp_function = :cached
Browse files Browse the repository at this point in the history
  • Loading branch information
paddor committed Dec 23, 2023
1 parent 755eac1 commit 268aebf
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions lib/sequel/adapters/sqlite.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ def initialize(opts = OPTS)
# static data that you do not want to modify
# :timeout :: how long to wait for the database to be available if it
# is locked, given in milliseconds (default is 5000)
# :setup_regexp_function :: enable use of Regexp objects with SQL
# 'REGEXP' operator (with regexp cache if ':cached')
def connect(server)
opts = server_opts(server)
opts[:database] = ':memory:' if blank_object?(opts[:database])
Expand All @@ -126,10 +128,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])
@regexp_cache = Hash.new{|h,k| h[k] = Regexp.new(k)}
db.create_function("regexp", 2) do |func, regexp_str, string|
func.result = @regexp_cache[regexp_str].match(string) ? 1 : 0
end
setup_regexp_function(db, opts[:setup_regexp_function])
end

class << db
Expand Down Expand Up @@ -203,6 +202,18 @@ def adapter_initialize
@conversion_procs['datetime'] = @conversion_procs['timestamp'] = method(:to_application_timestamp)
set_integer_booleans
end

def setup_regexp_function(db, how)
case how
when :cached
cache = Hash.new{|h,k| h[k] = Regexp.new(k)}
cb = proc { |func, regexp_str, str| func.result = cache[regexp_str].match(str) ? 1 : 0 }
else
cb = proc { |func, regexp_str, str| func.result = Regexp.new(regexp_str).match(str) ? 1 : 0 }
end

db.create_function("regexp", 2, &cb)
end

# Yield an available connection. Rescue
# any SQLite3::Exceptions and turn them into DatabaseErrors.
Expand Down

0 comments on commit 268aebf

Please sign in to comment.