Class: RedisCounters::Dumpers::Engine
- Inherits:
-
Object
- Object
- RedisCounters::Dumpers::Engine
- Extended by:
- Forwardable
- Includes:
- CallbacksRb, Dsl::Engine
- Defined in:
- lib/redis_counters/dumpers/engine.rb
Overview
Класс дампер (движек дампера) - класс осуществляющий перенос данных счетчика в БД.
Может использоваться как напрямую так и с помощью DSL (см. модуль RedisCounters::Dumpers::Dsl::Engine).
Общий алгоритм работы:
-
Все destinations должны быть в рамках одной БД. Все действия происходят в рамках соединения БД, первой destination.
Example:
dumper = Dumper.build do
name :hits_by_day
fields => {
:company_id => :integer,
:value => :integer,
:date => :date,
:start_month_date => :date,
}
destination do
model CompanyStatisticTotalByDay
take :company_id, :pages, :date
key_fields :company_id, :date
increment_fields :pages
map :pages, :to => :value
condition 'target.date = :date'
end
destination do
model CompanyStatisticTotalByMonth
take :company_id, :pages, :date
key_fields :company_id, :date
increment_fields :pages
map :pages, :to => :value
map :date, :to => :start_month_date
condition 'target.date = :start_month_date'
end
on_before_merge do |dumper, connection|
dumper.common_params = {
:date => dumper.date.strftime('%Y-%m-%d'),
:start_month_date => dumper.date.beginning_of_month.strftime('%Y-%m-%d'),
}
end
end
dumper.process!(counter, Date.yesterday)
В результате все данные счетчика за вчера, будут смерджены в целевые таблицы, по ключевым полям: company_id и date, причем все поля кроме pages, будут просто записаны в таблицы, а поле pages будет инкрементировано с текущим значением, при обновлении. Данные будут удалены из счетчика. Все действия производятся транзакционно, как в БД, так и в Redis.
Constant Summary collapse
- DATE_FORMAT =
'%Y-%m-%d'.freeze
Instance Attribute Summary collapse
-
#common_params ⇒ Object
Хеш общий параметров.
-
#counter ⇒ Object
readonly
Returns the value of attribute counter.
-
#date ⇒ Object
readonly
Returns the value of attribute date.
-
#destinations ⇒ Object
Массив, целевых моделей для сохранение данных, Array.
-
#fields ⇒ Object
Список доступных для сохранение в целевые таблицы полей и их типов данных, в виде Hash.
-
#name ⇒ Object
Название дампера.
-
#temp_table_name ⇒ Object
Название temp таблицы, используемой для переноса данных.
Instance Method Summary collapse
-
#initialize ⇒ Engine
constructor
A new instance of Engine.
-
#process!(counter, date) ⇒ Object
Public: Производит перенос данных счетчика.
Constructor Details
#initialize ⇒ Engine
Returns a new instance of Engine.
147 148 149 150 |
# File 'lib/redis_counters/dumpers/engine.rb', line 147 def initialize @destinations = [] @common_params = {} end |
Instance Attribute Details
#common_params ⇒ Object
Хеш общий параметров. Данные хеш мерджится в каждую, поступающую от счетчика, строку данных.
99 100 101 |
# File 'lib/redis_counters/dumpers/engine.rb', line 99 def common_params @common_params end |
#counter ⇒ Object (readonly)
Returns the value of attribute counter.
101 102 103 |
# File 'lib/redis_counters/dumpers/engine.rb', line 101 def counter @counter end |
#date ⇒ Object (readonly)
Returns the value of attribute date.
102 103 104 |
# File 'lib/redis_counters/dumpers/engine.rb', line 102 def date @date end |
#destinations ⇒ Object
Массив, целевых моделей для сохранение данных, Array. Каждый элемент массива это экземпляр класса Engine::Destination.
91 92 93 |
# File 'lib/redis_counters/dumpers/engine.rb', line 91 def destinations @destinations end |
#fields ⇒ Object
Список доступных для сохранение в целевые таблицы полей и их типов данных, в виде Hash. Доступны следующие типы данных: string, integer, date, timestamp, boolean. Преобразование типов производится непосредственно перед мерджем в целевые таблицы.
Example:
fields = {:company_id => :integer, :date => :timestamp}
87 88 89 |
# File 'lib/redis_counters/dumpers/engine.rb', line 87 def fields @fields end |
#name ⇒ Object
Название дампера
79 80 81 |
# File 'lib/redis_counters/dumpers/engine.rb', line 79 def name @name end |
#temp_table_name ⇒ Object
Название temp таблицы, используемой для переноса данных. По умолчанию: “tmp_#dumper_name”
95 96 97 |
# File 'lib/redis_counters/dumpers/engine.rb', line 95 def temp_table_name @temp_table_name end |
Instance Method Details
#process!(counter, date) ⇒ Object
Public: Производит перенос данных счетчика.
counter - экземпляр счетчика. date - Date - дата, за которую производится перенос данных.
Returns Fixnum - кол-во обработанных строк.
133 134 135 136 137 138 139 140 141 142 143 144 145 |
# File 'lib/redis_counters/dumpers/engine.rb', line 133 def process!(counter, date) @counter, @date = counter, date db_transaction do merge_data start_redis_transaction delete_from_redis end commit_redis_transaction rows_processed end |