使用sqlalchemy的postgresql xml数据类型

时间:2013-04-22 17:50:48

标签: python xml sqlalchemy postgresql-9.2

SqlAlchemy通过方言支持大多数特定于数据库的数据类型,但我找不到任何与postgresql xml列类型一起使用的东西。有人知道一个有效的解决方案。理想情况下,我自己不应该要求自定义列类型。

2 个答案:

答案 0 :(得分:2)

如果你需要 native' xml'在postgresql数据库中的数据类型,您需要编写继承自 UserDefinedType 的自定义类型,而不是来自TypeDecorator。 Documentation

以下是我在其中一个项目中使用的内容:

class XMLType(sqlalchemy.types.UserDefinedType):
    def get_col_spec(self):
        return 'XML'

    def bind_processor(self, dialect):
        def process(value):
            if value is not None:
                if isinstance(value, str):
                    return value
                else:
                    return etree.tostring(value)
            else:
                return None
        return process

    def result_processor(self, dialect, coltype):
        def process(value):
            if value is not None:
                value = etree.fromstring(value)
            return value
        return process

答案 1 :(得分:0)

请参阅:SQLAlchemy TypeDecorator doesn't work

以下是相同的解决方案,用于处理具有任意长度xml的oracle的XMLTYPE,并允许lxml etree分配到类列和从类列分配(不需要从容器类中解析/重新分析xml)

# coding: utf-8
from sqlalchemy import Column, DateTime, Float, ForeignKey, Index, Numeric, String, Table, Text, CLOB
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.sql.functions import GenericFunction
class XMLTypeFunc(GenericFunction):
    type=CLOB
    name='XMLType'
    identifier='XMLTypeFunc'


from sqlalchemy.types import TypeDecorator
from lxml import etree #you can use built-in etree if you want
class XMLType(TypeDecorator):

    impl = CLOB
    type = 'XMLTYPE' #etree.Element

    def get_col_spec(self):
        return 'XMLTYPE'

    def bind_processor(self, dialect):
        def process(value):
            if value is not None:
                return etree.tostring(value, encoding='UTF-8', pretty_print='True')
                #return etree.dump(value)
            else:
                return None
        return process

    def process_result_value(self, value, dialect):
        if value is not None:
            value = etree.fromstring(value)
        return value

    def bind_expression(self, bindvalue):
        return XMLTypeFunc(bindvalue)