psycopg2字符串组合错误

时间:2018-01-08 02:39:57

标签: psycopg2 psql

我正在做一个upsert。

POST liferay-20116/_suggest 
{
  "my-suggester": {
    "text": "service",
    "completion": {
      "field": "suggest"
    }
  }
}

语句:

owner.sq_properties = ['name', 'place', 'email_address',                      'preferred_transport', 'note', 'address_line_one',                      'address_line_two', 'address_line_three', 'contact_one',                'contact_two', 'contact_three', 'gst_number', 'nickname']

执行时:

sq = sql.SQL("insert into master.customer select * from public.customer on conflict (id) do update set({})=({})").format(sql.SQL(',').join(sql.Identifier(n) for n in owner.sq_properties),sql.SQL(',').join(sql.Identifier("excluded."+n) for n in owner.sq_properties))

输出是:

print(sq.as_string(cursor)) 

错误:

insert into master.customer select * from public.customer on conflict (id) do update set ("name", "place", "email_address", "preferred_transport", "note", "address_line_one", "address_line_two", "address_line_three", "contact_one", "contact_two", "contact_three", "gst_number", "nickname") = ("excluded.name", "excluded.place", "excluded.email_address", "excluded.preferred_transport", "excluded.note", "excluded.address_line_one", "excluded.address_line_two", "excluded.address_line_three", "excluded.contact_one", "excluded.contact_two", "excluded.contact_three", "excluded.gst_number", "excluded.nickname")

我做错了什么?

1 个答案:

答案 0 :(得分:0)

想出来。 excluded.应该是一个sql标识符。

joined =sql.SQL(',').join(sql.SQL('excluded.')+sql.Identifier(n) for n in owner.sq_properties)

更正声明:

sql.SQL("insert into master.customer select * from public.customer on conflict (id) do update set ({}) = ({})      returning id").format(sql.SQL(',').join(sql.Identifier(n) for n in owner.sq_properties), joined)