class Trifle::Stats::Driver::Postgres
Attributes
client[RW]
separator[RW]
table_name[RW]
Public Class Methods
new(client = PG::Connection.new, table_name: 'trifle_stats')
click to toggle source
# File lib/trifle/stats/driver/postgres.rb, line 13 def initialize(client = PG::Connection.new, table_name: 'trifle_stats') @client = client @table_name = table_name @separator = '::' end
Public Instance Methods
_get(key:)
click to toggle source
# File lib/trifle/stats/driver/postgres.rb, line 56 def _get(key:) result = client.exec_params( "SELECT * FROM #{table_name} WHERE key = $1 LIMIT 1;", [key] ).to_a.first return nil if result.nil? JSON.parse(result.try(:fetch, 'data')) rescue JSON::ParserError nil end
_inc_one(key:, name:, value:)
click to toggle source
# File lib/trifle/stats/driver/postgres.rb, line 27 def _inc_one(key:, name:, value:) data = { name => value } query = "INSERT INTO trifle_stats(key, data) VALUES ('#{key}', '#{data.to_json}') ON CONFLICT (key) DO UPDATE SET data = jsonb_set(to_jsonb(trifle_stats.data), '{#{name}}', (COALESCE(trifle_stats.data->>'#{name}','0')::int + #{value})::text::jsonb)" # rubocop:disable Metric/LineLength client.exec(query) end
_set_all(key:, **values)
click to toggle source
# File lib/trifle/stats/driver/postgres.rb, line 40 def _set_all(key:, **values) data = self.class.pack(hash: values) query = "INSERT INTO trifle_stats(key, data) VALUES ('#{key}', '#{data.to_json}') ON CONFLICT (key) DO UPDATE SET data = '#{data.to_json}'" # rubocop:disable Metric/LineLength client.exec(query) end
get(key:)
click to toggle source
# File lib/trifle/stats/driver/postgres.rb, line 47 def get(key:) pkey = key.join(separator) data = _get(key: pkey) return {} if data.nil? self.class.unpack(hash: data) end
inc(key:, **values)
click to toggle source
# File lib/trifle/stats/driver/postgres.rb, line 19 def inc(key:, **values) pkey = key.join(separator) self.class.pack(hash: values).each do |k, c| _inc_one(key: pkey, name: k, value: c) end end
set(key:, **values)
click to toggle source
# File lib/trifle/stats/driver/postgres.rb, line 34 def set(key:, **values) pkey = key.join(separator) _set_all(key: pkey, **values) end