<p dir="auto"><strong>Describe the bug</strong></p>

<p dir="auto">when using the postgres version of Insert, the <code class="notranslate"> sqlalchemy.dialects.postgresql.Insert.on_conflict_do_nothing</code> method, if you provide a <code class="notranslate">constraint</code> argument, it doesn't properly escape it, causing a SQL syntax error on a otherwise valid constraint name.</p>
<p dir="auto">if you add escaped quotes to the constraint name, it works, but I feel that sqlalchemy should escape these for you properly</p>
<div class="highlight highlight-source-python notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="
# doesn't work
do_nothing_upsert_statement = upsert_statement.on_conflict_do_nothing(constraint=&quot;IXUQ-users_found-user_name&quot;)

# works
do_nothing_upsert_statement = upsert_statement.on_conflict_do_nothing(constraint=&quot;\&quot;IXUQ-users_found-user_name\&quot;&quot;)
"><pre class="notranslate"><span class="pl-c"># doesn't work</span>
<span class="pl-s1">do_nothing_upsert_statement</span> <span class="pl-c1">=</span> <span class="pl-s1">upsert_statement</span>.<span class="pl-en">on_conflict_do_nothing</span>(<span class="pl-s1">constraint</span><span class="pl-c1">=</span><span class="pl-s">"IXUQ-users_found-user_name"</span>)

<span class="pl-c"># works</span>
<span class="pl-s1">do_nothing_upsert_statement</span> <span class="pl-c1">=</span> <span class="pl-s1">upsert_statement</span>.<span class="pl-en">on_conflict_do_nothing</span>(<span class="pl-s1">constraint</span><span class="pl-c1">=</span><span class="pl-s">"<span class="pl-cce">\"</span>IXUQ-users_found-user_name<span class="pl-cce">\"</span>"</span>)</pre></div>
<p dir="auto"><strong>To Reproduce</strong><br>
Provide your <a href="http://stackoverflow.com/help/mcve" rel="nofollow">Minimal, Complete, and Verifiable</a> example<br>
here.</p>
<p dir="auto">needs <code class="notranslate">asyncpg</code>, <code class="notranslate">sqlalchemy</code> and <code class="notranslate">sqlalchemy-repr</code> to run</p>
<div class="highlight highlight-source-python notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="import asyncio
import logging
import random

from sqlalchemy import Column, Index, Integer, Unicode, PrimaryKeyConstraint
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy_repr import RepresentableBase
from sqlalchemy.engine.url import URL
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.dialects.postgresql import insert


logging.basicConfig(level=&quot;DEBUG&quot;)
logger = logging.getLogger(&quot;main&quot;)

CustomDeclarativeBase = declarative_base(name=&quot;CustomDeclarativeBase&quot;)

class UsersFound(CustomDeclarativeBase):
    __tablename__ = &quot;users_found&quot;

    # primary key column
    user_id = Column(Integer, nullable=False, autoincrement=True)

    user_name = Column(Unicode, nullable=False)

    __table_args__ = (
        PrimaryKeyConstraint(&quot;user_id&quot;, name=&quot;PK-users_found-user_id&quot;),

        Index(&quot;IXUQ-users_found-user_name&quot;, &quot;user_name&quot;, unique=True),

    )

    def __str__(self):
        return f&quot;UsersFound(user_id={self.user_id}, user_name={self.user_name})&quot;


class ScrapeUsers:



    def __init__(self):

        self.config = None
        self.sqla_engine = None
        self.async_sessionmaker = None

    async def run(self):

        url = URL.create(drivername=&quot;postgresql+asyncpg&quot;,
            username=&quot;postgres&quot;,
            password=&quot;PASSWORD_HERE&quot;,
            host=&quot;localhost&quot;,
            port=&quot;5432&quot;,
            database=&quot;testing&quot;,
            query=None)
        self.sqla_engine = create_async_engine(url, echo=False, future=True)


        # expire_on_commit=False will prevent attributes from being expired
        # after commit.
        self.async_sessionmaker = sessionmaker(
            bind=self.sqla_engine, expire_on_commit=False, class_=AsyncSession
        )

        async with self.sqla_engine.begin() as conn:
            await conn.run_sync(CustomDeclarativeBase.metadata.create_all)

        async with self.async_sessionmaker() as session:

            name_list_letters = random.sample(&quot;abcdefghijklmnopqrstuvwxyz&quot;, 10)
            name = &quot;&quot;.join(name_list_letters)

            # do it twice to get the duplicate key error
            for i in range(2):
                # get things from the queue
                async with session.begin():

                    obj = UsersFound(user_name=name)

                    logger.info(&quot;adding: `%s`&quot;, obj)

                    list_of_dicts_to_insert = [{&quot;user_name&quot;: obj.user_name}]

                    conn = await session.connection()

                    upsert_statement = insert(UsersFound.__table__).values(list_of_dicts_to_insert)
                    do_nothing_upsert_statement = upsert_statement.on_conflict_do_nothing(constraint=&quot;IXUQ-users_found-user_name&quot;)
                    await conn.execute(do_nothing_upsert_statement)

                    session.add(obj)

        await self.sqla_engine.dispose()
        await asyncio.sleep(0.1)



x = ScrapeUsers()
asyncio.run(x.run(), debug=False)"><pre class="notranslate"><span class="pl-k">import</span> <span class="pl-s1">asyncio</span>
<span class="pl-k">import</span> <span class="pl-s1">logging</span>
<span class="pl-k">import</span> <span class="pl-s1">random</span>

<span class="pl-k">from</span> <span class="pl-s1">sqlalchemy</span> <span class="pl-k">import</span> <span class="pl-v">Column</span>, <span class="pl-v">Index</span>, <span class="pl-v">Integer</span>, <span class="pl-v">Unicode</span>, <span class="pl-v">PrimaryKeyConstraint</span>
<span class="pl-k">from</span> <span class="pl-s1">sqlalchemy</span>.<span class="pl-s1">ext</span>.<span class="pl-s1">declarative</span> <span class="pl-k">import</span> <span class="pl-s1">declarative_base</span>
<span class="pl-k">from</span> <span class="pl-s1">sqlalchemy</span>.<span class="pl-s1">orm</span> <span class="pl-k">import</span> <span class="pl-s1">relationship</span>
<span class="pl-k">from</span> <span class="pl-s1">sqlalchemy_repr</span> <span class="pl-k">import</span> <span class="pl-v">RepresentableBase</span>
<span class="pl-k">from</span> <span class="pl-s1">sqlalchemy</span>.<span class="pl-s1">engine</span>.<span class="pl-s1">url</span> <span class="pl-k">import</span> <span class="pl-v">URL</span>
<span class="pl-k">from</span> <span class="pl-s1">sqlalchemy</span>.<span class="pl-s1">ext</span>.<span class="pl-s1">asyncio</span> <span class="pl-k">import</span> <span class="pl-s1">create_async_engine</span>
<span class="pl-k">from</span> <span class="pl-s1">sqlalchemy</span>.<span class="pl-s1">orm</span> <span class="pl-k">import</span> <span class="pl-s1">sessionmaker</span>
<span class="pl-k">from</span> <span class="pl-s1">sqlalchemy</span>.<span class="pl-s1">ext</span>.<span class="pl-s1">asyncio</span> <span class="pl-k">import</span> <span class="pl-v">AsyncSession</span>
<span class="pl-k">from</span> <span class="pl-s1">sqlalchemy</span>.<span class="pl-s1">dialects</span>.<span class="pl-s1">postgresql</span> <span class="pl-k">import</span> <span class="pl-s1">insert</span>


<span class="pl-s1">logging</span>.<span class="pl-en">basicConfig</span>(<span class="pl-s1">level</span><span class="pl-c1">=</span><span class="pl-s">"DEBUG"</span>)
<span class="pl-s1">logger</span> <span class="pl-c1">=</span> <span class="pl-s1">logging</span>.<span class="pl-en">getLogger</span>(<span class="pl-s">"main"</span>)

<span class="pl-v">CustomDeclarativeBase</span> <span class="pl-c1">=</span> <span class="pl-en">declarative_base</span>(<span class="pl-s1">name</span><span class="pl-c1">=</span><span class="pl-s">"CustomDeclarativeBase"</span>)

<span class="pl-k">class</span> <span class="pl-v">UsersFound</span>(<span class="pl-v">CustomDeclarativeBase</span>):
    <span class="pl-s1">__tablename__</span> <span class="pl-c1">=</span> <span class="pl-s">"users_found"</span>

    <span class="pl-c"># primary key column</span>
    <span class="pl-s1">user_id</span> <span class="pl-c1">=</span> <span class="pl-v">Column</span>(<span class="pl-v">Integer</span>, <span class="pl-s1">nullable</span><span class="pl-c1">=</span><span class="pl-c1">False</span>, <span class="pl-s1">autoincrement</span><span class="pl-c1">=</span><span class="pl-c1">True</span>)

    <span class="pl-s1">user_name</span> <span class="pl-c1">=</span> <span class="pl-v">Column</span>(<span class="pl-v">Unicode</span>, <span class="pl-s1">nullable</span><span class="pl-c1">=</span><span class="pl-c1">False</span>)

    <span class="pl-s1">__table_args__</span> <span class="pl-c1">=</span> (
        <span class="pl-v">PrimaryKeyConstraint</span>(<span class="pl-s">"user_id"</span>, <span class="pl-s1">name</span><span class="pl-c1">=</span><span class="pl-s">"PK-users_found-user_id"</span>),

        <span class="pl-v">Index</span>(<span class="pl-s">"IXUQ-users_found-user_name"</span>, <span class="pl-s">"user_name"</span>, <span class="pl-s1">unique</span><span class="pl-c1">=</span><span class="pl-c1">True</span>),

    )

    <span class="pl-k">def</span> <span class="pl-en">__str__</span>(<span class="pl-s1">self</span>):
        <span class="pl-k">return</span> <span class="pl-s">f"UsersFound(user_id=<span class="pl-s1"><span class="pl-kos">{</span><span class="pl-s1">self</span>.<span class="pl-s1">user_id</span><span class="pl-kos">}</span></span>, user_name=<span class="pl-s1"><span class="pl-kos">{</span><span class="pl-s1">self</span>.<span class="pl-s1">user_name</span><span class="pl-kos">}</span></span>)"</span>


<span class="pl-k">class</span> <span class="pl-v">ScrapeUsers</span>:



    <span class="pl-k">def</span> <span class="pl-en">__init__</span>(<span class="pl-s1">self</span>):

        <span class="pl-s1">self</span>.<span class="pl-s1">config</span> <span class="pl-c1">=</span> <span class="pl-c1">None</span>
        <span class="pl-s1">self</span>.<span class="pl-s1">sqla_engine</span> <span class="pl-c1">=</span> <span class="pl-c1">None</span>
        <span class="pl-s1">self</span>.<span class="pl-s1">async_sessionmaker</span> <span class="pl-c1">=</span> <span class="pl-c1">None</span>

    <span class="pl-k">async</span> <span class="pl-k">def</span> <span class="pl-en">run</span>(<span class="pl-s1">self</span>):

        <span class="pl-s1">url</span> <span class="pl-c1">=</span> <span class="pl-v">URL</span>.<span class="pl-en">create</span>(<span class="pl-s1">drivername</span><span class="pl-c1">=</span><span class="pl-s">"postgresql+asyncpg"</span>,
            <span class="pl-s1">username</span><span class="pl-c1">=</span><span class="pl-s">"postgres"</span>,
            <span class="pl-s1">password</span><span class="pl-c1">=</span><span class="pl-s">"PASSWORD_HERE"</span>,
            <span class="pl-s1">host</span><span class="pl-c1">=</span><span class="pl-s">"localhost"</span>,
            <span class="pl-s1">port</span><span class="pl-c1">=</span><span class="pl-s">"5432"</span>,
            <span class="pl-s1">database</span><span class="pl-c1">=</span><span class="pl-s">"testing"</span>,
            <span class="pl-s1">query</span><span class="pl-c1">=</span><span class="pl-c1">None</span>)
        <span class="pl-s1">self</span>.<span class="pl-s1">sqla_engine</span> <span class="pl-c1">=</span> <span class="pl-en">create_async_engine</span>(<span class="pl-s1">url</span>, <span class="pl-s1">echo</span><span class="pl-c1">=</span><span class="pl-c1">False</span>, <span class="pl-s1">future</span><span class="pl-c1">=</span><span class="pl-c1">True</span>)


        <span class="pl-c"># expire_on_commit=False will prevent attributes from being expired</span>
        <span class="pl-c"># after commit.</span>
        <span class="pl-s1">self</span>.<span class="pl-s1">async_sessionmaker</span> <span class="pl-c1">=</span> <span class="pl-en">sessionmaker</span>(
            <span class="pl-s1">bind</span><span class="pl-c1">=</span><span class="pl-s1">self</span>.<span class="pl-s1">sqla_engine</span>, <span class="pl-s1">expire_on_commit</span><span class="pl-c1">=</span><span class="pl-c1">False</span>, <span class="pl-s1">class_</span><span class="pl-c1">=</span><span class="pl-v">AsyncSession</span>
        )

        <span class="pl-k">async</span> <span class="pl-k">with</span> <span class="pl-s1">self</span>.<span class="pl-s1">sqla_engine</span>.<span class="pl-en">begin</span>() <span class="pl-k">as</span> <span class="pl-s1">conn</span>:
            <span class="pl-k">await</span> <span class="pl-s1">conn</span>.<span class="pl-en">run_sync</span>(<span class="pl-v">CustomDeclarativeBase</span>.<span class="pl-s1">metadata</span>.<span class="pl-s1">create_all</span>)

        <span class="pl-k">async</span> <span class="pl-k">with</span> <span class="pl-s1">self</span>.<span class="pl-en">async_sessionmaker</span>() <span class="pl-k">as</span> <span class="pl-s1">session</span>:

            <span class="pl-s1">name_list_letters</span> <span class="pl-c1">=</span> <span class="pl-s1">random</span>.<span class="pl-en">sample</span>(<span class="pl-s">"abcdefghijklmnopqrstuvwxyz"</span>, <span class="pl-c1">10</span>)
            <span class="pl-s1">name</span> <span class="pl-c1">=</span> <span class="pl-s">""</span>.<span class="pl-en">join</span>(<span class="pl-s1">name_list_letters</span>)

            <span class="pl-c"># do it twice to get the duplicate key error</span>
            <span class="pl-k">for</span> <span class="pl-s1">i</span> <span class="pl-c1">in</span> <span class="pl-en">range</span>(<span class="pl-c1">2</span>):
                <span class="pl-c"># get things from the queue</span>
                <span class="pl-k">async</span> <span class="pl-k">with</span> <span class="pl-s1">session</span>.<span class="pl-en">begin</span>():

                    <span class="pl-s1">obj</span> <span class="pl-c1">=</span> <span class="pl-v">UsersFound</span>(<span class="pl-s1">user_name</span><span class="pl-c1">=</span><span class="pl-s1">name</span>)

                    <span class="pl-s1">logger</span>.<span class="pl-en">info</span>(<span class="pl-s">"adding: `%s`"</span>, <span class="pl-s1">obj</span>)

                    <span class="pl-s1">list_of_dicts_to_insert</span> <span class="pl-c1">=</span> [{<span class="pl-s">"user_name"</span>: <span class="pl-s1">obj</span>.<span class="pl-s1">user_name</span>}]

                    <span class="pl-s1">conn</span> <span class="pl-c1">=</span> <span class="pl-k">await</span> <span class="pl-s1">session</span>.<span class="pl-en">connection</span>()

                    <span class="pl-s1">upsert_statement</span> <span class="pl-c1">=</span> <span class="pl-en">insert</span>(<span class="pl-v">UsersFound</span>.<span class="pl-s1">__table__</span>).<span class="pl-en">values</span>(<span class="pl-s1">list_of_dicts_to_insert</span>)
                    <span class="pl-s1">do_nothing_upsert_statement</span> <span class="pl-c1">=</span> <span class="pl-s1">upsert_statement</span>.<span class="pl-en">on_conflict_do_nothing</span>(<span class="pl-s1">constraint</span><span class="pl-c1">=</span><span class="pl-s">"IXUQ-users_found-user_name"</span>)
                    <span class="pl-k">await</span> <span class="pl-s1">conn</span>.<span class="pl-en">execute</span>(<span class="pl-s1">do_nothing_upsert_statement</span>)

                    <span class="pl-s1">session</span>.<span class="pl-en">add</span>(<span class="pl-s1">obj</span>)

        <span class="pl-k">await</span> <span class="pl-s1">self</span>.<span class="pl-s1">sqla_engine</span>.<span class="pl-en">dispose</span>()
        <span class="pl-k">await</span> <span class="pl-s1">asyncio</span>.<span class="pl-en">sleep</span>(<span class="pl-c1">0.1</span>)



<span class="pl-s1">x</span> <span class="pl-c1">=</span> <span class="pl-v">ScrapeUsers</span>()
<span class="pl-s1">asyncio</span>.<span class="pl-en">run</span>(<span class="pl-s1">x</span>.<span class="pl-en">run</span>(), <span class="pl-s1">debug</span><span class="pl-c1">=</span><span class="pl-c1">False</span>)</pre></div>
<p dir="auto"><strong>Error</strong><br>
Provide the complete text of any errors received <strong>including the complete<br>
stack trace</strong>.   If the message is a warning, run your program with the<br>
<code class="notranslate">-Werror</code> flag:   <code class="notranslate">python -Werror myprogram.py</code></p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="PS C:\Users\auror\Code\sqlalchemy_bugs&gt; python .\sqlalchemy_bug_on_confilict_do_nothing_escape.py
DEBUG:asyncio:Using proactor: IocpProactor
INFO:main:adding: `UsersFound(user_id=None, user_name=vzxwnfpjoh)`
Traceback (most recent call last):
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py&quot;, line 388, in _prepare_and_execute
    prepared_stmt, attributes = await adapt_connection._prepare(
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py&quot;, line 630, in _prepare
    prepared_stmt = await self._connection.prepare(operation)
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\asyncpg\connection.py&quot;, line 530, in prepare
    return await self._prepare(
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\asyncpg\connection.py&quot;, line 546, in _prepare
    stmt = await self._get_statement(
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\asyncpg\connection.py&quot;, line 375, in _get_statement
    statement = await self._protocol.prepare(
  File &quot;asyncpg\protocol\protocol.pyx&quot;, line 168, in prepare
asyncpg.exceptions.PostgresSyntaxError: syntax error at or near &quot;-&quot;

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\base.py&quot;, line 1770, in _execute_context
    self.dialect.do_execute(
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\default.py&quot;, line 717, in do_execute
    cursor.execute(statement, parameters)
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py&quot;, line 449, in execute
    self._adapt_connection.await_(
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\util\_concurrency_py3k.py&quot;, line 69, in await_only
    return current.driver.switch(awaitable)
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\util\_concurrency_py3k.py&quot;, line 122, in greenlet_spawn
    value = await result
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py&quot;, line 424, in _prepare_and_execute
    self._handle_exception(error)
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py&quot;, line 358, in _handle_exception
    self._adapt_connection._handle_exception(error)
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py&quot;, line 652, in _handle_exception
    raise translated_error from error
sqlalchemy.dialects.postgresql.asyncpg.ProgrammingError: &lt;class 'asyncpg.exceptions.PostgresSyntaxError'&gt;: syntax error at or near &quot;-&quot;

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File &quot;C:\Users\auror\Code\sqlalchemy_bugs\sqlalchemy_bug_on_confilict_do_nothing_escape.py&quot;, line 101, in &lt;module&gt;
    asyncio.run(x.run(), debug=False)
  File &quot;c:\python39\lib\asyncio\runners.py&quot;, line 44, in run
    return loop.run_until_complete(main)
  File &quot;c:\python39\lib\asyncio\base_events.py&quot;, line 642, in run_until_complete
    return future.result()
  File &quot;C:\Users\auror\Code\sqlalchemy_bugs\sqlalchemy_bug_on_confilict_do_nothing_escape.py&quot;, line 91, in run
    await conn.execute(do_nothing_upsert_statement)
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\ext\asyncio\engine.py&quot;, line 405, in execute
    result = await greenlet_spawn(
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\util\_concurrency_py3k.py&quot;, line 127, in greenlet_spawn
    result = context.throw(*sys.exc_info())
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\base.py&quot;, line 1582, in _execute_20
    return meth(self, args_10style, kwargs_10style, execution_options)
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\sql\elements.py&quot;, line 323, in _execute_on_connection
    return connection._execute_clauseelement(
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\base.py&quot;, line 1451, in _execute_clauseelement
    ret = self._execute_context(
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\base.py&quot;, line 1813, in _execute_context
    self._handle_dbapi_exception(
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\base.py&quot;, line 1994, in _handle_dbapi_exception
    util.raise_(
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\util\compat.py&quot;, line 207, in raise_
    raise exception
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\base.py&quot;, line 1770, in _execute_context
    self.dialect.do_execute(
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\default.py&quot;, line 717, in do_execute
    cursor.execute(statement, parameters)
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py&quot;, line 449, in execute
    self._adapt_connection.await_(
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\util\_concurrency_py3k.py&quot;, line 69, in await_only
    return current.driver.switch(awaitable)
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\util\_concurrency_py3k.py&quot;, line 122, in greenlet_spawn
    value = await result
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py&quot;, line 424, in _prepare_and_execute
    self._handle_exception(error)
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py&quot;, line 358, in _handle_exception
    self._adapt_connection._handle_exception(error)
  File &quot;C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py&quot;, line 652, in _handle_exception
    raise translated_error from error
sqlalchemy.exc.ProgrammingError: (sqlalchemy.dialects.postgresql.asyncpg.ProgrammingError) &lt;class 'asyncpg.exceptions.PostgresSyntaxError'&gt;: syntax error at or near &quot;-&quot;
[SQL: INSERT INTO users_found (user_name) VALUES (%s) ON CONFLICT ON CONSTRAINT IXUQ-users_found-user_name DO NOTHING]
[parameters: ('vzxwnfpjoh',)]
(Background on this error at: http://sqlalche.me/e/14/f405)
Exception ignored in: &lt;function _ProactorBasePipeTransport.__del__ at 0x0000020F2DF3BB80&gt;
Traceback (most recent call last):
  File &quot;c:\python39\lib\asyncio\proactor_events.py&quot;, line 116, in __del__
  File &quot;c:\python39\lib\asyncio\proactor_events.py&quot;, line 108, in close
  File &quot;c:\python39\lib\asyncio\base_events.py&quot;, line 746, in call_soon
  File &quot;c:\python39\lib\asyncio\base_events.py&quot;, line 510, in _check_closed
RuntimeError: Event loop is closed
PS C:\Users\auror\Code\sqlalchemy_bugs&gt;"><pre class="notranslate"><code class="notranslate">PS C:\Users\auror\Code\sqlalchemy_bugs&gt; python .\sqlalchemy_bug_on_confilict_do_nothing_escape.py
DEBUG:asyncio:Using proactor: IocpProactor
INFO:main:adding: `UsersFound(user_id=None, user_name=vzxwnfpjoh)`
Traceback (most recent call last):
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py", line 388, in _prepare_and_execute
    prepared_stmt, attributes = await adapt_connection._prepare(
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py", line 630, in _prepare
    prepared_stmt = await self._connection.prepare(operation)
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\asyncpg\connection.py", line 530, in prepare
    return await self._prepare(
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\asyncpg\connection.py", line 546, in _prepare
    stmt = await self._get_statement(
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\asyncpg\connection.py", line 375, in _get_statement
    statement = await self._protocol.prepare(
  File "asyncpg\protocol\protocol.pyx", line 168, in prepare
asyncpg.exceptions.PostgresSyntaxError: syntax error at or near "-"

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\base.py", line 1770, in _execute_context
    self.dialect.do_execute(
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\default.py", line 717, in do_execute
    cursor.execute(statement, parameters)
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py", line 449, in execute
    self._adapt_connection.await_(
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\util\_concurrency_py3k.py", line 69, in await_only
    return current.driver.switch(awaitable)
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\util\_concurrency_py3k.py", line 122, in greenlet_spawn
    value = await result
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py", line 424, in _prepare_and_execute
    self._handle_exception(error)
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py", line 358, in _handle_exception
    self._adapt_connection._handle_exception(error)
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py", line 652, in _handle_exception
    raise translated_error from error
sqlalchemy.dialects.postgresql.asyncpg.ProgrammingError: &lt;class 'asyncpg.exceptions.PostgresSyntaxError'&gt;: syntax error at or near "-"

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\auror\Code\sqlalchemy_bugs\sqlalchemy_bug_on_confilict_do_nothing_escape.py", line 101, in &lt;module&gt;
    asyncio.run(x.run(), debug=False)
  File "c:\python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "c:\python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\auror\Code\sqlalchemy_bugs\sqlalchemy_bug_on_confilict_do_nothing_escape.py", line 91, in run
    await conn.execute(do_nothing_upsert_statement)
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\ext\asyncio\engine.py", line 405, in execute
    result = await greenlet_spawn(
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\util\_concurrency_py3k.py", line 127, in greenlet_spawn
    result = context.throw(*sys.exc_info())
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\base.py", line 1582, in _execute_20
    return meth(self, args_10style, kwargs_10style, execution_options)
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\sql\elements.py", line 323, in _execute_on_connection
    return connection._execute_clauseelement(
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\base.py", line 1451, in _execute_clauseelement
    ret = self._execute_context(
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\base.py", line 1813, in _execute_context
    self._handle_dbapi_exception(
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\base.py", line 1994, in _handle_dbapi_exception
    util.raise_(
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\base.py", line 1770, in _execute_context
    self.dialect.do_execute(
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\engine\default.py", line 717, in do_execute
    cursor.execute(statement, parameters)
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py", line 449, in execute
    self._adapt_connection.await_(
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\util\_concurrency_py3k.py", line 69, in await_only
    return current.driver.switch(awaitable)
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\util\_concurrency_py3k.py", line 122, in greenlet_spawn
    value = await result
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py", line 424, in _prepare_and_execute
    self._handle_exception(error)
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py", line 358, in _handle_exception
    self._adapt_connection._handle_exception(error)
  File "C:\Users\auror\AppData\Local\pypoetry\Cache\virtualenvs\sqlalchemy-bugs-w_rCfYdx-py3.9\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py", line 652, in _handle_exception
    raise translated_error from error
sqlalchemy.exc.ProgrammingError: (sqlalchemy.dialects.postgresql.asyncpg.ProgrammingError) &lt;class 'asyncpg.exceptions.PostgresSyntaxError'&gt;: syntax error at or near "-"
[SQL: INSERT INTO users_found (user_name) VALUES (%s) ON CONFLICT ON CONSTRAINT IXUQ-users_found-user_name DO NOTHING]
[parameters: ('vzxwnfpjoh',)]
(Background on this error at: http://sqlalche.me/e/14/f405)
Exception ignored in: &lt;function _ProactorBasePipeTransport.__del__ at 0x0000020F2DF3BB80&gt;
Traceback (most recent call last):
  File "c:\python39\lib\asyncio\proactor_events.py", line 116, in __del__
  File "c:\python39\lib\asyncio\proactor_events.py", line 108, in close
  File "c:\python39\lib\asyncio\base_events.py", line 746, in call_soon
  File "c:\python39\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed
PS C:\Users\auror\Code\sqlalchemy_bugs&gt;
</code></pre></div>
<p dir="auto"><strong>Versions.</strong></p>
<ul dir="auto">
<li>OS: windows 10</li>
<li>Python: Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)]</li>
<li>SQLAlchemy: 1.4.20</li>
<li>Database: postgres 13.2</li>
<li>DBAPI: asyncpg 0.23.0</li>
</ul>
<p dir="auto"><strong>Additional context</strong></p>

<p dir="auto"><strong>Have a nice day!</strong></p>
<p dir="auto"><strong>Migrated issue, originally created by Adrian (<a href="https://github.com/thiefmaster">@thiefmaster</a>)</strong></p>
<p dir="auto">In some cases it would be useful to have a set on the python side, e.g. because you don't need/want duplicates and the set api is nicer to use in that case (as you won't have to worry about removing dupes).</p>
<p dir="auto">Since there's already <code class="notranslate">as_tuple</code>, I'd deprecate this option and have a <code class="notranslate">python_type</code> kwarg instead that defaults to <code class="notranslate">list</code> but can be set to <code class="notranslate">tuple</code> or <code class="notranslate">set</code>, too. <code class="notranslate">as_tuple</code> and <code class="notranslate">python_type</code> would be mutually exclusive.</p>