3

我正在尝试使用最初为 Postgres 数据库设计的 SQLAlchemy ORM 创建内存中的 SQLite 数据库。为了允许 SQLite 引擎转换 postgres 特定的数据类型,我依赖于 SQLAlchemy@compiles装饰器,它按预期用于sqlalchemy.dialects.postgresql命名空间中的类型。

如何将geoalchemy2.Raster数据类型转换为与引擎无关的数据类型(它可能是sqlalchemy.BLOB我关心的所有类型。重要的是我可以创建相似的表,它们不需要精确)?

此示例代码DOUBLE_PRECISION按预期转换类型,但我不知道如何修改geoalchemy2.Raster数据类型是UserDefinedType. 我希望能够编写一个类似的方法来将compile_DOUBLE_PRECISION()其更改RasterBLOB类型。

import sqlalchemy
from sqlalchemy import Column, Integer
from sqlalchemy.dialects.postgresql import DOUBLE_PRECISION
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.dialects.sqlite.base import SQLiteTypeCompiler
from geoalchemy2 import Raster

Base = declarative_base()

class SomeModel(Base):
    __tablename__ = "some_model"
    id = Column(Integer, primary_key=True)
    double_precision = Column(DOUBLE_PRECISION)
    raster = Column(Raster)

# The following @compiles works as intended
@compiles(DOUBLE_PRECISION, 'sqlite')
def compile_DOUBLE_PRECISION(element, compiler: SQLiteTypeCompiler, **kw):
    """ Handles postgres DOUBLE_PRECISION datatype as REAL in sqlite. """
    return compiler.visit_real(element, **kw)

def test_throws_error_due_to_raster_data_type():
    engine = sqlalchemy.create_engine("sqlite:///:memory:")
    Base.metadata.create_all(engine)
4

1 回答 1

2

我不熟悉 postgresql 但也许这样的东西可以工作

import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from geoalchemy2 import Raster

Base = declarative_base()


def raster_if_postgresql_else_blob():
    return sa.BLOB().with_variant(Raster, "postgresql")


class SomeModel(Base):
    __tablename__ = "some_model"
    id = sa.Column(sa.Integer, primary_key=True)
    raster = sa.Column(raster_if_postgresql_else_blob())


lite_engine = sa.create_engine("sqlite:///:memory:", echo=True)
Base.metadata.create_all(lite_engine)
于 2021-05-15T08:17:53.730 回答