Skip to content

Optionally allow JSON encode/decode #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions codecs/__init__.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ cdef class CodecContext:

cpdef get_text_codec(self)
cdef is_encoding_utf8(self)
cpdef get_json_decoder(self)
cdef is_decoding_json(self)
cpdef get_json_encoder(self)
cdef is_encoding_json(self)


ctypedef object (*encode_func)(CodecContext settings,
Expand Down
12 changes: 12 additions & 0 deletions codecs/context.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,15 @@ cdef class CodecContext:

cdef is_encoding_utf8(self):
raise NotImplementedError

cpdef get_json_decoder(self):
raise NotImplementedError

cdef is_decoding_json(self):
raise NotImplementedError

cpdef get_json_encoder(self):
raise NotImplementedError

cdef is_encoding_json(self):
raise NotImplementedError
30 changes: 29 additions & 1 deletion codecs/json.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ cdef jsonb_encode(CodecContext settings, WriteBuffer buf, obj):
char *str
ssize_t size

if settings.is_encoding_json():
obj = settings.get_json_encoder().encode(obj)

as_pg_string_and_size(settings, obj, &str, &size)

if size > 0x7fffffff - 1:
Expand All @@ -26,4 +29,29 @@ cdef jsonb_decode(CodecContext settings, FRBuffer *buf):
if format != 1:
raise ValueError('unexpected JSONB format: {}'.format(format))

return text_decode(settings, buf)
rv = text_decode(settings, buf)

if settings.is_decoding_json():
rv = settings.get_json_decoder().decode(rv)

return rv


cdef json_encode(CodecContext settings, WriteBuffer buf, obj):
cdef:
char *str
ssize_t size

if settings.is_encoding_json():
obj = settings.get_json_encoder().encode(obj)

text_encode(settings, buf, obj)


cdef json_decode(CodecContext settings, FRBuffer *buf):
rv = text_decode(settings, buf)

if settings.is_decoding_json():
rv = settings.get_json_decoder().decode(rv)

return rv