Class: Moneta::Adapters::ActiveRecord

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

Overview

ActiveRecord as key/value stores

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Defaults

#[], #[]=, #decrement, #each_key, #features, #fetch, #fetch_values, included, #merge!, #slice, #supports?, #values_at

Methods included from OptionSupport

#expires, #prefix, #raw, #with

Constructor Details

#initialize(options = {}) ⇒ ActiveRecord

Returns a new instance of ActiveRecord

Parameters:

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

Options Hash (options):

  • :backend (Object)

    A class object inheriting from ActiveRecord::Base to use as a table

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

    Table name

  • :connection (Hash/String/Symbol)

    ActiveRecord connection configuration (`Hash` or `String`), or symbol giving the name of a Rails connection (e.g. :production)

  • :create_table (Proc)

    Proc called with a connection if table needs to be created

  • :key_column (Symbol)

    The name of the column to use for keys

  • :value_column (Symbol)

    The name of the column to use for values


47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/moneta/adapters/activerecord.rb', line 47

def initialize(options = {})
  @key_column = options.delete(:key_column) || :k
  @value_column = options.delete(:value_column) || :v

  if backend = options.delete(:backend)
    @connection_pool = backend.connection_pool
    @table = ::Arel::Table.new(backend.table_name.to_sym)
  else
    # Feed the connection info into ActiveRecord and get back a name to use for getting the
    # connection pool
    connection = options.delete(:connection)
    spec =
      case connection
      when Symbol
        connection
      when Hash, String
        # Normalize the connection specification to a hash
        resolver = ::ActiveRecord::ConnectionAdapters::ConnectionSpecification::Resolver.new \
          'dummy' => connection

        # Turn the config into a standardised hash, sans a couple of bits
        hash = resolver.resolve(:dummy)
        hash.delete('name')
        hash.delete(:password) # For security

        # Make a name unique to this config
        name = 'moneta?' + URI.encode_www_form(hash.to_a.sort)

        # Add into configurations unless its already there (initially done without locking for
        # speed)
        unless self.class.configurations.key? name
          self.class.connection_lock.synchronize do
            self.class.configurations[name] = connection \
              unless self.class.configurations.key? name
          end
        end

        name.to_sym
      else
        Rails.env.to_sym if defined? Rails
      end

    # If no connection spec is given, fallback to default connection pool
    @connection_pool =
      if spec
        self.class.retrieve_or_establish_connection_pool(spec)
      else
        ::ActiveRecord::Base.connection_pool
      end

    table_name = (options.delete(:table) || :moneta).to_sym
    create_table_if_not_exists(table_name, &options.delete(:create_table))

    @table = ::Arel::Table.new(table_name)
  end
end

Class Attribute Details

.connection_lockObject (readonly)


18
19
20
# File 'lib/moneta/adapters/activerecord.rb', line 18

def connection_lock
  @connection_lock
end

Instance Attribute Details

#connection_poolObject (readonly)


13
14
15
# File 'lib/moneta/adapters/activerecord.rb', line 13

def connection_pool
  @connection_pool
end

#key_columnObject (readonly)


13
14
15
# File 'lib/moneta/adapters/activerecord.rb', line 13

def key_column
  @key_column
end

#tableObject (readonly)


13
14
15
# File 'lib/moneta/adapters/activerecord.rb', line 13

def table
  @table
end

#value_columnObject (readonly)


13
14
15
# File 'lib/moneta/adapters/activerecord.rb', line 13

def value_column
  @value_column
end

Class Method Details

.establish_connection(spec_name) ⇒ Object


25
26
27
28
29
30
31
32
33
# File 'lib/moneta/adapters/activerecord.rb', line 25

def establish_connection(spec_name)
  connection_lock.synchronize do
    if connection_pool = retrieve_connection_pool(spec_name)
      connection_pool
    else
      connection_handler.establish_connection(spec_name.to_sym)
    end
  end
end

.retrieve_connection_pool(spec_name) ⇒ Object


21
22
23
# File 'lib/moneta/adapters/activerecord.rb', line 21

def retrieve_connection_pool(spec_name)
  connection_handler.retrieve_connection_pool(spec_name.to_s)
end

.retrieve_or_establish_connection_pool(spec_name) ⇒ Object


35
36
37
# File 'lib/moneta/adapters/activerecord.rb', line 35

def retrieve_or_establish_connection_pool(spec_name)
  retrieve_connection_pool(spec_name) || establish_connection(spec_name)
end

Instance Method Details

#clear(options = {}) ⇒ void

This method returns an undefined value.

Clear all keys in this store

Parameters:

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

176
177
178
179
180
181
# File 'lib/moneta/adapters/activerecord.rb', line 176

def clear(options = {})
  with_connection do |conn|
    conn.delete(arel_del)
  end
  self
end

#closeObject

Explicitly close the store

Returns:

  • nil


184
185
186
187
# File 'lib/moneta/adapters/activerecord.rb', line 184

def close
  @table = nil
  @connection_pool = nil
end

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

Note:

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

Atomically sets a key to value if it's not set.

Parameters:

  • key (Object)
  • value (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)

Returns:

  • (Boolean)

    key was set


166
167
168
169
170
171
172
173
# File 'lib/moneta/adapters/activerecord.rb', line 166

def create(key, value, options = {})
  with_connection do |conn|
    conn_ins(conn, key, value)
    true
  end
rescue
  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


129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/moneta/adapters/activerecord.rb', line 129

def delete(key, options = {})
  with_connection do |conn|
    conn.transaction do
      sel = arel_sel_key(key).project(table[value_column]).lock
      value = conn.select_value(sel)

      del = arel_del.where(table[key_column].eq(key))
      conn.delete(del)

      value
    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


144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/moneta/adapters/activerecord.rb', line 144

def increment(key, amount = 1, options = {})
  with_connection do |conn|
    begin
      conn_ins(conn, key, amount)
      amount
    rescue
      conn.transaction do
        # This will raise if the existing value is not an integer
        conn_sel_int_value(conn, key)
        raise "No row updated" \
          unless conn_upd(conn, key, ::Arel.sql("#{value_column} + #{amount}")) == 1
        conn_sel_int_value(conn, key)
      end
    end
  end
rescue
  # This handles the "no row updated" issue, above
  tries ||= 0
  if (tries += 1) <= 3; retry else raise 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)

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

def key?(key, options = {})
  with_connection do |conn|
    sel = arel_sel_key(key).project(::Arel.sql('1'))
    result = conn.select_all(sel)
    !result.empty?
  end
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


114
115
116
117
118
# File 'lib/moneta/adapters/activerecord.rb', line 114

def load(key, options = {})
  with_connection do |conn|
    conn_sel_value(conn, key)
  end
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


121
122
123
124
125
126
# File 'lib/moneta/adapters/activerecord.rb', line 121

def store(key, value, options = {})
  with_connection do |conn|
    conn_ins(conn, key, value) unless conn_upd(conn, key, value) == 1
  end
  value
end