michiya / django-pyodbc-azure

Django backend for Microsoft SQL Server and Azure SQL Database using pyodbc
https://pypi.python.org/pypi/django-pyodbc-azure
BSD 3-Clause "New" or "Revised" License
321 stars 140 forks source link

Consider dbo schema to be in-scope as well as user's schema #174

Open bobince opened 6 years ago

bobince commented 6 years ago

Issue #133 changed introspection to only consider tables in the current user's default schema. However, when one refers to a table without a leading schema name (as Django always does), SQL Server can also happily take it as a reference to a table in the dbo schema, if there is no such table in the user's default schema.

This means introspection will return a different set of tables to the ones Django naturally sees. If a user has a non-dbo default schema and has previously been accessing tables that exist in dbo, upgrading django-pyodbc-azure on a previously-working database can lead to a variety of errors and inconsistent data. This is likely the cause of issue #165 (although without more detail who knows).

Probably the code added in 312538e that tests for TABLE_SCHEMA = SCHEMA_NAME() should be instead be checking for something like TABLE_SCHEMA = SCHEMA_NAME() OR TABLE_SCHEMA = 'dbo'.

...Although I suspect there are some nasty edge cases here if there is a table with the same name in both dbo and the user's own schema; in this case the dbo fallback table should properly be ignored and only one table returned. But that looks quite hairy to implement in the relations/indexes queries, so not really sure what the “right” thing to do there is.