7

SqlAlchemy は方言を介してほとんどのデータベース固有のデータ型をサポートしていますが、postgresql xml 列型で機能するものは見つかりませんでした。誰かが実用的な解決策を知っていますか。理想的には、自分でカスタム列タイプを実装する必要はありません。

4

2 に答える 2

3

Postgresql データベースにネイティブの 'xml' データ型が必要な場合は、TypeDecorator からではなく UserDefinedType から継承したカスタム型を記述する必要があります。ドキュメンテーション

プロジェクトの1つで使用したものは次のとおりです。

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 に答える