psycopg2 difficuty在调用postgres存储函数时格式化用户定义类型的数组

时间:2013-02-15 07:31:43

标签: python postgresql psycopg2

我使用postgres 9.1和python 2.7与psycopg2。我有一个用户定义的类型,如

CREATE TYPE RegCompT AS (short_name VARCHAR, description VARCHAR, currency CHAR(3), NumId INTEGER);
CREATE OR REPLACE FUNCTION cw.create_tree( IN treespec RegCompT[] )...

我试图在python中创建这种类型的对象数组并调用这个存储的函数。这是我的python代码:

import os, sys, csv, psycopg2
import psycopg2.extensions as ps2e
# -- see http://initd.org/psycopg/docs/advanced.html#adapting-new-python-types-to-sql-syntax
class RegDefT(object):
    def __init__(self, row): 
        self.short_name, self.desc, self.currency, self.N = row[0:4]

def adapt_RegDefT(x):
    return ps2e.AsIs("'(%s, %s, %s, %s)'" % (ps2e.adapt(x.short_name), ps2e.adapt(x.desc), ps2e.adapt(x.currency), ps2e.adapt(x.N)))  
ps2e.register_adapter( RegDefT, adapt_RegDefT )

# -- some regions
region_defs = []
region_defs.append( RegDefT( ["NA", "North America", "USD", 10] ) )
region_defs.append( RegDefT( ["EMEA", "Europe Middle-east Africa", "EUR", 11] ) )
region_defs.append( RegDefT( ["APAC", "Asia Pacific", "USD", 20] ) )

# using it
try:
    dbcon = psycopg2.connect( "dbname=lab" )
    curs = dbcon.cursor()
    qs = "select * from cw.create_tree(%s)"
    print "SQL GENERATED:", curs.mogrify( qs, [region_defs] )
    curs.execute( qs, [region_defs] )
except Exception, e:
    print "failed to execute:", qs, e

但是它产生的东西既不通过python也不通过psql:

SQL GENERATED: select * from cw.create_tree(ARRAY['('NA', 'North America', 'USD', 10)', '('EMEA', 'Europe Middle-east Africa', 'EUR', 11)', '('APAC', 'Asia Pacific', 'USD', 20)'])
failed to execute: select * from cw.create_tree(%s) syntax error at or near "NA"
LINE 1: select * from cw.create_tree(ARRAY['('NA', 'North America', ...

我认为postgresql想要的是数组说明符的不同格式 - 不引用字符串,而不是'(但是“(而不是”ARRAY [“但是'{。

select * from cw.create_tree( '{"(NA, North America, USD, 10)", 
                                "(EMEA, Europe Middle-east Africa, EUR, 11)",
                                "(APAC, Asia Pacific, USD, 20)" }');

在python结束时出了什么问题?或者是否可以在postgresql中设置一些选项以接受数组的替代规范? psycopg2的版本在zypper中显示为python-psycopg2-2.4.5-3.1.2.x86_64 - 这是适当的版本吗?

由于

0 个答案:

没有答案