Skip to content

Commit

Permalink
Optionally allow JSON encode/decode
Browse files Browse the repository at this point in the history
  • Loading branch information
fantix committed Oct 28, 2022
1 parent e7f1a02 commit c4fcf43
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
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
10 changes: 9 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,9 @@ 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

0 comments on commit c4fcf43

Please sign in to comment.