asyncpg icon indicating copy to clipboard operation
asyncpg copied to clipboard

Access Provided Codecs at Runtime

Open seandstewart opened this issue 3 years ago • 1 comments

  • asyncpg version: 0.25.0
  • PostgreSQL version: 12
  • Do you use a PostgreSQL SaaS? If so, which? Can you reproduce the issue with a local PostgreSQL install?: n/a
  • Python version: 3.9
  • Platform: MacOS and Linux
  • Do you use pgbouncer?: no
  • Did you install asyncpg with pip?: yes
  • If you built asyncpg locally, which version of Cython did you use?: n/a
  • Can the issue be reproduced under both asyncio and uvloop?: n/a

Hello - I was wondering if it's possible to access the provided codecs for types such as Range at runtime?

Use-case: I'd like to pass my objects in as a JSON array rather than an array of composite types. However, one field is a Range type, which isn't json-encodable by default. I was hoping to use your optimized encoders when we encounter such types.

seandstewart avatar May 16 '22 23:05 seandstewart

import asyncpg
from asyncpg import range as asyncpg_range

# Define a custom encoder function for the Range type
def encode_range(range_obj):
    return f"[{range_obj.lower},{range_obj.upper})"

# Register the custom codec
asyncpg_range.Range._binary_encoder = encode_range

# Create a connection pool with the custom codec
async def create_db_pool():
    pool = await asyncpg.create_pool(
        dsn="postgres://....",
        host="....amazonaws.com",
        user="xxx",
        database="yyy",
        port="5432",
        password="12345"
    )
    return pool

ljluestc avatar Jan 15 '24 00:01 ljluestc