psycopg2 register_composite from sqlalchemy

纵然是瞬间 提交于 2021-01-27 12:56:58

问题


is it possible to somehow use function register_composite from psycopg2, when i am using sqlalchemy to connect to postgresql database?

My problem is that I want SQLAlchemy to handle custom composite type that i created in postgresql like this:

CREATE TYPE card AS (value int, suit text);

Sqlalchemy returns me values of this type as an string and I would like to somhow learn sqlalchemy my new type. If found some information about creating custom composite types in SQL alchemy ORM, but I am using just SQLAlechemy Core API (not ORM) and somebody on sqlalchemy IRC told me that psycopg should do it for me.

I would be happy with any advice, that would solve this.

Thank you Josh


回答1:


You can use the psycopg2 function register_composite from sqlalchemy but you have to

import psycopg2.extras

yourself, then with your connection object c from

c = e.connect()

just do

psycopg2.extras.register_composite('card', c.connection, globally=True)

You have to use c.connection because

>>> hasattr(c.connection, 'cursor')
True



回答2:


Ok so, I will answer myself :)

I have not found any way how to access to method register_composite of psycopg2 from sqlalchemy core api. But i am able to register new type via psycopg2 methods new_type and register_adapter. Tutorial can be found here. This methods allows you to register mapping from sql representation to python class and the other way.

From SQLAlechemy connection you can access these methods like this:

from sqlalchemy import *
e = create_engine("postgresql://xxx:xxx@localhost:5432/db")
c = e.connect()
c.dialect.dbapi.extensions.register_adapter
c.dialect.dbapi.extensions.new_type


来源:https://stackoverflow.com/questions/7243495/psycopg2-register-composite-from-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!