Class: CachedConnection

Inherits:
Object
  • Object
show all
Defined in:
lib/db/cached_connection.rb

Constant Summary collapse

DEFAULT_CACHE_TTL =

24 hours in seconds

24 * 60 * 60

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(database_type, config, cache_config = {}) ⇒ CachedConnection

Returns a new instance of CachedConnection.



12
13
14
15
16
17
18
19
# File 'lib/db/cached_connection.rb', line 12

def initialize(database_type, config, cache_config = {})
  @database_type = database_type
  @pool = DatabaseHelper.connect_to_database(database_type, config)
  @tenant_ids = nil
  @ttl = cache_config[:ttl] || DEFAULT_CACHE_TTL
  @cache = get_cache(cache_config)
  @closed = false
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



8
9
10
# File 'lib/db/cached_connection.rb', line 8

def cache
  @cache
end

#closedObject (readonly)

Returns the value of attribute closed.



9
10
11
# File 'lib/db/cached_connection.rb', line 9

def closed
  @closed
end

#database_typeObject (readonly)

Returns the value of attribute database_type.



8
9
10
# File 'lib/db/cached_connection.rb', line 8

def database_type
  @database_type
end

#poolObject (readonly)

Returns the value of attribute pool.



8
9
10
# File 'lib/db/cached_connection.rb', line 8

def pool
  @pool
end

#tenant_ids=(value) ⇒ Object (writeonly)

Sets the attribute tenant_ids

Parameters:

  • value

    the value to set the attribute tenant_ids to.



10
11
12
# File 'lib/db/cached_connection.rb', line 10

def tenant_ids=(value)
  @tenant_ids = value
end

#ttlObject (readonly)

Returns the value of attribute ttl.



8
9
10
# File 'lib/db/cached_connection.rb', line 8

def ttl
  @ttl
end

Instance Method Details

#closeObject



47
48
49
50
# File 'lib/db/cached_connection.rb', line 47

def close
  DatabaseHelper.disconnect_from_database(@database_type, @pool)
  @closed = true
end

#get_poolObject



43
44
45
# File 'lib/db/cached_connection.rb', line 43

def get_pool
  @pool
end

#query(text) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/db/cached_connection.rb', line 21

def query(text)
  raise "Connection is closed" if @closed

  if @cache.nil?
    return DatabaseHelper.run_query_by_database(@database_type, @pool, text)
  end

  key = "#{@tenant_ids}:#{text}"
  cached_result = @cache.get(key)

  if cached_result
    JSON.parse(cached_result)
  else
    new_result = DatabaseHelper.run_query_by_database(@database_type, @pool, text)
    new_result_string = JSON.generate(new_result)
    @cache.set(key, new_result_string, "EX", DEFAULT_CACHE_TTL)
    new_result
  end
rescue StandardError => e
  raise StandardError, e.message
end