Class: Timeline

Inherits:
Object
  • Object
show all
Includes:
UpdateHelper
Defined in:
lib/time_travel/timeline.rb

Constant Summary collapse

UPDATE_MODE =
ENV["TIME_TRAVEL_UPDATE_MODE"] || TimeTravel.configuration.update_mode

Class Method Summary collapse

Instance Method Summary collapse

Methods included from UpdateHelper

#construct_corrected_records, #fetch_history_for_correction, #get_affected_timeframes, #squish_record_history

Constructor Details

#initialize(model_class, **timeline_identifiers) ⇒ Timeline

Returns a new instance of Timeline.



9
10
11
12
13
# File 'lib/time_travel/timeline.rb', line 9

def initialize(model_class,**timeline_identifiers)
  @model_class=model_class
  @timeline_identifiers=timeline_identifiers
  @timeline=model_class.where(**timeline_identifiers)
end

Class Method Details

.bulk_update(model_class, attribute_set, current_time: Time.current, latest_transactions: false) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/time_travel/timeline.rb', line 80

def self.bulk_update(model_class, attribute_set, current_time: Time.current, latest_transactions: false)
  if UPDATE_MODE=="native"
    attribute_set.each do |attributes|
      attributes.symbolize_keys!
      if attributes.slice(*model_class.timeline_fields).keys.length != model_class.timeline_fields.length
        raise "Timeline identifiers can't be empty"
      end
      timeline=model_class.timeline(attributes.slice(*model_class.timeline_fields))
      timeline.create_or_update(
        attributes, 
        current_time: current_time, 
        effective_from: attributes[:effective_from], 
        effective_till: attributes[:effective_till]
      )
    end
  else
    update_sql(
      model_class,
      attribute_set, 
      current_time: current_time, 
      latest_transactions: latest_transactions
    )
  end
end

.db_timestamp(datetime) ⇒ Object



192
193
194
# File 'lib/time_travel/timeline.rb', line 192

def self.db_timestamp(datetime)
  datetime.to_datetime.utc.strftime(TimeTravel::PRECISE_TIME_FORMAT)
end

.set_enum(model_class, attrs) ⇒ Object



184
185
186
187
188
189
190
# File 'lib/time_travel/timeline.rb', line 184

def self.set_enum(model_class, attrs)
  enum_fields, enum_items = model_class.enum_info
  enum_fields.each do |key|
    string_value = attrs[key]
    attrs[key] = enum_items[key][string_value] unless string_value.blank?
  end
end

.update_sql(model_class, attribute_set, current_time: Time.current, latest_transactions: false) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/time_travel/timeline.rb', line 151

def self.update_sql(model_class, attribute_set, current_time: Time.current, latest_transactions: false)
  other_attrs = (model_class.column_names - ["id", "created_at", "updated_at", "valid_from", "valid_till"])
  empty_obj_attrs = other_attrs.map{|attr| {attr => nil}}.reduce(:merge!).with_indifferent_access
  query = ActiveRecord::Base.connection.quote(model_class.unscoped.where(valid_till: TimeTravel::INFINITE_DATE).to_sql)
  table_name = ActiveRecord::Base.connection.quote(model_class.table_name)

  attribute_set.each_slice(model_class.batch_size).to_a.each do |batched_attribute_set|
    batched_attribute_set.each do |attrs|
      attrs.symbolize_keys!
      set_enum(model_class, attrs)
      attrs[:timeline_clauses], attrs[:update_attrs] = attrs.partition do  |key, value|
        key.in?(model_class.timeline_fields)
      end.map(&:to_h).map(&:symbolize_keys!)
      if attrs[:timeline_clauses].empty? || attrs[:timeline_clauses].values.any?(&:blank?)
        raise "Timeline identifiers can't be empty"
      end
      obj_current_time = attrs[:update_attrs].delete(:current_time) || current_time
      attrs[:effective_from] = db_timestamp(attrs[:update_attrs].delete(:effective_from) || obj_current_time)
      attrs[:effective_till] = db_timestamp(attrs[:update_attrs].delete(:effective_till) || TimeTravel::INFINITE_DATE)
      attrs[:current_time] = db_timestamp(obj_current_time)
      attrs[:infinite_date] = db_timestamp(TimeTravel::INFINITE_DATE)
      attrs[:empty_obj_attrs] = empty_obj_attrs.merge(attrs[:timeline_clauses])
    end
    attrs = ActiveRecord::Base.connection.quote(batched_attribute_set.to_json)
    begin
      result = ActiveRecord::Base.connection.execute("select update_bulk_history(#{query},#{table_name},#{attrs},#{latest_transactions})")
    rescue => e
      ActiveRecord::Base.connection.execute 'ROLLBACK'
      raise e
    end
  end
end

Instance Method Details

#as_of(valid_date = Time.current) ⇒ Object



29
30
31
32
33
34
# File 'lib/time_travel/timeline.rb', line 29

def as_of(valid_date=Time.current)
  @timeline
    .where("valid_from <= ?", valid_date)
    .where("valid_till > ?", valid_date)
    .order("effective_from ASC")
end

#at(date, as_of: Time.current) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/time_travel/timeline.rb', line 15

def at(date, as_of: Time.current)
  record=@timeline
    .where("effective_from <= ?", date)
    .where("effective_till > ?", date)
    .where("valid_from <= ?", as_of)
    .where("valid_till > ?", as_of)
  record.first if record.exists?

end

#construct_record(attributes, current_time:, effective_from:, effective_till:) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/time_travel/timeline.rb', line 47

def construct_record(attributes,current_time:,effective_from:,effective_till:)
  record=@model_class.new
  record.attributes=attributes
  @timeline_identifiers.each do |attribute,value|
    record[attribute]=value
  end
  record.current_time=current_time
  record.effective_from=effective_from
  record.effective_till=effective_till
  record
end

#create(attributes, current_time: Time.current, effective_from: nil, effective_till: nil) ⇒ Object

Raises:

  • (ActiveRecord::RecordInvalid)


69
70
71
72
73
74
75
76
77
78
# File 'lib/time_travel/timeline.rb', line 69

def create(attributes,current_time: Time.current, effective_from: nil, effective_till: nil)
  record=construct_record(attributes, current_time: current_time, 
                          effective_from: effective_from, effective_till: effective_till)
  if self.has_history?
    raise "timeline already exists"
  end
  raise ActiveRecord::RecordInvalid.new(record) unless record.validate_update(attributes)
  record.save!
  record
end

#create_or_update(attributes, current_time: Time.current, effective_from: nil, effective_till: nil) ⇒ Object



59
60
61
62
63
64
65
66
67
# File 'lib/time_travel/timeline.rb', line 59

def create_or_update(attributes,current_time: Time.current, effective_from: nil, effective_till: nil)
  if self.has_history?
    self.update(
      attributes, current_time: current_time, effective_from: effective_from, effective_till: effective_till)
  else
    self.create(
      attributes,current_time: current_time, effective_from: effective_from, effective_till: effective_till)
  end
end

#effective_historyObject



43
44
45
# File 'lib/time_travel/timeline.rb', line 43

def effective_history
  @timeline.where(valid_till: TimeTravel::INFINITE_DATE).order("effective_from ASC")
end

#full_historyObject



25
26
27
# File 'lib/time_travel/timeline.rb', line 25

def full_history
  @timeline.order("effective_from ASC").order("valid_from ASC")
end

#has_history?Boolean

Returns:

  • (Boolean)


222
223
224
# File 'lib/time_travel/timeline.rb', line 222

def has_history?
  effective_history.exists?
end

#ignored_copy_attributesObject



218
219
220
# File 'lib/time_travel/timeline.rb', line 218

def ignored_copy_attributes
  ["id", "created_at", "updated_at", "valid_from", "valid_till"]
end

#ignored_update_attributesObject



214
215
216
# File 'lib/time_travel/timeline.rb', line 214

def ignored_update_attributes
  ["id", "created_at", "updated_at", "effective_from", "effective_till", "valid_from", "valid_till"]
end

#terminate(current_time: Time.current, effective_till: nil) ⇒ Object



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/time_travel/timeline.rb', line 196

def terminate(current_time: Time.current, effective_till: nil)
  effective_record = self.effective_history.where(effective_till: TimeTravel::INFINITE_DATE).first
  if effective_record.present?
    attributes = effective_record.attributes.except(*ignored_copy_attributes)
    @model_class.transaction do
      @model_class.create!(
        attributes.merge(
          effective_till: (effective_till || current_time),
          current_time: current_time
        )
      )
      effective_record.update_attribute(:valid_till, current_time)
    end
  else
    raise "no effective record found on timeline"
  end
end

#update(attributes, current_time: Time.current, effective_from: nil, effective_till: nil) ⇒ Object

Raises:

  • (ActiveRecord::RecordInvalid)


105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/time_travel/timeline.rb', line 105

def update(attributes, current_time: Time.current, effective_from: nil, effective_till: nil)
  attributes.symbolize_keys!
  attributes=attributes.except(*ignored_update_attributes)
  return true if attributes.empty?
  if not self.has_history?
    raise "timeline not found"
  end
  record=construct_record(
    attributes, current_time: current_time, effective_from: effective_from, effective_till: effective_till)
  raise ActiveRecord::RecordInvalid.new(record) unless record.validate_update(attributes)
  record_attributes=record.attributes.except(*ignored_copy_attributes).symbolize_keys!
  update_attributes=record_attributes.slice(*attributes.keys)
  if UPDATE_MODE=="native"
    update_native(
      record, update_attributes, 
      current_time: current_time, effective_from: effective_from, effective_till: effective_till
    )
  else
    update_attributes.merge!(@timeline_identifiers)
    update_attributes.merge!({effective_from: effective_from, effective_till: effective_till})
    self.class.update_sql(@model_class, [update_attributes], current_time: current_time)
  end
end

#update_native(record, update_attributes, current_time: Time.current, effective_from: nil, effective_till: nil) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/time_travel/timeline.rb', line 130

def update_native(record, update_attributes, current_time: Time.current, effective_from: nil, effective_till: nil)
  affected_records = fetch_history_for_correction(record)
  affected_timeframes = get_affected_timeframes(record, affected_records)

  corrected_records = construct_corrected_records(
    record, affected_timeframes, affected_records, update_attributes)
  squished_records = squish_record_history(corrected_records)

  @model_class.transaction do
    squished_records.each do |record|
      insert_record=record.merge(
        current_time: current_time
      )
      @model_class.create!(insert_record)
    end

    affected_records.each {|record| record.update_attribute(:valid_till, current_time)}
  end
  true
end

#valid_history(effective_at: Time.current) ⇒ Object



36
37
38
39
40
41
# File 'lib/time_travel/timeline.rb', line 36

def valid_history(effective_at: Time.current)
  @timeline
      .where("effective_from <= ?", effective_date)
      .where("effective_till > ?", effective_date)
      .order("valid_from ASC")
end