Class: Moneta::Adapters::Sqlite

Inherits:
Object
  • Object
show all
Includes:
Defaults, IncrementSupport
Defined in:
lib/moneta/adapters/sqlite.rb

Overview

Sqlite3 backend

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from IncrementSupport

included

Methods included from Defaults

#[], #[]=, #decrement, #features, #fetch, included, #supports?, #update

Methods included from OptionSupport

#expires, #prefix, #raw, #with

Constructor Details

#initialize(options = {}) ⇒ Sqlite

Returns a new instance of Sqlite

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :file (String)

    Database file

  • :table (String) — default: 'moneta'

    Table name

  • :busy_timeout (Integer) — default: 1000

    Sqlite timeout if database is busy

  • :backend (::Sqlite3::Database)

    Use existing backend instance

  • :journal_mode (String, Symbol)

    Set the journal mode for the connection



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/moneta/adapters/sqlite.rb', line 20

def initialize(options = {})
  @table = options[:table] || 'moneta'
  @backend = options[:backend] ||
    begin
      raise ArgumentError, 'Option :file is required' unless options[:file]
      ::SQLite3::Database.new(options[:file])
    end
  @backend.busy_timeout(options[:busy_timeout] || 1000)
  @backend.execute("create table if not exists #{@table} (k blob not null primary key, v blob)")
  if journal_mode = options[:journal_mode]
    @backend.journal_mode = journal_mode.to_s
  end
  @stmts =
    [@exists  = @backend.prepare("select exists(select 1 from #{@table} where k = ?)"),
     @select  = @backend.prepare("select v from #{@table} where k = ?"),
     @replace = @backend.prepare("replace into #{@table} values (?, ?)"),
     @delete  = @backend.prepare("delete from #{@table} where k = ?"),
     @clear   = @backend.prepare("delete from #{@table}"),
     @create  = @backend.prepare("insert into #{@table} values (?, ?)"),
     @keys    = @backend.prepare("select k from #{@table}"),
     @count   = @backend.prepare("select count(*) from #{@table}")]

  version = @backend.execute("select sqlite_version()").first.first
  if @can_upsert = ::Gem::Version.new(version) >= ::Gem::Version.new('3.24.0')
    @stmts << (@increment = @backend.prepare "insert into \#{@table} values (?, ?)\non conflict (k)\ndo update set v = cast(cast(v as integer) + ? as blob)\nwhere v = '0' or v = X'30' or cast(v as integer) != 0\n")
  end
end

Instance Attribute Details

#backendObject (readonly)



12
13
14
# File 'lib/moneta/adapters/sqlite.rb', line 12

def backend
  @backend
end

Instance Method Details

#clear(options = {}) ⇒ void

This method returns an undefined value.

Clear all keys in this store

Parameters:

  • options (Hash) (defaults to: {})


87
88
89
90
# File 'lib/moneta/adapters/sqlite.rb', line 87

def clear(options = {})
  @clear.execute!
  self
end

#closeObject

Explicitly close the store

Returns:

  • nil



104
105
106
107
108
# File 'lib/moneta/adapters/sqlite.rb', line 104

def close
  @stmts.each {|s| s.close }
  @backend.close
  nil
end

#create(key, value, options = {}) ⇒ Object



93
94
95
96
97
98
99
100
101
# File 'lib/moneta/adapters/sqlite.rb', line 93

def create(key, value, options = {})
  @create.execute!(key,value)
  true
rescue SQLite3::ConstraintException
  # If you know a better way to detect whether an insert-ignore
  # suceeded, please tell me.
  @create.reset!
  false
end

#delete(key, options = {}) ⇒ Object

Delete the key from the store and return the current value

Parameters:

  • key (Object)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (Object)

    current value



71
72
73
74
75
# File 'lib/moneta/adapters/sqlite.rb', line 71

def delete(key, options = {})
  value = load(key, options)
  @delete.execute!(key)
  value
end

#each_keyEnumerator #each_key {|key| ... } ⇒ self

Note:

Not every Moneta store implements this method, a NotImplementedError is raised if it is not supported.

Calls block once for each key in store, passing the key as a parameter. If no block is given, an enumerator is returned instead.

Overloads:

  • #each_keyEnumerator

    Returns An all-the-keys enumerator

    Returns:

    • (Enumerator)

      An all-the-keys enumerator

  • #each_key {|key| ... } ⇒ self

    Yield Parameters:

    • key (Object)

      Each key is yielded to the supplied block

    Returns:

    • (self)


160
161
162
163
164
165
166
# File 'lib/moneta/adapters/sqlite.rb', line 160

def each_key
  return enum_for(:each_key) { @count.execute!.first.first } unless block_given?
  @keys.execute!.each do |row|
    yield row.first
  end
  self
end

#fetch_values(*keys, **options) ⇒ Object #fetch_values(*keys, **options) {|key| ... } ⇒ Array<Object, nil>

Note:

Some adapters may implement this method atomically. The default implmentation uses #values_at.

Behaves identically to #values_at except that it accepts an optional block. When supplied, the block will be called successively with each supplied key that is not present in the store. The return value of the block call will be used in place of nil in returned the array of values.

Overloads:

  • #fetch_values(*keys, **options) {|key| ... } ⇒ Array<Object, nil>

    Returns Array containing the values requested, or where keys are missing, the return values from the corresponding block calls

    Yield Parameters:

    • key (Object)

      Each key that is not found in the store

    Yield Returns:

    • (Object, nil)

      The value to substitute for the missing one

    Returns:

    • (Array<Object, nil>)

      Array containing the values requested, or where keys are missing, the return values from the corresponding block calls



123
124
125
126
127
128
129
130
131
132
133
# File 'lib/moneta/adapters/sqlite.rb', line 123

def fetch_values(*keys, **options)
  return values_at(*keys, **options) unless block_given?
  hash = Hash[slice(*keys, **options)]
  keys.map do |key|
    if hash.key?(key)
      hash[key]
    else
      yield key
    end
  end
end

#increment(key, amount = 1, options = {}) ⇒ Object

Note:

Not every Moneta store implements this method, a NotImplementedError is raised if it is not supported.

Atomically increment integer value with key

This method also accepts negative amounts.

Parameters:

  • key (Object)
  • amount (Integer) (defaults to: 1)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :prefix (String)

    Prefix key (See Transformer)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (Object)

    value from store



78
79
80
81
82
83
84
# File 'lib/moneta/adapters/sqlite.rb', line 78

def increment(key, amount = 1, options = {})
  @backend.transaction(:exclusive) { return super } unless @can_upsert
  @backend.transaction do
    @increment.execute!(key, amount.to_s, amount)
    return Integer(load(key))
  end
end

#key?(key, options = {}) ⇒ Boolean

Exists the value with key

Parameters:

  • key (Object)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :expires (Integer)

    Update expiration time (See Expires)

  • :prefix (String)

    Prefix key (See Transformer)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (Boolean)


54
55
56
# File 'lib/moneta/adapters/sqlite.rb', line 54

def key?(key, options = {})
  @exists.execute!(key).first.first.to_i == 1
end

#load(key, options = {}) ⇒ Object

Fetch value with key. Return nil if the key doesn't exist

Parameters:

  • key (Object)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :expires (Integer)

    Update expiration time (See Expires)

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

  • :sync (Boolean)

    Synchronized load (Cache reloads from adapter, Daybreak syncs with file)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (Object)

    value



59
60
61
62
# File 'lib/moneta/adapters/sqlite.rb', line 59

def load(key, options = {})
  rows = @select.execute!(key)
  rows.empty? ? nil : rows.first.first
end

#merge!(pairs, options = {}) ⇒ self #merge!(pairs, options = {}) {|key, old_value, new_value| ... } ⇒ self

Note:

Some adapters may implement this method atomically, or in two passes when a block is provided. The default implmentation uses #key?, #load and #store.

Stores the pairs in the key-value store, and returns itself. When a block is provided, it will be called before overwriting any existing values with the key, old value and supplied value, and the return value of the block will be used in place of the supplied value.

Overloads:

  • #merge!(pairs, options = {}) ⇒ self

    Parameters:

    • pairs (<(Object, Object)>)

      A collection of key-value pairs to store

    • options (Hash) (defaults to: {})

    Returns:

    • (self)
  • #merge!(pairs, options = {}) {|key, old_value, new_value| ... } ⇒ self

    Parameters:

    • pairs (<(Object, Object)>)

      A collection of key-value pairs to store

    • options (Hash) (defaults to: {})

    Yield Parameters:

    • key (Object)

      A key that whose value is being overwritten

    • old_value (Object)

      The existing value which is being overwritten

    • new_value (Object)

      The value supplied in the method call

    Yield Returns:

    • (Object)

      The value to use for overwriting

    Returns:

    • (self)


136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/moneta/adapters/sqlite.rb', line 136

def merge!(pairs, options = {})
  transaction = if block_given?; @backend.transaction end

  if block_given?
    existing = Hash[slice(*pairs.map { |k, _| k }.to_a)]
    pairs = pairs.map do |key, new_value|
      new_value = yield(key, existing[key], new_value) if existing.key?(key)
      [key, new_value]
    end.to_a
  else
    pairs = pairs.to_a
  end

  query = "replace into #{@table} (k, v) values" + (['(?, ?)'] * pairs.length).join(',')
  @backend.query(query, pairs.flatten).close
rescue
  @backend.rollback if transaction
  raise
else
  @backend.commit if transaction
  self
end

#slice(*keys, **options) ⇒ <(Object, Object)>

Note:

The keys in the return value may be the same objects that were supplied (i.e. Object#equal?), or may simply be equal (i.e. Object#==).

Note:

Some adapters may implement this method atomically. The default implmentation uses #values_at.

Returns a collection of key-value pairs corresponding to those supplied keys which are present in the key-value store, and their associated values. Only those keys present in the store will have pairs in the return value. The return value can be any enumerable object that yields pairs, so it could be a hash, but needn't be.

Parameters:

  • keys (<Object>)

    The keys for the values to fetch

  • options (Hash)

Options Hash (**options):

  • :expires (Integer)

    Update expiration time (See Expires)

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

  • :sync (Boolean)

    Synchronized load (Cache reloads from adapter, Daybreak syncs with file)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (<(Object, Object)>)

    A collection of key-value pairs



111
112
113
114
# File 'lib/moneta/adapters/sqlite.rb', line 111

def slice(*keys, **options)
  query = "select k, v from #{@table} where k in (#{(['?'] * keys.length).join(',')})"
  @backend.execute(query, keys)
end

#store(key, value, options = {}) ⇒ Object

Store value with key

Parameters:

  • key (Object)
  • value (Object)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :expires (Integer)

    Set expiration time (See Expires)

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • value



65
66
67
68
# File 'lib/moneta/adapters/sqlite.rb', line 65

def store(key, value, options = {})
  @replace.execute!(key, value)
  value
end

#values_at(*keys, **options) ⇒ Array<Object, nil>

Note:

Some adapters may implement this method atomically, but the default implementation simply makes repeated calls to #load.

Returns an array containing the values associated with the given keys, in the same order as the supplied keys. If a key is not present in the key-value-store, nil is returned in its place.

Parameters:

  • keys (<Object>)

    The keys for the values to fetch

  • options (Hash)

Options Hash (**options):

  • :expires (Integer)

    Update expiration time (See Expires)

  • :raw (Boolean)

    Raw access without value transformation (See Transformer)

  • :prefix (String)

    Prefix key (See Transformer)

  • :sync (Boolean)

    Synchronized load (Cache reloads from adapter, Daybreak syncs with file)

  • Other (Object)

    options as defined by the adapters or middleware

Returns:

  • (Array<Object, nil>)

    Array containing the values requested, with nil for missing values



117
118
119
120
# File 'lib/moneta/adapters/sqlite.rb', line 117

def values_at(*keys, **options)
  hash = Hash[slice(*keys, **options)]
  keys.map { |key| hash[key] }
end