e 是我的引擎,我可以使用它进行常规选择、插入等操作,但是当我想做一个“选择或忽略”类型的任务时,我会得到一个奇怪的行为:
e.execute('insert into users (username) select %s where not exists (select 1 from users where username = %s);', 'toto', 'toto')
我得到:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1416, in _cursor_executemany
context)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/default.py", line 298, in do_executemany
cursor.executemany(statement, parameters)
File "/projects/bin/packages/pg8000/dbapi.py", line 243, in _fn
return fn(self, *args, **kwargs)
File "/projects/bin/packages/pg8000/dbapi.py", line 370, in executemany
self._execute(operation, parameters)
File "/projects/bin/packages/pg8000/dbapi.py", line 319, in _execute
self.cursor.execute(new_query, *new_args)
File "/projects/bin/packages/pg8000/interface.py", line 301, in execute
self._stmt.execute(*args, **kwargs)
File "/projects/bin/packages/pg8000/interface.py", line 136, in execute
self._row_desc, cmd = self.c.bind(self._portal_name, self._statement_name, args, self._parse_row_desc, kwargs.get("stream"))
File "/projects/bin/packages/pg8000/protocol.py", line 933, in _fn
return fn(self, *args, **kwargs)
File "/projects/bin/packages/pg8000/protocol.py", line 1116, in bind
return reader.handle_messages()
File "/projects/bin/packages/pg8000/protocol.py", line 901, in handle_messages
retval = handler(msg, *args, **kwargs)
File "/projects/bin/packages/pg8000/protocol.py", line 1155, in _bind_nodata
reader.handle_messages()
File "/projects/bin/packages/pg8000/protocol.py", line 906, in handle_messages
raise exc
pg8000.errors.ProgrammingError: (b'ERROR', b'23505', b'duplicate key value violates unique constraint "users_pkey"')
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1790, in execute
return connection.execute(statement, *multiparams, **params)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1191, in execute
params)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1287, in _execute_text
return self.__execute_context(context)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1297, in __execute_context
context.parameters, context=context)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1423, in _cursor_executemany
context)
File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1360, in _handle_dbapi_exception
from e
sqlalchemy.exc.ProgrammingError: (ProgrammingError) (b'ERROR', b'23505', b'duplicate key value violates unique constraint "users_pkey"') 'insert into users (username) select %s where not exists (select 1 from users where username = %s);' [('x', 'o', 'x', 'o'), ('x', 'o', 'x', 'o')]
该值(xoxo)不在该表中,即使从头开始重新创建表,我也会得到相同的结果。