paper_trail_diff 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +724 -1
  3. data/README.md +43 -8
  4. data/docs/architecture.md +7 -5
  5. data/docs/performance.md +89 -32
  6. data/docs/reference.md +427 -96
  7. data/docs/testing.md +260 -32
  8. data/lib/paper_trail_diff/activity_belongs_to_event_applier.rb +2 -16
  9. data/lib/paper_trail_diff/activity_boundary.rb +55 -34
  10. data/lib/paper_trail_diff/activity_child_candidate_loader.rb +46 -57
  11. data/lib/paper_trail_diff/activity_collection_event_applier.rb +33 -11
  12. data/lib/paper_trail_diff/activity_collection_route_updater.rb +1 -1
  13. data/lib/paper_trail_diff/activity_event.rb +33 -21
  14. data/lib/paper_trail_diff/activity_event_record_resolver.rb +16 -116
  15. data/lib/paper_trail_diff/activity_event_route_finder.rb +49 -18
  16. data/lib/paper_trail_diff/activity_event_snapshot_refresher.rb +13 -7
  17. data/lib/paper_trail_diff/activity_history.rb +90 -49
  18. data/lib/paper_trail_diff/activity_range.rb +9 -35
  19. data/lib/paper_trail_diff/activity_root_snapshot_refresher.rb +104 -52
  20. data/lib/paper_trail_diff/activity_root_steps.rb +10 -13
  21. data/lib/paper_trail_diff/activity_scope_filter.rb +77 -0
  22. data/lib/paper_trail_diff/activity_snapshot_delta.rb +12 -15
  23. data/lib/paper_trail_diff/activity_snapshot_sequence.rb +37 -15
  24. data/lib/paper_trail_diff/activity_target_candidate_loader.rb +35 -43
  25. data/lib/paper_trail_diff/activity_timeline_builder.rb +200 -249
  26. data/lib/paper_trail_diff/activity_transaction_grouper.rb +3 -1
  27. data/lib/paper_trail_diff/activity_tree_filter.rb +54 -13
  28. data/lib/paper_trail_diff/activity_version_collector.rb +72 -138
  29. data/lib/paper_trail_diff/activity_view.rb +22 -11
  30. data/lib/paper_trail_diff/analysis.rb +39 -6
  31. data/lib/paper_trail_diff/analysis_batch.rb +16 -58
  32. data/lib/paper_trail_diff/approximate_paths.rb +4 -8
  33. data/lib/paper_trail_diff/association_activity_edge.rb +5 -24
  34. data/lib/paper_trail_diff/association_activity_selection.rb +10 -18
  35. data/lib/paper_trail_diff/association_discovery.rb +1 -6
  36. data/lib/paper_trail_diff/association_key.rb +9 -6
  37. data/lib/paper_trail_diff/association_traversal.rb +49 -6
  38. data/lib/paper_trail_diff/batch_boundary_resolver.rb +33 -42
  39. data/lib/paper_trail_diff/batch_preload.rb +2 -12
  40. data/lib/paper_trail_diff/batched_root_analyses.rb +72 -0
  41. data/lib/paper_trail_diff/batched_root_analyzer.rb +22 -14
  42. data/lib/paper_trail_diff/batched_root_versions.rb +25 -20
  43. data/lib/paper_trail_diff/branch_snapshot_refresher.rb +41 -42
  44. data/lib/paper_trail_diff/change_attribution.rb +314 -0
  45. data/lib/paper_trail_diff/change_row.rb +30 -10
  46. data/lib/paper_trail_diff/comparison_batch.rb +3 -4
  47. data/lib/paper_trail_diff/configuration.rb +1 -1
  48. data/lib/paper_trail_diff/deleted_analysis_batch.rb +22 -33
  49. data/lib/paper_trail_diff/deleted_root_filter.rb +29 -10
  50. data/lib/paper_trail_diff/deprecation.rb +4 -43
  51. data/lib/paper_trail_diff/diagnostics.rb +8 -7
  52. data/lib/paper_trail_diff/direct_record_state_loader.rb +8 -1
  53. data/lib/paper_trail_diff/endpoint.rb +78 -44
  54. data/lib/paper_trail_diff/errors.rb +2 -9
  55. data/lib/paper_trail_diff/fallback_paths.rb +2 -5
  56. data/lib/paper_trail_diff/habtm_transaction_owners.rb +5 -3
  57. data/lib/paper_trail_diff/historical_association_reifier.rb +3 -1
  58. data/lib/paper_trail_diff/historical_filter.rb +40 -15
  59. data/lib/paper_trail_diff/historical_snapshot_store.rb +80 -38
  60. data/lib/paper_trail_diff/instrumentation.rb +0 -8
  61. data/lib/paper_trail_diff/live_endpoint_batch_loader.rb +11 -7
  62. data/lib/paper_trail_diff/live_endpoint_provider.rb +7 -23
  63. data/lib/paper_trail_diff/live_graph_collector.rb +3 -3
  64. data/lib/paper_trail_diff/nested_comparator.rb +46 -19
  65. data/lib/paper_trail_diff/net_change.rb +276 -0
  66. data/lib/paper_trail_diff/own_window.rb +35 -0
  67. data/lib/paper_trail_diff/paper_trail_adapter.rb +119 -87
  68. data/lib/paper_trail_diff/prepared_activity_index.rb +182 -50
  69. data/lib/paper_trail_diff/prepared_child_candidates.rb +58 -0
  70. data/lib/paper_trail_diff/prepared_edge_loader.rb +43 -107
  71. data/lib/paper_trail_diff/prepared_history.rb +31 -36
  72. data/lib/paper_trail_diff/prepared_history_loader.rb +47 -12
  73. data/lib/paper_trail_diff/prepared_record_index.rb +143 -49
  74. data/lib/paper_trail_diff/prepared_snapshot_builder.rb +16 -0
  75. data/lib/paper_trail_diff/prepared_state_association_reader.rb +17 -19
  76. data/lib/paper_trail_diff/read_snapshot.rb +99 -0
  77. data/lib/paper_trail_diff/recorded_changes.rb +10 -11
  78. data/lib/paper_trail_diff/recorded_changes_reader.rb +60 -0
  79. data/lib/paper_trail_diff/recorded_class.rb +14 -19
  80. data/lib/paper_trail_diff/recorded_columns.rb +33 -0
  81. data/lib/paper_trail_diff/root_version_plan.rb +20 -22
  82. data/lib/paper_trail_diff/root_version_selection.rb +39 -29
  83. data/lib/paper_trail_diff/scope_condition.rb +92 -32
  84. data/lib/paper_trail_diff/scope_ranking.rb +27 -34
  85. data/lib/paper_trail_diff/scoped_analysis.rb +27 -4
  86. data/lib/paper_trail_diff/scoped_analysis_builder.rb +18 -7
  87. data/lib/paper_trail_diff/scoped_root_selection.rb +65 -39
  88. data/lib/paper_trail_diff/snapshot_normalizer.rb +18 -3
  89. data/lib/paper_trail_diff/stored_json_values.rb +52 -0
  90. data/lib/paper_trail_diff/stored_time_precision.rb +30 -18
  91. data/lib/paper_trail_diff/stored_values.rb +20 -0
  92. data/lib/paper_trail_diff/support.rb +185 -35
  93. data/lib/paper_trail_diff/time_of_day.rb +39 -0
  94. data/lib/paper_trail_diff/time_range.rb +40 -22
  95. data/lib/paper_trail_diff/time_version_range.rb +5 -10
  96. data/lib/paper_trail_diff/timeline_builder.rb +9 -3
  97. data/lib/paper_trail_diff/timeline_range.rb +18 -12
  98. data/lib/paper_trail_diff/timeline_snapshot_provider.rb +1 -1
  99. data/lib/paper_trail_diff/total_order.rb +55 -0
  100. data/lib/paper_trail_diff/transaction_cut.rb +235 -75
  101. data/lib/paper_trail_diff/traversal_preparer.rb +5 -8
  102. data/lib/paper_trail_diff/value_objects.rb +8 -4
  103. data/lib/paper_trail_diff/version.rb +1 -1
  104. data/lib/paper_trail_diff/version_association_candidate_scope.rb +1 -12
  105. data/lib/paper_trail_diff/version_boundary.rb +41 -23
  106. data/lib/paper_trail_diff/version_query.rb +25 -25
  107. data/lib/paper_trail_diff/version_range.rb +12 -16
  108. data/lib/paper_trail_diff/version_sequence_diagnostics.rb +36 -1
  109. data/lib/paper_trail_diff/version_table.rb +12 -8
  110. data/lib/paper_trail_diff.rb +32 -44
  111. data/sig/generated/paper_trail_diff/activity_belongs_to_event_applier.rbs +0 -8
  112. data/sig/generated/paper_trail_diff/activity_boundary.rbs +39 -17
  113. data/sig/generated/paper_trail_diff/activity_child_candidate_loader.rbs +19 -22
  114. data/sig/generated/paper_trail_diff/activity_collection_event_applier.rbs +13 -5
  115. data/sig/generated/paper_trail_diff/activity_event.rbs +25 -9
  116. data/sig/generated/paper_trail_diff/activity_event_record_resolver.rbs +6 -34
  117. data/sig/generated/paper_trail_diff/activity_event_route_finder.rbs +25 -4
  118. data/sig/generated/paper_trail_diff/activity_event_snapshot_refresher.rbs +6 -3
  119. data/sig/generated/paper_trail_diff/activity_history.rbs +54 -19
  120. data/sig/generated/paper_trail_diff/activity_range.rbs +6 -20
  121. data/sig/generated/paper_trail_diff/activity_root_snapshot_refresher.rbs +55 -10
  122. data/sig/generated/paper_trail_diff/activity_root_steps.rbs +6 -6
  123. data/sig/generated/paper_trail_diff/activity_scope_filter.rbs +51 -0
  124. data/sig/generated/paper_trail_diff/activity_snapshot_delta.rbs +5 -3
  125. data/sig/generated/paper_trail_diff/activity_snapshot_sequence.rbs +21 -3
  126. data/sig/generated/paper_trail_diff/activity_target_candidate_loader.rbs +19 -24
  127. data/sig/generated/paper_trail_diff/activity_timeline_builder.rbs +125 -127
  128. data/sig/generated/paper_trail_diff/activity_tree_filter.rbs +41 -8
  129. data/sig/generated/paper_trail_diff/activity_version_collector.rbs +42 -35
  130. data/sig/generated/paper_trail_diff/activity_view.rbs +16 -8
  131. data/sig/generated/paper_trail_diff/analysis.rbs +26 -5
  132. data/sig/generated/paper_trail_diff/analysis_batch.rbs +6 -24
  133. data/sig/generated/paper_trail_diff/association_activity_edge.rbs +0 -13
  134. data/sig/generated/paper_trail_diff/association_activity_selection.rbs +6 -9
  135. data/sig/generated/paper_trail_diff/association_discovery.rbs +0 -3
  136. data/sig/generated/paper_trail_diff/association_key.rbs +5 -0
  137. data/sig/generated/paper_trail_diff/association_traversal.rbs +26 -2
  138. data/sig/generated/paper_trail_diff/batch_boundary_resolver.rbs +17 -17
  139. data/sig/generated/paper_trail_diff/batch_preload.rbs +0 -4
  140. data/sig/generated/paper_trail_diff/batched_root_analyses.rbs +47 -0
  141. data/sig/generated/paper_trail_diff/batched_root_analyzer.rbs +13 -8
  142. data/sig/generated/paper_trail_diff/batched_root_versions.rbs +10 -6
  143. data/sig/generated/paper_trail_diff/branch_snapshot_refresher.rbs +16 -4
  144. data/sig/generated/paper_trail_diff/change_attribution.rbs +185 -0
  145. data/sig/generated/paper_trail_diff/change_row.rbs +22 -7
  146. data/sig/generated/paper_trail_diff/deleted_analysis_batch.rbs +11 -9
  147. data/sig/generated/paper_trail_diff/deleted_root_filter.rbs +9 -3
  148. data/sig/generated/paper_trail_diff/deprecation.rbs +4 -24
  149. data/sig/generated/paper_trail_diff/direct_record_state_loader.rbs +4 -0
  150. data/sig/generated/paper_trail_diff/endpoint.rbs +40 -16
  151. data/sig/generated/paper_trail_diff/errors.rbs +2 -11
  152. data/sig/generated/paper_trail_diff/habtm_transaction_owners.rbs +2 -1
  153. data/sig/generated/paper_trail_diff/historical_filter.rbs +20 -9
  154. data/sig/generated/paper_trail_diff/historical_snapshot_store.rbs +40 -10
  155. data/sig/generated/paper_trail_diff/instrumentation.rbs +0 -3
  156. data/sig/generated/paper_trail_diff/live_endpoint_batch_loader.rbs +3 -0
  157. data/sig/generated/paper_trail_diff/live_endpoint_provider.rbs +5 -8
  158. data/sig/generated/paper_trail_diff/live_graph_collector.rbs +2 -2
  159. data/sig/generated/paper_trail_diff/nested_comparator.rbs +20 -4
  160. data/sig/generated/paper_trail_diff/net_change.rbs +168 -0
  161. data/sig/generated/paper_trail_diff/own_window.rbs +22 -0
  162. data/sig/generated/paper_trail_diff/paper_trail_adapter.rbs +19 -6
  163. data/sig/generated/paper_trail_diff/prepared_activity_index.rbs +113 -17
  164. data/sig/generated/paper_trail_diff/prepared_child_candidates.rbs +39 -0
  165. data/sig/generated/paper_trail_diff/prepared_edge_loader.rbs +18 -35
  166. data/sig/generated/paper_trail_diff/prepared_history.rbs +15 -13
  167. data/sig/generated/paper_trail_diff/prepared_history_loader.rbs +28 -3
  168. data/sig/generated/paper_trail_diff/prepared_record_index.rbs +70 -15
  169. data/sig/generated/paper_trail_diff/prepared_snapshot_builder.rbs +12 -0
  170. data/sig/generated/paper_trail_diff/prepared_state_association_reader.rbs +6 -7
  171. data/sig/generated/paper_trail_diff/read_snapshot.rbs +62 -0
  172. data/sig/generated/paper_trail_diff/recorded_changes.rbs +4 -2
  173. data/sig/generated/paper_trail_diff/recorded_changes_reader.rbs +41 -0
  174. data/sig/generated/paper_trail_diff/recorded_class.rbs +7 -6
  175. data/sig/generated/paper_trail_diff/recorded_columns.rbs +21 -0
  176. data/sig/generated/paper_trail_diff/root_version_plan.rbs +8 -4
  177. data/sig/generated/paper_trail_diff/root_version_selection.rbs +27 -13
  178. data/sig/generated/paper_trail_diff/scope_condition.rbs +39 -9
  179. data/sig/generated/paper_trail_diff/scope_ranking.rbs +16 -16
  180. data/sig/generated/paper_trail_diff/scoped_analysis.rbs +19 -0
  181. data/sig/generated/paper_trail_diff/scoped_analysis_builder.rbs +9 -2
  182. data/sig/generated/paper_trail_diff/scoped_root_selection.rbs +40 -12
  183. data/sig/generated/paper_trail_diff/snapshot_normalizer.rbs +7 -0
  184. data/sig/generated/paper_trail_diff/stored_json_values.rbs +35 -0
  185. data/sig/generated/paper_trail_diff/stored_time_precision.rbs +19 -5
  186. data/sig/generated/paper_trail_diff/stored_values.rbs +13 -0
  187. data/sig/generated/paper_trail_diff/support.rbs +120 -23
  188. data/sig/generated/paper_trail_diff/time_of_day.rbs +21 -0
  189. data/sig/generated/paper_trail_diff/time_range.rbs +15 -7
  190. data/sig/generated/paper_trail_diff/time_version_range.rbs +2 -5
  191. data/sig/generated/paper_trail_diff/timeline_builder.rbs +6 -2
  192. data/sig/generated/paper_trail_diff/timeline_range.rbs +12 -7
  193. data/sig/generated/paper_trail_diff/total_order.rbs +32 -0
  194. data/sig/generated/paper_trail_diff/transaction_cut.rbs +131 -40
  195. data/sig/generated/paper_trail_diff/traversal_preparer.rbs +2 -2
  196. data/sig/generated/paper_trail_diff/value_objects.rbs +5 -1
  197. data/sig/generated/paper_trail_diff/version_association_candidate_scope.rbs +0 -7
  198. data/sig/generated/paper_trail_diff/version_boundary.rbs +17 -8
  199. data/sig/generated/paper_trail_diff/version_query.rbs +17 -10
  200. data/sig/generated/paper_trail_diff/version_range.rbs +6 -9
  201. data/sig/generated/paper_trail_diff/version_sequence_diagnostics.rbs +16 -0
  202. data/sig/generated/paper_trail_diff/version_table.rbs +3 -0
  203. data/sig/generated/paper_trail_diff.rbs +16 -16
  204. metadata +31 -7
  205. data/lib/paper_trail_diff/preloaded_endpoint_batch_loader.rb +0 -60
  206. data/sig/generated/paper_trail_diff/preloaded_endpoint_batch_loader.rbs +0 -32
@@ -56,6 +56,7 @@ module PaperTrailDiff
56
56
  @pool = pool
57
57
  @structural_columns = {} #: Hash[String, Array[String]]
58
58
  @excluded_attributes = {} #: Hash[Array[untyped], Array[String?]]
59
+ @leaves = {} #: Hash[String, Hash[PreparedRecordState, RecordSnapshot]]
59
60
  end
60
61
 
61
62
  #: (untyped, reifier: untyped) -> RecordSnapshot?
@@ -90,8 +91,22 @@ module PaperTrailDiff
90
91
  end
91
92
 
92
93
  # Same exclusions as AR normalization, applied to an already typed state.
94
+ # A state without associations is normalized once at each path: the
95
+ # same state is read again at every boundary it spans.
93
96
  #: (PreparedRecordState, tree: AssociationTree, path: String, ?incoming: untyped, ?associations: snapshot_associations) -> RecordSnapshot
94
97
  def from_state(state, tree:, path:, incoming: nil, associations: {})
98
+ unless associations.empty?
99
+ return snapshot_from_state(state, tree, path, incoming, associations)
100
+ end
101
+
102
+ leaves = @leaves[path] ||= {}
103
+ leaves[state] ||= snapshot_from_state(state, tree, path, incoming, associations)
104
+ end
105
+
106
+ private
107
+
108
+ #: (PreparedRecordState, AssociationTree, String, untyped, snapshot_associations) -> RecordSnapshot
109
+ def snapshot_from_state(state, tree, path, incoming, associations)
95
110
  model = state.model_class
96
111
  @structural_columns[path] ||= @traversal.incoming_relationship_columns(incoming) if incoming
97
112
  reflections = @traversal.reflections_for(model, tree, path: path)
@@ -104,8 +119,6 @@ module PaperTrailDiff
104
119
  pool_state(path, snapshot)
105
120
  end
106
121
 
107
- private
108
-
109
122
  # The id a live record of the same row reports: one value, or one per
110
123
  # column of a composite key.
111
124
  #: (untyped, PreparedRecordState) -> untyped
@@ -125,6 +138,7 @@ module PaperTrailDiff
125
138
  # @rbs @pool: SnapshotPool
126
139
  # @rbs @structural_columns: Hash[String, Array[String]]
127
140
  # @rbs @excluded_attributes: Hash[Array[untyped], Array[String?]]
141
+ # @rbs @leaves: Hash[String, Hash[PreparedRecordState, RecordSnapshot]]
128
142
 
129
143
  #: (untyped, AssociationTree, String, untyped, Array[untyped]) -> RecordSnapshot
130
144
  def normalize_record(record, tree, path, reifier, reflections)
@@ -141,7 +155,7 @@ module PaperTrailDiff
141
155
  def normalized_attributes(record, reflections, path)
142
156
  attributes = record.attributes
143
157
  excluded_attributes(record, reflections, path).each { |name| attributes.delete(name) }
144
- StoredTimePrecision.apply(attributes, StoredTimePrecision.digits(record.class))
158
+ StoredValues.apply(record.class, attributes)
145
159
  end
146
160
 
147
161
  # Every input is fixed for one model class at one selected path, and the
@@ -222,6 +236,7 @@ module PaperTrailDiff
222
236
  def normalize_children(records, tree, path, reifier)
223
237
  reflections_by_class = {} #: Hash[untyped, Array[untyped]]
224
238
  records.map do |child|
239
+ Support.with_recorded_times(child)
225
240
  reflections = reflections_by_class[child.class] ||= reflections_for(child, tree, path)
226
241
  reifier.reify(child, reflections) unless reflections.empty?
227
242
  normalize_record(child, tree, path, reifier, reflections)
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module PaperTrailDiff
5
+ # Reads values in the form JSON history gives them back.
6
+ #
7
+ # A `json` or `jsonb` object column stores a record's attributes as they
8
+ # are, without PaperTrail's attribute serializer, so a `serialize`d value
9
+ # comes back as JSON writes it: keys as strings, and dates, times and
10
+ # symbols inside it as strings, which its type does not cast back.
11
+ # PaperTrail's JSON serializer stores a binary value as `{"value" => bytes}`,
12
+ # which its type does not cast back either. Compared as they are, the live
13
+ # row and every version would differ though nothing was edited. So every
14
+ # side is read in one form: a `serialize`d value as JSON writes it, and a
15
+ # binary value as its bytes. Both leave a value read from history as it is.
16
+ module StoredJsonValues
17
+ SERIALIZED_TYPE = 'ActiveRecord::Type::Serialized'
18
+ BINARY_TYPE = 'ActiveModel::Type::Binary'
19
+ BINARY_KEYS = ['value'].freeze
20
+ private_constant :SERIALIZED_TYPE, :BINARY_TYPE, :BINARY_KEYS
21
+
22
+ # For a model whose history is JSON, which StoredTimePrecision.digits
23
+ # tells: a `json` or `jsonb` object column, or the JSON serializer.
24
+ #: (untyped, Hash[untyped, untyped]) -> Hash[untyped, untyped]
25
+ def self.apply(model_class, attributes)
26
+ if StoredTimePrecision.json_column?(model_class.paper_trail.version_class, 'object')
27
+ convert(model_class, attributes, SERIALIZED_TYPE, &:as_json)
28
+ else
29
+ convert(model_class, attributes, BINARY_TYPE) { |value| bytes(value) }
30
+ end
31
+ end
32
+
33
+ # The attributes with the value of each of this type converted. An
34
+ # adapter's type can be a subclass, as PostgreSQL's `bytea` is of binary.
35
+ #: (untyped, Hash[untyped, untyped], String) { (untyped) -> untyped } -> Hash[untyped, untyped]
36
+ def self.convert(model_class, attributes, type_name)
37
+ type = Support.constant(type_name)
38
+ attributes.to_h do |name, value|
39
+ [name, model_class.type_for_attribute(name).is_a?(type) ? yield(value) : value]
40
+ end
41
+ end
42
+ private_class_method :convert
43
+
44
+ #: (untyped) -> untyped
45
+ def self.bytes(value)
46
+ return value unless value.instance_of?(Hash) && value.keys == BINARY_KEYS
47
+
48
+ value.fetch('value').b
49
+ end
50
+ private_class_method :bytes
51
+ end
52
+ end
@@ -17,52 +17,64 @@ module PaperTrailDiff
17
17
  JSON_COLUMN_TYPES = %i[json jsonb].freeze
18
18
  private_constant :NANOSECOND_DIGITS, :JSON_COLUMN_TYPES
19
19
 
20
- module_function
21
-
22
20
  # Fractional digits a model's history keeps for times, or nil when the
23
21
  # history is stored losslessly.
24
22
  #: (untyped) -> Integer?
25
- def digits(model_class)
23
+ def self.digits(model_class)
26
24
  return unless Support.versioned?(model_class)
27
25
  return unless json_history?(model_class.paper_trail.version_class)
28
26
 
29
- active_support = Object.const_get(:ActiveSupport) #: untyped
30
- active_support.const_get(:JSON).const_get(:Encoding).time_precision
27
+ json_time_precision
31
28
  end
32
29
 
33
30
  #: (Hash[untyped, untyped], Integer?) -> Hash[untyped, untyped]
34
- def apply(attributes, digits)
31
+ def self.apply(attributes, digits)
35
32
  return attributes unless digits
36
33
 
37
34
  attributes.transform_values { |value| truncate(value, digits) }
38
35
  end
39
36
 
37
+ # From nine digits on, the step is one nanosecond or a fraction of one, so
38
+ # nothing is cut.
40
39
  #: (untyped, Integer) -> untyped
41
- def truncate(value, digits)
42
- return value unless value.is_a?(Time) && digits < NANOSECOND_DIGITS
40
+ def self.truncate(value, digits)
41
+ return value unless value.is_a?(Time)
43
42
 
44
43
  # ActiveSupport's Time#change, which also serves TimeWithZone.
45
44
  time = value #: untyped
46
- step = 10**(NANOSECOND_DIGITS - [digits, 0].max) #: Integer
47
- remainder = time.nsec % step
45
+ remainder = time.nsec % (10**(NANOSECOND_DIGITS - digits))
48
46
  remainder.zero? ? time : time.change(nsec: time.nsec - remainder)
49
47
  end
50
48
 
51
49
  #: (untyped) -> bool
52
- def json_history?(version_class)
53
- columns = version_class.columns_hash
54
- json_column = %w[object object_changes].any? do |name|
55
- JSON_COLUMN_TYPES.include?(columns[name]&.type)
56
- end
57
- json_column || json_serializer?
50
+ def self.json_history?(version_class)
51
+ %w[object object_changes].any? { |name| json_column?(version_class, name) } ||
52
+ json_serializer?
58
53
  end
59
54
  private_class_method :json_history?
60
55
 
56
+ # Whether the version table keeps this column as `json` or `jsonb`, which
57
+ # PaperTrail writes without its serializer.
58
+ #: (untyped, String) -> bool
59
+ def self.json_column?(version_class, name)
60
+ JSON_COLUMN_TYPES.include?(version_class.columns_hash[name]&.type)
61
+ end
62
+
63
+ # mutant:disable - Every mutation that survives here reads the same
64
+ # constant another way: from this module rather than Object, or with `::`.
65
+ #: () -> Integer
66
+ def self.json_time_precision
67
+ active_support = Object.const_get(:ActiveSupport) #: untyped
68
+ active_support.const_get(:JSON).const_get(:Encoding).time_precision
69
+ end
70
+ private_class_method :json_time_precision
71
+
72
+ # Whether PaperTrail writes history with its JSON serializer.
73
+ # mutant:disable - As for json_time_precision.
61
74
  #: () -> bool
62
- def json_serializer?
75
+ def self.json_serializer?
63
76
  paper_trail = Object.const_get(:PaperTrail) #: untyped
64
77
  paper_trail.serializer.equal?(paper_trail.const_get(:Serializers).const_get(:JSON))
65
78
  end
66
- private_class_method :json_serializer?
67
79
  end
68
80
  end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module PaperTrailDiff
5
+ # Reads a model's attribute values in the one form every account of them
6
+ # shares: a version decoded from history, the current row, and the changes
7
+ # a version recorded. Each would otherwise differ where nothing was edited.
8
+ # TimeOfDay puts a time of day on one date, and for JSON history,
9
+ # StoredJsonValues and StoredTimePrecision read values as JSON stored them.
10
+ module StoredValues
11
+ #: (untyped, Hash[untyped, untyped]) -> Hash[untyped, untyped]
12
+ def self.apply(model_class, attributes)
13
+ attributes = TimeOfDay.apply(model_class, attributes)
14
+ digits = StoredTimePrecision.digits(model_class)
15
+ return attributes unless digits
16
+
17
+ StoredTimePrecision.apply(StoredJsonValues.apply(model_class, attributes), digits)
18
+ end
19
+ end
20
+ end
@@ -4,10 +4,109 @@
4
4
  module PaperTrailDiff
5
5
  # Internal helpers for isolating and serializing values held by result objects.
6
6
  module Support # rubocop:disable Metrics/ModuleLength
7
- module_function
7
+ # Ids per statement, for the queries that list them in slices. SQL Server
8
+ # compiles every statement afresh, since its ids are written into it, in
9
+ # time that grows with their number; fewer statements than this cost more
10
+ # than they save.
11
+ IDS_PER_STATEMENT = 500
12
+
13
+ # PaperTrail's YAML serializer stores a `time` column's value as this
14
+ # wrapper, which PaperTrail 16 and 17 decode by reading its `@time`. Only
15
+ # some zone-aware times are stored with one, as a TimeWithZone's fields
16
+ # under the wrapper's tag; any other wraps its time, and decodes as nil.
17
+ TIME_VALUE = 'ActiveRecord::Type::Time::Value'
18
+
19
+ # The date a database gives a time of day it reads back.
20
+ TIME_OF_DAY_DATE = { year: 2000, month: 1, day: 1 }.freeze #: Hash[Symbol, Integer]
21
+
22
+ # Answers a question about `value` once for each Active Record class, in
23
+ # `answers`: its respond_to? also looks through the instance's attributes,
24
+ # which costs more than most of what reading a version does, and every
25
+ # instance of a model answers alike, since this gem reads versions with
26
+ # all their columns. Anything else is asked each time.
27
+ #: [T] (Hash[untyped, T], untyped) { (untyped) -> T } -> T
28
+ def self.per_model(answers, value)
29
+ model = value.class
30
+ return yield(value) unless model.respond_to?(:column_names)
31
+
32
+ answers.fetch(model) { answers[model] = yield(value) }
33
+ end
34
+
35
+ # Stored attributes or changes ready for PaperTrail to decode: keyed by
36
+ # name, with each time of day unwrapped, which then decodes as any value
37
+ # does. A change's values are a pair.
38
+ #: (Hash[untyped, untyped]) -> Hash[String, untyped]
39
+ def self.decodable(stored)
40
+ stored.to_h { |name, value| [name.to_s, unwrapped_time(value)] }
41
+ end
42
+
43
+ #: (untyped) -> untyped
44
+ def self.unwrapped_time(value)
45
+ return value.map { |item| unwrapped_time(item) } if value.instance_of?(Array)
46
+
47
+ TIME_VALUE.eql?(value.class.name) ? recorded_time(value) : value
48
+ end
49
+ private_class_method :unwrapped_time
50
+
51
+ # The time a stored wrapper holds -- the one it wraps, or the `@time`
52
+ # PaperTrail reads -- on 2000-01-01, as the database keeps a time of day.
53
+ # Active Record keeps the date of a time assigned in memory, which
54
+ # PaperTrail stores, but the row holds only the time.
55
+ #: (untyped) -> untyped
56
+ def self.recorded_time(value)
57
+ value.__getobj__ { value.instance_variable_get(:@time) }&.change(**TIME_OF_DAY_DATE)
58
+ end
59
+ private_class_method :recorded_time
60
+
61
+ # PaperTrail's `reify`, with each time of day its version recorded.
62
+ #: (untyped, **untyped) -> untyped
63
+ def self.reify(version, **options)
64
+ with_recorded_times(version.reify(**options))
65
+ end
66
+
67
+ # A record PaperTrail rebuilt, with each time of day assigned from the
68
+ # version it was rebuilt from, which PaperTrail can decode as nil. PaperTrail
69
+ # assigns stored attributes after building the record and links it to
70
+ # that version, PT-AT's members too, so this assigns what PaperTrail would
71
+ # if it unwrapped the value. Only a version whose stored text names the
72
+ # wrapper is decoded again; any other record is returned as it is.
73
+ #: [T] (T) -> T
74
+ def self.with_recorded_times(record)
75
+ version = rebuilt_from(record)
76
+ return record unless version
77
+
78
+ version.object_deserialized.each do |name, value|
79
+ next unless TIME_VALUE.eql?(value.class.name)
80
+
81
+ assign_recorded(record, name, recorded_time(value))
82
+ end
83
+ record
84
+ end
85
+
86
+ #: (untyped) -> untyped
87
+ def self.rebuilt_from(record)
88
+ model = record.class
89
+ return unless model.respond_to?(:version_association_name)
90
+
91
+ version = record.public_send(model.version_association_name)
92
+ # A JSON column's Hash is keyed by attribute names, never this one.
93
+ version if version&.object&.include?(TIME_VALUE)
94
+ end
95
+ private_class_method :rebuilt_from
96
+
97
+ # As PaperTrail assigns a stored attribute.
98
+ #: (untyped, String, untyped) -> void
99
+ def self.assign_recorded(record, name, value)
100
+ if record.has_attribute?(name)
101
+ record[name.to_sym] = value
102
+ elsif record.respond_to?(:"#{name}=")
103
+ record.public_send(:"#{name}=", value)
104
+ end
105
+ end
106
+ private_class_method :assign_recorded
8
107
 
9
108
  #: (untyped) -> untyped
10
- def immutable_copy(value)
109
+ def self.immutable_copy(value)
11
110
  case value
12
111
  when Hash
13
112
  immutable_hash(value)
@@ -19,7 +118,7 @@ module PaperTrailDiff
19
118
  end
20
119
 
21
120
  #: (Hash[untyped, untyped]) -> Hash[untyped, untyped]
22
- def immutable_hash(value)
121
+ def self.immutable_hash(value)
23
122
  copy = {} #: Hash[untyped, untyped]
24
123
  value.each do |key, item|
25
124
  copy[immutable_copy(key)] = immutable_copy(item)
@@ -29,7 +128,7 @@ module PaperTrailDiff
29
128
  private_class_method :immutable_hash
30
129
 
31
130
  #: (untyped) -> untyped
32
- def serialize(value)
131
+ def self.serialize(value)
33
132
  case value
34
133
  when Hash
35
134
  serialized = {} #: Hash[untyped, untyped]
@@ -49,7 +148,7 @@ module PaperTrailDiff
49
148
  # id 10 before id 2, which is deterministic but reads as unsorted wherever a
50
149
  # result is rendered.
51
150
  #: (untyped, untyped) -> Array[untyped]
52
- def sortable_identity(type, id)
151
+ def self.sortable_identity(type, id)
53
152
  key = case id
54
153
  when Numeric then [0, id]
55
154
  when String, Symbol then [1, id.to_s]
@@ -58,13 +157,53 @@ module PaperTrailDiff
58
157
  [type.to_s, key]
59
158
  end
60
159
 
160
+ # Which loaded row a version or record is, across the lookups of a call:
161
+ # by its class's name rather than the class, so a row still matches after
162
+ # its class is reloaded.
163
+ #: (untyped) -> Array[untyped]
164
+ def self.row_key(row)
165
+ [row.class.name, row.id]
166
+ end
167
+
168
+ # Which record a model and id name, as Endpoint.identity reads a record:
169
+ # by its base class, so a subclass and its base name the same row.
170
+ #: (untyped, untyped) -> Array[String]
171
+ def self.record_identity(model_class, id)
172
+ [model_class.base_class.name, id.to_s]
173
+ end
174
+
175
+ # Only quoting helpers are needed where this is used, so the model's
176
+ # connection is borrowed for the block rather than checked out
177
+ # permanently, which Active Record 7.2 and newer can deprecate. Active
178
+ # Record 7.1 has no `with_connection` and reaches the same connection
179
+ # through the accessor.
180
+ #: [T] (untyped) { (untyped) -> T } -> T
181
+ def self.with_connection(model, &block)
182
+ return model.with_connection(&block) if model.respond_to?(:with_connection)
183
+
184
+ yield(model.connection)
185
+ end
186
+
187
+ # A constant by its full name, such as a model's or one of Active
188
+ # Record's, untyped: Active Record and the models ship no signatures. Any
189
+ # spelling of the lookup finds the same constant.
190
+ # mutant:disable
191
+ #: (String) -> untyped
192
+ def self.constant(name)
193
+ Object.const_get(name)
194
+ end
195
+
196
+ # Arel, which ships no signatures either.
197
+ #: () -> untyped
198
+ def self.arel = constant('Arel')
199
+
61
200
  #: (untyped) -> Array[untyped]
62
- def chronological_version_key(version)
201
+ def self.chronological_version_key(version)
63
202
  version_key(version.created_at, version.id)
64
203
  end
65
204
 
66
205
  #: (untyped, untyped) -> Array[untyped]
67
- def version_key(created_at, id)
206
+ def self.version_key(created_at, id)
68
207
  [created_at, id.to_s.rjust(32, '0')]
69
208
  end
70
209
 
@@ -73,7 +212,7 @@ module PaperTrailDiff
73
212
  # does; a UUID does not, so a tie between UUID-keyed versions is genuinely
74
213
  # unorderable and any timeline built from it would be fiction.
75
214
  #: (Array[untyped]) -> Array[untyped]
76
- def chronological_sort(versions)
215
+ def self.chronological_sort(versions)
77
216
  sorted = versions.sort_by { |version| chronological_version_key(version) }
78
217
  ambiguous = ambiguous_pair(sorted)
79
218
  return sorted unless ambiguous
@@ -82,7 +221,7 @@ module PaperTrailDiff
82
221
  end
83
222
 
84
223
  #: (Array[untyped]) -> Array[untyped]?
85
- def ambiguous_pair(sorted)
224
+ def self.ambiguous_pair(sorted)
86
225
  sorted.each_cons(2).find do |left, right|
87
226
  left.created_at == right.created_at && !orderable_tie?(left, right)
88
227
  end
@@ -91,14 +230,14 @@ module PaperTrailDiff
91
230
  # Ids order versions saved in one instant only when they count up in one
92
231
  # table. Two version tables count separately, so ids there say nothing.
93
232
  #: (untyped, untyped) -> bool
94
- def orderable_tie?(left, right)
233
+ def self.orderable_tie?(left, right)
95
234
  version_table(left) == version_table(right) &&
96
235
  sequential_id?(left.id) && sequential_id?(right.id)
97
236
  end
98
237
 
99
238
  #: (untyped) -> untyped
100
- def version_table(version)
101
- version.class.respond_to?(:table_name) ? version.class.table_name : version.class.name
239
+ def self.version_table(version)
240
+ version.class.respond_to?(:table_name) ? version.class.table_name : version.class
102
241
  end
103
242
  private_class_method :version_table
104
243
 
@@ -107,7 +246,7 @@ module PaperTrailDiff
107
246
  # so association state cannot be told apart across such a pair even when the
108
247
  # scalar sequence is perfectly recoverable.
109
248
  #: (Array[untyped]) -> Array[untyped]?
110
- def tied_timestamp_pair(versions)
249
+ def self.tied_timestamp_pair(versions)
111
250
  versions.each_cons(2).find { |left, right| left.created_at == right.created_at }
112
251
  end
113
252
 
@@ -120,7 +259,7 @@ module PaperTrailDiff
120
259
  # distinguish the two, which is why this lives in one place: the predicate is
121
260
  # easy to write in a form that looks right and always answers true.
122
261
  #: (untyped) -> bool
123
- def versioned?(model_class)
262
+ def self.versioned?(model_class)
124
263
  model_class.respond_to?(:paper_trail_options) && !model_class.paper_trail_options.nil?
125
264
  end
126
265
 
@@ -129,20 +268,34 @@ module PaperTrailDiff
129
268
  # is cast to the key's type, or the same record read once from history and
130
269
  # once from its live row would count as two.
131
270
  #: (untyped, untyped) -> untyped
132
- def record_id(model_class, id)
271
+ def self.record_id(model_class, id)
133
272
  key = model_class.primary_key
134
- return id if id.nil? || !key.is_a?(String)
273
+ return id unless key.instance_of?(String)
135
274
 
136
275
  model_class.type_for_attribute(key).cast(id)
137
276
  end
138
277
 
278
+ # A relation's limit and offset as Active Record writes them into SQL.
279
+ # Before 8.1 it keeps a limit as given, as every version keeps an offset,
280
+ # so either may be a String, as request parameters are.
281
+ #: (untyped) -> Integer?
282
+ def self.limit(relation)
283
+ value = relation.limit_value
284
+ Integer(value) unless value.nil?
285
+ end
286
+
287
+ #: (untyped) -> Integer
288
+ def self.offset(relation)
289
+ relation.offset_value.to_i
290
+ end
291
+
139
292
  #: (untyped) -> bool
140
- def sequential_id?(id)
141
- id.is_a?(Integer) || id.to_s.match?(/\A\d+\z/)
293
+ def self.sequential_id?(id)
294
+ id.instance_of?(Integer) || id.to_s.match?(/\A\d+\z/)
142
295
  end
143
296
 
144
297
  #: (Array[untyped]) -> String
145
- def ambiguous_message(pair)
298
+ def self.ambiguous_message(pair)
146
299
  left, right = pair
147
300
  "versions #{left.id.inspect} and #{right.id.inspect} share the timestamp " \
148
301
  "#{left.created_at.inspect} and have ids that do not order them, so their " \
@@ -151,44 +304,41 @@ module PaperTrailDiff
151
304
  end
152
305
 
153
306
  #: (untyped, untyped) -> Integer
154
- def compare_versions(left, right)
307
+ def self.compare_versions(left, right)
155
308
  chronological_version_key(left) <=> chronological_version_key(right) ||
156
309
  raise(ConfigurationError, 'versions have incomparable timestamps')
157
310
  end
158
311
 
159
312
  #: (String, String | Symbol) -> String
160
- def association_path(parent, name)
313
+ def self.association_path(parent, name)
161
314
  parent.empty? ? name.to_s : "#{parent}.#{name}"
162
315
  end
163
316
 
317
+ # Groups of one name are joined: their ids, and their owners where both
318
+ # know some. A group that knows none has no :owners key.
164
319
  #: (Hash[String, Hash[Symbol, untyped]], Hash[String, Hash[Symbol, untyped]]) -> Hash[String, Hash[Symbol, untyped]]
165
- def merge_record_groups(existing, incoming)
320
+ def self.merge_record_groups(existing, incoming)
166
321
  existing.merge(incoming) do |_name, left, right|
167
322
  merged = left.merge(right, ids: (left.fetch(:ids) | right.fetch(:ids)))
168
- owners = merge_record_owners(left[:owners], right[:owners])
169
- owners ? merged.merge(owners: owners) : merged
323
+ next merged unless left.key?(:owners) && right.key?(:owners)
324
+
325
+ owners = left.fetch(:owners).merge(right.fetch(:owners)) do |_owner, first, second|
326
+ first | second
327
+ end
328
+ merged.merge(owners: owners)
170
329
  end
171
330
  end
172
331
 
173
332
  #: (untyped) -> untyped
174
- def duplicate_and_freeze(value)
333
+ def self.duplicate_and_freeze(value)
175
334
  value.dup.freeze
176
335
  rescue TypeError
177
336
  value
178
337
  end
179
338
  private_class_method :duplicate_and_freeze
180
339
 
181
- #: (Hash[String, Array[untyped]]?, Hash[String, Array[untyped]]?) -> Hash[String, Array[untyped]]?
182
- def merge_record_owners(left, right)
183
- return right unless left
184
- return left unless right
185
-
186
- left.merge(right) { |_owner, first, second| first | second }
187
- end
188
- private_class_method :merge_record_owners
189
-
190
340
  #: (untyped) -> bool
191
- def paper_trail_diff_value?(value)
341
+ def self.paper_trail_diff_value?(value)
192
342
  class_name = value.class.name
193
343
  class_name&.start_with?('PaperTrailDiff::') && value.respond_to?(:to_h)
194
344
  end
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module PaperTrailDiff
5
+ # Reads every value of a `time` column on 2000-01-01, in its own zone.
6
+ #
7
+ # A time column keeps only the time, but Active Record before 8.1 gives a
8
+ # zone-aware one a date two ways: assigned, it falls on 2000-01-01 in the
9
+ # time zone; read from the database, on 2000-01-01 in UTC. A version rebuilt
10
+ # by assignment and the row read for the same time could then hold it a day
11
+ # apart, east of UTC in the morning and west of it in the evening, and
12
+ # compare as a change. Every side is read the way Active Record 8.1 reads
13
+ # both, which leaves a value already on that date as it is.
14
+ module TimeOfDay
15
+ @columns = {} #: Hash[untyped, Array[String]]
16
+
17
+ #: (untyped, Hash[untyped, untyped]) -> Hash[untyped, untyped]
18
+ def self.apply(model_class, attributes)
19
+ columns = columns(model_class)
20
+ return attributes if columns.empty?
21
+
22
+ attributes.to_h do |name, value|
23
+ [name, columns.include?(name) && value ? value.change(**Support::TIME_OF_DAY_DATE) : value]
24
+ end
25
+ end
26
+
27
+ # The model's `time` columns, which a model keeps as it was defined.
28
+ #: (untyped) -> Array[String]
29
+ def self.columns(model_class)
30
+ known = @columns #: Hash[untyped, Array[String]]
31
+ known.fetch(model_class) do
32
+ known[model_class] = model_class.attribute_types.filter_map do |name, type|
33
+ name if type.type == :time
34
+ end
35
+ end
36
+ end
37
+ private_class_method :columns
38
+ end
39
+ end