Skip to content
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

Easy way to use python dict as postgresql composite #349

Closed
Piatachock opened this issue Aug 24, 2018 · 1 comment
Closed

Easy way to use python dict as postgresql composite #349

Piatachock opened this issue Aug 24, 2018 · 1 comment

Comments

@Piatachock
Copy link

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?

elprans added a commit that referenced this issue Aug 26, 2018
This allows asyncpg to take an arbitrary mapping as input for composite
types, as long as the keys match composite type fields.
This allows removing some tedium when handling complex composite types.

Fixes: #349.
@elprans
Copy link
Member

elprans commented Aug 26, 2018

This seems useful. I implemented support for mappings as composite input in #351.

elprans added a commit that referenced this issue Sep 7, 2018
This allows asyncpg to take an arbitrary mapping as input for composite
types, as long as the keys match composite type fields.
This allows removing some tedium when handling complex composite types.

Fixes: #349.
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

No branches or pull requests

2 participants