问题
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