我正在使用多维数组,我注意到postgres需要使用casted表达式来插入值,例如:
CREATE TABLE test (
pay integer[]
);
CREATE TABLE
INSERT INTO test values (ARRAY[NULL]);
ERROR: column "pay" is of type integer[] but expression is of type text[]
LINE 1: INSERT INTO test values (ARRAY[NULL]);
^
HINT: You will need to rewrite or cast the expression.
INSERT INTO test values (ARRAY[NULL::integer]); -- How to do this on SqlAlchemy ?
INSERT 0 1 -- ARRAY[NULL]::integer[] would also works
这是我添加对象时SqlAlchemy正在做的事情,如果VALUE为NULL,它不会进行类型转换。这是我的代码的一部分:
from sqlalchemy.dialects.postgresql import ARRAY
class Test (Base):
__tablename__ = 'test'
pay = Column(ARRAY(Integer))
member = Test()
member.pay = [None]
session.add(member)
session.commit()
然后在postgres日志中我得到:
ERROR: column "pay" is of type integer[] but expression is of type text[] at character 26
HINT: You will need to rewrite or cast the expression.
STATEMENT: INSERT INTO test (pay) VALUES (ARRAY[NULL]); -- See ?? No casting from SqlAlchemy
所以问题是:当列表中的值为None时,我能为SqlAlchemy做什么才能进行类型转换?也许是一些自定义类型的实现?
答案 0 :(得分:1)
这似乎是psycopg2中的一个遗漏;从2.4.6升级到2.6.2修复它。当然感谢SQLA作者@zzzeek
答案 1 :(得分:0)
看起来你正试图插入
VALUES(ARRAY [NULL])
它正在读作
VALUES('ARRAY [NULL]')
而您实际想要插入的是
VALUES({NULL})
或
VALUES({})
即。一个空数组。