DataError:在PostgreSQL中插入多维数组时,数组文字格式不正确



这是我的表的简化版本:

class Alert(Base):
    __tablename__ = 'alert'
    id = Column(Integer, primary_key=True)
    created_on = Column(DateTime(timezone=True))
    category = Column(Unicode, nullable=False)
    parameters = Column(ARRAY(Unicode), nullable=True)

当试图将以下多维数组插入表中时,我收到一个DataError,告诉我我的数组格式不正确。

DataError: (DataError) malformed array literal: "numbers"
LINE 1: ...RRAY[ARRAY['key', 'sXl5SoNh0KY'], ARRAY['nu...
                                                   ^
DETAIL:  Array value must start with "{" or dimension information.
'INSERT INTO alert (created_on, category, parameters) 
VALUES (%(created_on)s, %(category)s, %(parameters)s) 
RETURNING alert.id' {
'created_on': datetime.datetime(2015, 6, 24, 1, 52, 30, 631330, tzinfo=<UTC>)
'category': u'new_cases',
'parameters':
    [[u'key', u'sXl5SoNh0KY'],
    ['numbers', [u'8129431', u'8669290', u'8754131', u'8871813', u'8927606']],
    ['status', 'all']]
}

我的印象是Postgres的ARRAY类型是多维的,无论它是如何创建的(http://thread.gmane.org/gmane.comp.python.sqlalchemy.user/31186),那么为什么会出现这种错误呢?

PostgreSQL中的数组可以是多维的,但中的所有元素都必须具有相同数量的维度(http://www.postgresql.org/docs/9.4/interactive/arrays.html),所以你可以写:

SELECT ARRAY[ARRAY[1,2], ARRAY[3,4]];
=> "{{1,2},{3,4}}"

但不是:

SELECT ARRAY[ARRAY[1,2], ARRAY[3]]
ERROR:  multidimensional arrays must have array expressions with matching dimensions

最新更新