7

SqlAlchemy 通过方言支持大多数数据库特定的数据类型,但我找不到任何可以使用 postgresql xml 列类型的东西。有人知道可行的解决方案吗?理想情况下,它不应该需要我自己的自定义列类型实现。

4

2 回答 2

3

如果您需要在 postgresql 数据库中具有本机 'xml' 数据类型,则需要编写从UserDefinedType而不是从 TypeDecorator 继承的自定义类型。文档

这是我在其中一个项目中使用的:

import xml.etree.ElementTree as etree
import sqlalchemy

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
于 2016-12-20T05:28:05.313 回答
0

请参阅:SQLAlchemy TypeDecorator 不起作用

这是修改后的相同解决方案,以处理具有任意 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)
于 2015-10-30T15:13:40.320 回答