Commit 68b68798 authored by Peter Leitzen's avatar Peter Leitzen

Implement custom AR type JsonPgSafe

Extends Rails' ActiveRecord::Type::Json data type to remove JSON encoded
null bytes `\u0000` to prevent PostgreSQL errors like
`PG::UntranslatableCharacter: ERROR: unsupported Unicode escape
sequence`.
parent 01dd30cc
# frozen_string_literal: true
module Gitlab
module Database
module Type
# Extends Rails' ActiveRecord::Type::Json data type to remove JSON
# encooded nullbytes `\u0000` to prevent PostgreSQL errors like
# `PG::UntranslatableCharacter: ERROR: unsupported Unicode escape
# sequence`.
#
# Example:
#
# class SomeModel < ApplicationRecord
# # some_model.a_field is of type `jsonb`
# attribute :a_field, Gitlab::Database::Type::JsonPgSafe.new
# end
class JsonPgSafe < ActiveRecord::Type::Json
def serialize(value)
super&.gsub('\u0000', '')
end
end
end
end
end
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::Database::Type::JsonPgSafe do
let(:type) { described_class.new }
describe '#serialize' do
using RSpec::Parameterized::TableSyntax
subject { type.serialize(value) }
where(:value, :json) do
nil | nil
1 | '1'
1.0 | '1.0'
"str\0ing\u0000" | '"string"'
["\0arr", "a\u0000y"] | '["arr","ay"]'
{ "key\0" => "value\u0000\0" } | '{"key":"value"}'
end
with_them do
it { is_expected.to eq(json) }
end
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment