Skip to content

Commit 45e685e

Browse files
committed
Another case for backwards compatibility — bad configuration
Warn about data to migrate, while still allowing to read it with some performance impact.
1 parent 540854b commit 45e685e

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

ruby_event_store-active_record/lib/ruby_event_store/active_record/event_repository.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,33 @@ def initialize(model_factory: WithDefaultModels.new, serializer:)
3232
@event_klass.include(SkipJsonSerialization)
3333
end
3434
@repo_reader = EventRepositoryReader.new(@event_klass, @stream_klass, serializer)
35+
EventRepositoryReader.prepend(
36+
Module.new do
37+
def unwrap(column_name, deserialized_payload)
38+
case deserialized_payload
39+
when String
40+
warn "Double serialization of #{column_name} column detected"
41+
JSON.parse(deserialized_payload)
42+
else
43+
deserialized_payload
44+
end
45+
end
46+
47+
def record(...)
48+
record_ = super
49+
50+
Record.new(
51+
event_id: record_.event_id,
52+
metadata: unwrap("metadata", record_.metadata),
53+
data: unwrap("data", record_.data),
54+
event_type: record_.event_type,
55+
timestamp: record_.timestamp,
56+
valid_at: record_.valid_at,
57+
)
58+
end
59+
end,
60+
) if serializer == JSON && json_data_type?
61+
3562
@index_violation_detector = IndexViolationDetector.new(@event_klass.table_name, @stream_klass.table_name)
3663
end
3764

ruby_event_store-active_record/spec/event_repository_spec.rb

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,29 @@ module ActiveRecord
311311
}.not_to raise_error
312312
end
313313

314+
specify "JSON/B backwards compatibility — with mistakenly configured double serialization" do
315+
skip unless %w[json jsonb].include?(ENV["DATA_TYPE"])
316+
317+
repository = EventRepository.new(serializer: JSON)
318+
repository.append_to_stream(
319+
[SRecord.new(data: JSON.dump({ "simulate" => "double" }))],
320+
Stream.new("stream"),
321+
ExpectedVersion.any,
322+
)
323+
repository.append_to_stream(
324+
[SRecord.new(data: { "simulate" => "single" })],
325+
Stream.new("stream"),
326+
ExpectedVersion.any,
327+
)
328+
329+
expect(repository.read(specification.backward.limit(1).result).first.data).to eq({ "simulate" => "single" })
330+
expect {
331+
expect(repository.read(specification.forward.limit(1).result).first.data).to eq({ "simulate" => "double" })
332+
}.to output(<<~MSG).to_stderr
333+
Double serialization of data column detected
334+
MSG
335+
end
336+
314337
private
315338

316339
def with_precision(time)

0 commit comments

Comments
 (0)