4

Postgres 版本:9.1.x。

假设我有以下架构:

DROP TABLE IF EXISTS posts CASCADE;
DROP TYPE IF EXISTS quotes CASCADE;

CREATE TYPE quotes AS
(
  text  CHARACTER VARYING,
  is_direct CHARACTER VARYING
);

CREATE TABLE posts
(
    body  CHARACTER VARYING,
    q     quotes[]
);

我希望执行以下插入,显示在 SQL 中,但来自 Python Psycopg2。

insert into posts(body,q) VALUES('ninjas rock',ARRAY[ ROW('I AGREE',True)::quotes, ROW('I DISAGREE',FALSE)::quotes ]);

实现这一点的语法是什么(没有循环等)。我确信这是可能的,因为文档说 “在 2.4.3 版中更改:添加了对复合类型数组的支持”。该文档仅显示SELECT语句示例。

注意:我的客户端代码中有一个字典列表,它们在概念上映射到上面的伪模式。

编辑:

嗯,我一定错过了文档中的这一点:“从 Python 元组到复合类型的适应是自动的,不需要适配器注册。” . 现在要弄清楚数组部分。

编辑2:

%s当传递的数据类型是list(tuple)或时, psycopg2 的占位符应该起作用list(dict)。必须测试一下:D

编辑3: 差不多就在那里,在这种情况下,字典不起作用,列表起作用,元组起作用。但是,我需要将元组字符串表示形式转换为复合记录类型。

这个 :

quote_1 = ("monkeys rock", "False")
quote_2 = ("donkeys rock",  "True")
q_list = [ quote_1, quote_2]
print cur.mogrify("insert into posts VALUES(%s,%s)", ("animals are good", q_list))

创建以下字符串:

insert into posts VALUES('animals are good',ARRAY[('monkeys rock', 'false'), ('donkeys rock', 'true')])

这会产生以下错误:

psycopg2.ProgrammingError: column "q" is of type quotes[] but expression is of type record[]
4

1 回答 1

6

稍微扩展你的努力,怎么样:

quote_1 = ("monkeys rock", "False")
quote_2 = ("donkeys rock",  "True")
q_list = [ quote_1, quote_2]
print cur.mogrify("insert into posts VALUES(%s,%s::quotes[])", 
                  ("animals are good", q_list))
#
#                 added explicit cast to quotes[]->^^^^^^^^

说明

如果你运行:

insert into posts 
VALUES('animals are good', ARRAY[
    ('monkeys rock', 'false'),
    ('donkeys rock', 'true')
]);

直接在psql你会得到:

regress=# insert into posts 
regress-# VALUES('animals are good',ARRAY[
regress-#             ('monkeys rock', 'false'),
regress-#             ('donkeys rock', 'true')
regress-#  ]);
ERROR:  column "q" is of type quotes[] but expression is of type record[]
LINE 1: insert into posts VALUES('animals are good',ARRAY[('monkeys ...
                                                    ^
HINT:  You will need to rewrite or cast the expression.

果然,告诉 Pg 你的匿名数组是类型quotes[]就可以了:

regress=# insert into posts 
regress-# VALUES('animals are good',ARRAY[
regress-#           ('monkeys rock', 'false'),
regress-#           ('donkeys rock', 'true')
regress-# ]::quotes[]);
INSERT 0 1

regress=# select * from posts;
       body       |                           q                            
------------------+--------------------------------------------------------
 animals are good | {"(\"monkeys rock\",false)","(\"donkeys rock\",true)"}
(1 row)
于 2012-08-15T01:30:16.657 回答