<p dir="auto"><strong>Migrated issue, originally created by Michael Bayer (<a href="https://github.com/zzzeek">@zzzeek</a>)</strong></p>
<p dir="auto">SQLIte-specific variant implemented similarly to Postgresql's ON CONFLICT, MySQL ON DUPLICATE KEY</p>
<p dir="auto">original issue <a class="issue-link js-issue-link" data-error-text="Failed to load title" data-id="384613771" data-permission-text="Title is private" data-url="https://github.com/sqlalchemy/sqlalchemy/issues/960" data-hovercard-type="issue" data-hovercard-url="/sqlalchemy/sqlalchemy/issues/960/hovercard" href="https://github.com/sqlalchemy/sqlalchemy/issues/960">#960</a></p>
<p dir="auto"><strong>Migrated issue, originally created by Sean Dunn (<a href="https://github.com/seanfdnn">@seanfdnn</a>)</strong></p>
<p dir="auto">For MSSQL:</p>
<ul dir="auto">
<li>When reflecting a database (such as using <code class="notranslate">autoload</code> for a table) an exception can be thrown <code class="notranslate">ArgumentError: ForeignKeyConstraint with duplicate source column references are not supported.</code> Even when there are no duplicate source column references in the database.</li>
</ul>
<p dir="auto">This is caused by two tables in two schemas with the same Primary Key names -- SqlAlchemy confuses these two Primary Keys as being the referred column for a Foreign Key, when only one of them is. This is because SqlAlchemy isn't also checking the constraint schema.</p>
<p dir="auto">To reproduce:</p>
<ul dir="auto">
<li>Create two schemas FOO and BAR</li>
<li>Create three tables, FOO.FOOTABLE, FOO.BAZTABLE, BAR.BARTABLE</li>
<li>Create a PRIMARY KEY on FOO.BAZTABLE and BAR.BARTABLE with the same PK names (i.e. `CONSTRAINT [MY_PK] PRIMARY KEY CLUSTERED ([MY_PK_COL])</li>
<li>Create a FK in FOO.FOOTABLE that references FOO.BAZTABLE.MY_PK_COL</li>
<li>reflect <code class="notranslate">FOO.FOOTABLE</code> via <code class="notranslate">footable = Table('FOOTABLE', fooschemameta, autoload=True, autoload_with=myengine)</code></li>
</ul>
<p dir="auto">Here's one example of someone else who has had the same problem:<br>
<a href="https://stackoverflow.com/questions/47205433/sqlalchemy-table-reflection-remove-duplicate-source-column-references/51024467#51024467" rel="nofollow">https://stackoverflow.com/questions/47205433/sqlalchemy-table-reflection-remove-duplicate-source-column-references/51024467#51024467</a></p>
<p dir="auto">The root issue is in <code class="notranslate">dialects/mssql/base.py</code> in <code class="notranslate">def_foreign_keys</code> -- the query that checks the foreign key constraints does not have a WHERE clause that matches the <code class="notranslate">R.c.constraint_schema</code> to <code class="notranslate">RR.c.unique_constraint_schema</code>.  -- so it's not uniquely identifying the PK (PK's can have identical names in different schemas, so we also need to check the schema)</p>