Class: Moneta::Adapters::Sqlite

Inherits:
Moneta::Adapter show all
Includes:
IncrementSupport
Defined in:
lib/moneta/adapters/sqlite.rb

Overview

Sqlite3 backend

Instance Attribute Summary

Attributes inherited from Moneta::Adapter

#backend

Instance Method Summary collapse

Methods included from IncrementSupport

included

Methods inherited from Moneta::Adapter

backend, backend_block, backend_required?

Methods included from Config

#config, 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



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
52
53
# File 'lib/moneta/adapters/sqlite.rb', line 24

def initialize(options = {})
  super

  backend.busy_timeout(config.busy_timeout)
  backend.execute("create table if not exists #{config.table} (k blob not null primary key, v blob)")

  if journal_mode = config.journal_mode
    backend.journal_mode = journal_mode.to_s
  end

  @stmts =
    [@exists = backend.prepare("select exists(select 1 from #{config.table} where k = ?)"),
     @select = backend.prepare("select v from #{config.table} where k = ?"),
     @replace = backend.prepare("replace into #{config.table} values (?, ?)"),
     @delete = backend.prepare("delete from #{config.table} where k = ?"),
     @clear = backend.prepare("delete from #{config.table}"),
     @create = backend.prepare("insert into #{config.table} values (?, ?)"),
     @keys = backend.prepare("select k from #{config.table}"),
     @count = backend.prepare("select count(*) from #{config.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 <<-SQL)
      insert into #{config.table} values (?, ?)
      on conflict (k)
      do update set v = cast(cast(v as integer) + ? as blob)
      where v = '0' or v = X'30' or cast(v as integer) != 0
    SQL
  end
end

Instance Method Details

#clear(options = {}) ⇒ void

This method returns an undefined value.

Clear all keys in this store

Parameters:

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


89
90
91
92
# File 'lib/moneta/adapters/sqlite.rb', line 89

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

#closeObject

Explicitly close the store

Returns:

  • nil



106
107
108
109
110
# File 'lib/moneta/adapters/sqlite.rb', line 106

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

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



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

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



73
74
75
76
77
# File 'lib/moneta/adapters/sqlite.rb', line 73

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)


164
165
166
167
168
169
170
# File 'lib/moneta/adapters/sqlite.rb', line 164

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



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

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



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

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)


56
57
58
# File 'lib/moneta/adapters/sqlite.rb', line 56

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



61
62
63
64
# File 'lib/moneta/adapters/sqlite.rb', line 61

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)


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

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

  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

  unless pairs.empty?
    query = "replace into #{config.table} (k, v) values" + (['(?, ?)'] * pairs.length).join(',')
    backend.query(query, pairs.flatten).close
  end
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



113
114
115
116
# File 'lib/moneta/adapters/sqlite.rb', line 113

def slice(*keys, **options)
  query = "select k, v from #{config.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



67
68
69
70
# File 'lib/moneta/adapters/sqlite.rb', line 67

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



119
120
121
122
# File 'lib/moneta/adapters/sqlite.rb', line 119

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