Skip to content

Easy way to use python dict as postgresql composite #349

Closed
@Piatachock

Description

@Piatachock

Is there a way to do subj?
In Postgre, I have a table with composite type, like this:

CREATE TYPE user_info AS (
    name   text,
    surname   text,
    alias text
);

CREATE TABLE users AS (
    user_id bigserial,
    info user_info
);

In Python, I have dict reflecting composite type, like this:

data = {
    'name': 'John',
    'surname': 'Doe',
    'alias': 'Mr. Example',
}

I can't use this dict in query directly:

conn = asyncpg.connect(...)
conn.execute('INSERT INTO users (user_info) VALUES ($1)', data)  # WRONG

So I have to convert it to tuple, like this:

tuple_data = data['name'], data['surname'], data['alias']
conn.execute('INSERT INTO users (user_info) VALUES ($1)', tuple_data)

But that conversion requires me to mimic field order of postgre composite in python code, or else inserted data will be messed up.
Is there a way to insert composite column represented as key-value pairs in your code without using explicit knowledge of composite's field order?

As far as I understand, asyncpg has introspection of postgre types anyway, so maybe field order of composite types is presented inside asyncpg meta information already - so that asyncpg clients can use it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions