Skip to content

JSONB is not automatically decoded#273

Closed
mosquito wants to merge 1 commit into
MagicStack:masterfrom
mosquito:master
Closed

JSONB is not automatically decoded#273
mosquito wants to merge 1 commit into
MagicStack:masterfrom
mosquito:master

Conversation

@mosquito

@mosquito mosquito commented Mar 14, 2018

Copy link
Copy Markdown

JSONB column is not automatically decoded.

Workaround for me is:

async def set_json_charset(connection):
    await connection.set_type_codec(
        'jsonb',
        encoder=lambda x: x,
        decoder=ujson.loads,
        schema='pg_catalog'
    )

    await Pool("postgresql://127.0.0.1/template0", init=set_json_charset)

@elprans

elprans commented Mar 14, 2018

Copy link
Copy Markdown
Member

Not decoding JSON data automatically is by design.

@elprans elprans closed this Mar 14, 2018
@mosquito

Copy link
Copy Markdown
Author

IMHO is't so strange. Jsonb fields serializes automatically while inserts but select returns string.

@elprans

elprans commented Mar 14, 2018

Copy link
Copy Markdown
Member

Jsonb fields serializes automatically

It doesn't:

import asyncio
import asyncpg
import json


async def test():
    conn = await asyncpg.connect()
    try:
        await conn.execute('CREATE TABLE tab(a jsonb);')
        await conn.execute('INSERT INTO tab(a) VALUES($1)', {'foo': 'bar'})
        print(json.dumps(dict(await conn.fetchrow('SELECT * FROM tab'))))
    finally:
        await conn.execute('DROP TABLE tab')
        await conn.close()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(test())
  File "asyncpg/protocol/codecs/json.pyx", line 13, in asyncpg.protocol.protocol.jsonb_encode
    as_pg_string_and_size(settings, obj, &str, &size)
  File "asyncpg/protocol/codecs/text.pyx", line 12, in asyncpg.protocol.protocol.as_pg_string_and_size
    raise TypeError('expected str, got {}'.format(type(obj).__name__))
TypeError: expected str, got dict

@mosquito

mosquito commented Mar 14, 2018

Copy link
Copy Markdown
Author

hmmm... ok. My mistake. asyncpgsa serializes it. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants