python - SQLAlchemy 中的 PostgreSQL 多维数组

标签 python multidimensional-array sqlalchemy

我在 Debian squeeze 上使用 SQLAlchemy 0.6.3 和 PostgreSQL 8.4。我想要一个表,其中一列在 PostgreSQL 中存储一些东西,在 Python 中显示为整数列表或整数元组的列表。例如

((1,2), (3,4), (5,6,7))

在下面的示例中,该列是 model。我认为一个合理的方法可能是将内容存储为 PG 二维表,在 PG 中它看起来像 integer[][]。我不知道 SQLA 将以何种形式将其返回给 Python,但我希望它是元组中的元组之类的东西。

但是,我不知道如何告诉 SQLA 给我一个二维整数数组。 documentation对于 sqlalchemy.dialects.postgresql.ARRAY

item_type – The data type of items of this array. Note that dimensionality is irrelevant here, so multi-dimensional arrays like INTEGER[][], are constructed as ARRAY(Integer), not as ARRAY(ARRAY(Integer)) or such. The type mapping figures out on the fly.

不幸的是,我不知道那是什么意思。类型映射如何即时解决这个问题?它需要创建正确的 DDL。 我对如何执行此操作的第一个也是唯一的猜测是 ARRAY(ARRAY(Integer))。目前我有

  crossval_table = Table(
        name, meta,
        Column('id', Integer, primary_key=True),
        Column('created', TIMESTAMP(), default=now()),
        Column('sample', postgresql.ARRAY(Integer)),
        Column('model', postgresql.ARRAY(Integer)),
        Column('time', Float),
        schema = schema,

这将创建以下 DDL

CREATE TABLE crossval (
    id integer NOT NULL,
    created timestamp without time zone,
    sample integer[],
    model integer[],
    "time" double precision
);

当然,这是不对的。我错过了什么?

最佳答案

我在这里回答这个问题,因为 Mike Bayer 在 sqlalchemy 用户上回答了这个问题。

参见 thread在 sqlalchemy-user 上,Mike Bayer 回答了这个问题。正如迈克所澄清的那样,正如我在阅读 PG 文档时所遗漏的那样,PG 实际上并没有强制执行数组维度,SQLA 也没有。因此,可以编写 integer[][],但 PG 的处理方式与 integer[] 没有任何区别。特别是,PG 和 SQLA 都将接受任何维度的数组表达式。我不确定为什么会这样。正如 Mike 所引用的,PG Arrays documentation

The current implementation does not enforce the declared number of dimensions either. Arrays of a particular element type are all considered to be of the same type, regardless of size or number of dimensions. So, declaring the array size or number of dimensions in CREATE TABLE is simply documentation; it does not affect run-time behavior.

另见 ticket他打开。 看起来这是在 SQLA 级别强制执行维度。

关于python - SQLAlchemy 中的 PostgreSQL 多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9729175/

相关文章:

c++ - 使用文本文件 C++ 初始化数组的更快方法

创建一个多维数组以在 C 中存储许多不同大小的数组

python - 在python中获取列组合及其各自索引的乘积的最大值

javascript - 如何找到完整的二维数组行行?

python - gVim 与可移植 python ?

python - sqlalchemy 关系隐式诱导连接

python - 使用 Python 和 SQLAlchemy 从 Google Cloud Function 连接到 Cloud SQL

python - 如何查询数据库以获得一个列表,其中每个值是具有相同日期值的记录数之和?

python - Plotly-Dash:如何提高绘图对 slider 更改的响应能力

python - 解包函数参数