Skip to content

Commit befcc55

Browse files
joymaxnascimentoaaronburtlesouvikghosh04
authored
Skip unsupported column data types during schema discovery (#3802)
## Why make this change? - Closes [[Bug]: Table with a geometry column fails schema discovery ("GetFieldType returned null") even when fields.include excludes it #3801](#3801) A table holding a `geometry` column cannot be exposed at all. `FillSchemaForTableAsync` reads the object shape with `SELECT *`, and `DbDataAdapter.FillSchema` needs a CLR type for every column in the projection. For a SQL Server CLR user-defined type the reader reports no CLR type, so `SchemaMapping` fails with `DataReader.GetFieldType(N) returned null` and takes the whole object down. DAB does not reference `Microsoft.SqlServer.Types`. The entity never loads, and there is no configuration-side workaround — excluding the column through permissions does not help, because discovery runs before authorization is consulted. ## What is this change? Schema discovery leaves out columns whose data type the provider cannot map to a CLR type, so the rest of the object stays reachable. `SqlMetadataProvider` gains a virtual `UnsupportedColumnDataTypes`, empty by default. When it is empty the projection stays `SELECT *`, so PostgreSQL, MySQL and Cosmos are untouched. `MsSqlMetadataProvider` overrides it with the three SQL Server CLR user-defined types: `geometry`, `geography`, `hierarchyid`. When a provider declares such types, the projection is built from the catalog and names the remaining columns. Identifiers come from the catalog's own `COLUMN_NAME`, so casing and quoting match the database rather than the config. The catalog is read once per object and shared with column definition population, instead of being queried twice. The projection reproduces the set of columns `SELECT *` exposes before subtracting the unsupported types. This matters because the catalog also reports columns declared `GENERATED ALWAYS AS ROW START/END HIDDEN`, which `SELECT *` does not return: naming them would widen the exposed contract rather than preserve it, and since the read-only classification does not recognize generated-always period columns, an overwriting PUT would target them. They are excluded through `sys.columns.is_hidden`, and they are not reported as skipped — they were never part of the object's shape as the engine sees it. When — and only when — the projection is narrowed, the shape is read with `CommandBehavior.SchemaOnly` rather than through `DbDataAdapter.FillSchema`. `FillSchema` runs with `KeyInfo`, under which the provider performs its own key discovery and returns key columns absent from the `SELECT` list as hidden reader columns; an unsupported type among them reintroduces `DataReader.GetFieldType(N) returned null` even though the projection excluded it. That is reachable through the object's own primary key and through any unique index, including when a supported key is configured through `source.key-fields`. Without `KeyInfo` the projection is authoritative, and the primary key comes from the catalog instead. When nothing is skipped, `FillSchema` still runs with `KeyInfo` exactly as before, so ordinary primary-key inference is untouched for every object that works today. The primary key comes from the object's own key when it has one. Absent a primary key, the first unique index whose every key column is non-nullable and readable is used, in index order — which is what the data adapter reports as `DataTable.PrimaryKey` on the unnarrowed path, so the two paths agree and the narrowed one does not start demanding `source.key-fields` for an object the other resolves on its own. ### Keys of a view A view has no index of its own, so `sys.indexes` holds nothing for it and the narrowed path has no catalog key to fall back to. An earlier revision took the key from `is_part_of_unique_key` in `sys.dm_exec_describe_first_result_set`. That flag is wrong for this purpose: it is a per-column union across every unique key of the underlying object and cannot be split back into one key. A view exposing one column of a two-column key would have that single column inferred as the key, and a partial key silently matches more than one row on an update or a delete. Browse mode on the same procedure also reports `source_schema`, `source_table` and `source_column` for each column. The narrowed path resolves the projection's source object from those, requires a single source object — a projection over a join yields nothing and the missing primary key is reported exactly as before — reads that object's primary key and non-nullable unique candidates from the catalog it already caches, and accepts the first key the projection exposes in full. Every row browse mode returns counts toward the single-source check, the hidden ones included. Browse mode reports the key columns of each participating object, so an object whose every selected column was dropped from the projection survives in hidden rows alone: a view `select a.id, a.name, b.geom from A a join B b on ...` narrows to `[id], [name]`, and without counting the hidden row for `B`'s key the result would read as a single object and be keyed by `A`'s primary key — which does not identify a row, because the join can duplicate `A`'s rows. Only a column the projection selects can carry a key, so the hidden rows are excluded from the key mapping itself. A self-join gets past that check, because browse mode reports the physical table and not the alias, so both instances look like one object. What gives it away is a source column reported twice, since each instance contributes the key. Inference is declined when one repeats. The rule is conservative: a projection that selects a single column twice under different names is declined too, and simply needs `source.key-fields`, as it did before this change. When no key qualifies, the reason is returned rather than thrown, and reported only if the object ends up with no key at all. The schema read runs for every object while the answer matters only for one that is keyless, so an object whose `source.key-fields` is configured must not be rejected over a key it was told not to use — failing there would recommend precisely what was configured. When the object is keyless, the error names the key column the projection leaves out, which is more useful than the generic missing-primary-key one. ### Identity, unreadable keys, stale references Identity columns are carried from `sys.columns.is_identity` rather than through `DataColumn.AutoIncrement`. That setter coerces a DataType it cannot increment to `Int32`, and SQL Server allows identity on `tinyint`, `numeric` and `decimal`, so using it as the transport would report the wrong `SystemType` and reach parameter typing and the generated API schemas. A primary key that cannot be read is rejected at initialization, with the column and its data type named. This covers a key configured over such a column, and the object's own database key when no key is configured — single column or one member of a composite key. Omitting it would leave the key in `SourceDefinition.PrimaryKey` while absent from `SourceDefinition.Columns`, and that inconsistency surfaces much later as a lookup failure. The generic "primary key not configured" error is not used for these, because it reads as something the user forgot to configure even though no configuration can express that key. Configuration naming a column left out of the projection also fails initialization. The exposed and backing column maps are built from entity fields and mappings without requiring the column to exist in `SourceDefinition.Columns`, and the authorization resolver accepts explicitly included field names, so such a reference keeps resolving after the column is gone and then fails per request rather than at startup. `mappings`, `fields`, a permission's `fields.include` and a database policy are all rejected; `exclude` is left alone, since it asks for what already happened. The policy case matters for the same reason the field-permission approach was withdrawn: a policy is parsed per request against the OData model, which `EdmModelBuilder` builds from `SourceDefinition.Columns`, so one naming an absent column returns 400 on every request for that role. Policy field references are found by scanning the expression and skipping single-quoted literals, with `''` treated as an escaped quote, so a literal that happens to read like a column name is not mistaken for one. Aliases resolve through `fields` before `mappings`, matching the precedence `GenerateExposedToBackingColumnMapUtil` already applies. A configured relationship's `source.fields` and `target.fields` are rejected on the same grounds, and `MultipleCreateOrderHelper` is the path that would otherwise fail per request, since it indexes `SourceDefinition.Columns` by each relationship field. That check runs after every object definition is populated rather than alongside the others, because a relationship's `target.fields` belong to the other entity's object, which may not have been read yet. Foreign keys inferred from the catalog and `linking.*` fields are deliberately left alone: there is no configuration to correct for an inferred key, so refusing to start would punish the database's shape rather than the configuration, and the relationship simply not forming is the proportionate outcome. ### Catalog access The catalog facts that the `Columns` schema collection does not carry — which columns the database hides from `SELECT *`, and which columns form the object's primary key — come from a new provider hook, `GetObjectCatalogMetadataAsync`, which returns null in the base class. Only `MsSqlMetadataProvider` implements it, reading `sys.columns` joined to `sys.indexes` / `sys.index_columns`, cached once per object for the duration of initialization. Providers that declare no unsupported types never call it, and neither does an object that holds none: the classification runs first over the `Columns` schema collection, which is read for every object anyway, so only an object whose projection must be narrowed pays the additional query. Both the catalog read and the browse-mode describe are resolved before the object's connection is opened, so nothing nests a second connection inside an open scope. If nothing unsupported is present, or the catalog cannot be read, or it does not report a usable type name, the projection falls back to `SELECT *` and behavior is exactly what it is today. That last case includes an engine without `sys.columns.is_hidden`, which exists from SQL Server 2016 on, and a login without `VIEW DEFINITION`. When every column of an object is unsupported it fails with a clear initialization error instead, since falling back there would re-issue the projection that cannot be read. Skipped columns are logged once per object at Warning level, naming each column and its type, so the omission is discoverable rather than silent. ### Deliberately limited to three types `MsSqlQueryBuilder`'s autoentity discovery skips objects containing `geography`, `geometry`, `hierarchyid`, `sql_variant`, `xml`, `rowversion` or `vector`. That list is intentionally not reused here: `SqlTypeConstants.SupportedSqlDbTypes` marks `timestamp` and `vector` as supported, and there are dedicated `vector` tests, so excluding them would regress shipped behavior. This change is scoped to the CLR user-defined types, which are the ones whose CLR type the provider does not report. ### Why not honor `fields.include` instead An earlier revision of this PR narrowed the projection to the columns the permissions allow to be read. I withdrew it: read permission and physical existence are different things, and several paths need a column to be in `SourceDefinition.Columns` without needing it to be readable. A database policy on an excluded column stops parsing against the EDM model (`EdmModelBuilder` iterates `Columns`) and returns 400 on every request in that role; entities sharing a `source.object` share one `SourceDefinition`, so a per-entity filter cannot isolate anything; multiple-create indexes `Columns` by relationship column name; REST PUT stops nulling the hidden columns. Skipping by type has none of that blast radius, because a column the provider cannot type was never usable in any of those paths. ## Compatibility impact Skipping is provider-wide and driven by the column's data type alone, so it does not consult permissions: a `geometry`, `geography` or `hierarchyid` column is left out even for a role that grants unrestricted read, and `fields.include` / `fields.exclude` no longer narrow discovery. They are not ignored either — naming one of these columns in `fields`, `mappings` or a permission's `fields.include` now fails initialization, because the reference cannot be honored once the column is not part of the exposed contract. That is a deliberate widening, and it takes nothing away in practice. Those three types cannot be read today at all — the object fails discovery and the entity never loads, which is #3801. The observable change is that such an entity now loads with the column absent, instead of not loading. No column that previously reached `SourceDefinition.Columns` stops reaching it, so REST, GraphQL, OpenAPI, MCP and database policies see exactly what they see today for every object that works today. Objects that fail today now fail with a specific reason instead of the provider's opaque error: one whose configured or database primary key is of an unsupported type, and one whose every column is. Providers other than MSSQL and DWSQL declare no unsupported types and keep `SELECT *`. DWSQL shares `MsSqlMetadataProvider` and therefore inherits the override, which is inert there since Synapse has no spatial types. The one thing worth reviewing is discoverability: an omitted column is now a Warning in the log rather than a startup failure. I chose the Warning deliberately, but if you would rather the engine keep failing loudly and require an explicit opt-in per entity, that is a small change and I am happy to make it. ## How was this tested? - [x] Integration Tests - [ ] Unit Tests Twenty-three tests in `src/Service.Tests/UnitTests/SqlMetadataProviderUnitTests.cs` infer metadata against a live MSSQL instance, and one REST test in `src/Service.Tests/SqlTests/RestApiTests/Put/MsSqlPutApiTests.cs` covers the PUT path: | Test | What it asserts | | --- | --- | | `ValidateUnsupportedColumnTypeIsNotInferred` | a `geometry` column is absent from the inferred `SourceDefinition` while the supported columns are present, on the strength of its type alone | | `ValidateObjectWithOnlyUnsupportedColumnsFailsInitialization` | an object whose every column is unsupported fails with a specific error instead of the provider's opaque one | | `ValidatePrimaryKeyOnUnsupportedColumnFailsInitialization` | a configured key naming an unsupported column fails, naming the column and its type | | `ValidateUnsupportedDatabasePrimaryKeyFailsInitialization` | an object whose own database key is of an unsupported type is rejected before adapter execution, with the reason | | `ValidateUnsupportedColumnInCompositeDatabasePrimaryKeyFailsInitialization` | the same when the unsupported column is one member of a composite key | | `ValidateConfiguredKeyIsUsedWhenUniqueIndexColumnIsUnsupported` | an object whose unique index covers an unsupported column loads when a supported key is configured through `source.key-fields` | | `ValidateUniqueKeyIsInferredWhenNoDatabasePrimaryKeyExists` | an object with no database primary key has its non-nullable unique key inferred, with no `source.key-fields` configured | | `ValidateIdentityTypeIsPreservedOnTheNarrowedPath` | a `decimal` identity column keeps its reported type and is still marked auto-generated | | `ValidateHiddenPeriodColumnsAreNotInferred` | the `HIDDEN` period columns of a temporal table stay out of the exposed contract, as does the spatial column | | `PutOneWithHiddenPeriodColumnsInTemporalTable` | an overwriting PUT against that table succeeds: the period columns are not in `SourceDefinition.Columns`, so `AddNullifiedUnspecifiedFields` never targets them | | `ValidateViewKeyIsInferredWithoutConfiguredKeyFields` | a view over a table with a primary key has that key inferred, with no `source.key-fields` configured | | `ValidateViewWithoutPrimaryKeyFallsBackToUniqueKey` | a view over a table whose only key is a unique index has that key inferred | | `ValidateViewOverPartiallyUnsupportedKeyDoesNotInferPartialKey` | a view exposing only part of the source object's composite key fails instead of inferring the exposed part as the key | | `ValidateViewOverJoinDoesNotInferKeyFromOneSide` | a view whose join's second object contributes only the unsupported column is not keyed by the first object's primary key, and still requires `source.key-fields` | | `ValidateViewOverSelfJoinDoesNotInferKey` | a view built on a self-join, which browse mode cannot distinguish from a single instance by source lineage, is not keyed by the object's own key | | `ValidateConfiguredKeyIsHonoredWhenViewOmitsUnderlyingKey` | a configured `source.key-fields` loads a view whose underlying key the projection cannot express, instead of being rejected over that key | | `ValidateRelationshipFieldOverUnsupportedColumnFailsInitialization` | a relationship's `source.fields` naming an unsupported column fails initialization instead of failing per request | | `ValidateConfiguredReferenceToUnsupportedColumnFailsInitialization` | a `mappings` entry over an unsupported column fails initialization | | `ValidateFieldsAliasOverUnsupportedColumnFailsInitialization` | a `fields` alias over an unsupported column fails initialization | | `ValidateIncludedFieldOverUnsupportedColumnFailsInitialization` | a permission's `fields.include` naming an unsupported column fails initialization | | `ValidateDatabasePolicyOverUnsupportedColumnFailsInitialization` | a database policy referencing an unsupported column fails initialization | | `ValidateQuotedLiteralInDatabasePolicyIsNotAFieldReference` | a quoted literal that reads like an unsupported column name is not treated as a field reference | | `ValidateEscapedQuoteInDatabasePolicyLiteralIsNotAFieldReference` | the same when the literal contains an escaped quote (`''`) | | `ValidateDatabasePolicyOverAliasOfSupportedColumnIsHonored` | a policy over an alias of a supported column still resolves, so the rejection does not overreach | Run against SQL Server 2025 (RTM-CU8-GDR) 17.0.4085.5, Developer Edition, in a local Linux container, with `DatabaseSchema-MsSql.sql` applied in full, using the two MSSQL filters from `.pipelines/mssql-pipelines.yml` split into smaller blocks: | Filter | Passed | Failed | | --- | --- | --- | | `TestCategory=MsSql&FullyQualifiedName~SqlTests.Rest` | 349 | 0 | | `TestCategory=MsSql&FullyQualifiedName~SqlTests.GraphQL` | 616 | 0 | | `FullyQualifiedName~SqlMetadataProviderUnitTests&TestCategory=MSSQL` | 51 | 1 | | `TestCategory=MsSql&(UnitTests\|OpenApi\|Telemetry\|Authorization\|Caching)` | 270 | 1 | | `TestCategory=MsSql` minus the above and minus hot reload | 272 | 29 | | `TestCategory=MsSql&FullyQualifiedName~ConfigurationHotReloadTests` | 9 | 1 | All twenty-four tests above pass. The failures are environmental and reproduce on a clean checkout of the merge base; none is in a code path this PR touches: - 29 of them, plus `SqlQueryExecutorUnitTests.TestRetryPolicySuccessfullyExecutingQueryAfterNAttempts`, fail on the container's self-signed certificate. Those tests run late-configured, and `MsSqlQueryExecutor.ConfigureMsSqlQueryExecutor` deliberately sets `Encrypt = Mandatory` with `TrustServerCertificate = false` for that mode, so no connection string can make them pass against a certificate the host does not trust. CI uses LocalDB and does not hit this. - `SqlMetadataProviderUnitTests.CheckExceptionForBadConnectionStringForMsSql` with an empty connection string fails when the class runs on its own and passes alongside the other MSSQL suites. `SqlTestBase._queryBuilder` is static and the helper only assigns it for MySQL and PostgreSQL, so for MSSQL it relies on a value another test left behind; with none, the key fallback added in `c3515c8` reaches `GetTableNameWithSchemaPrefix` before any connection is opened and dereferences a null query builder. Reproduced on `dfd3be4c`, the merge base. - `ConfigurationHotReloadTests.HotReloadConfigConnectionString` times out waiting on the file watcher. The first three rows were re-run on the final commit. The last three are from the commit before it, which the following one changed only in the view key inference that the first three cover. MSSQL only. DWSQL, MySQL and PostgreSQL need engines I do not have locally, so CI remains the check for those suites — no fixture of theirs is touched by this change. ### Fixtures In `src/Service.Tests/DatabaseSchema-MsSql.sql`, following the pattern already used for `vector` columns: - `geometry_type_table` and `geometry_only_view` — a spatial column, and an object whose every column is spatial. - `geometry_all_view` — a view exposing the full key of a table with a primary key. - `temporal_geometry_type_table` — system-versioned, with `HIDDEN` period columns and a spatial column. - `hierarchyid_pk_table` and `hierarchyid_composite_pk_table` — an unsupported type as the database primary key, alone and as one member of a composite key. - `hierarchyid_composite_view` — a view over that composite key exposing only its supported member, which is the partial-key case. - `hierarchyid_unique_table` — no database primary key, an unsupported column under a unique index, and a supported column to configure as the key. - `unique_key_geometry_table` — no database primary key, a non-nullable unique index over a supported column, and a spatial column. - `pk_and_unique_geometry_table` and `unique_without_pk_view` — a table with both a primary key and a unique index, and a view exposing only the unique one. - `join_geometry_view` — a join whose second object contributes only the unsupported column, so after narrowing every selected column resolves to the first object and only browse mode's hidden row reveals the join. - `self_join_geometry_view` — a self-join, where browse mode reports the same physical table for both instances and only the key column appearing twice reveals it. - `decimal_identity_geometry_table` — a `decimal(18, 0)` identity column, whose CLR type `DataColumn.AutoIncrement` would coerce to `Int32`, and a spatial column. `config-generators/mssql-commands.txt` and `src/Service.Tests/dab-config.MsSql.json` carry the `GeometryType` and `TemporalGeometryType` entities, and `src/Service.Tests/Snapshots/ConfigurationTests.TestReadingRuntimeConfigForMsSql.verified.txt` has the matching blocks. I added only those blocks rather than accepting the full received file, and it is worth saying why. The committed `dab-config.MsSql.json` has drifted from what the generator produces: the committed file orders `test_role_with_excluded_fields_on_mutation` as read, create, update, delete on `Book` and `WebsiteUser`, while the generator emits update, create, read, delete — which is what the committed snapshot expects. It also differs in `Connection Timeout` and in a few permission blocks that were collapsed onto one line by hand. Since CI regenerates the config before testing, the snapshot matches there; against the committed file it does not. I confirmed this by regenerating the config locally and running `TestReadingRuntimeConfigForMsSql` against the generated file, where it passes with the blocks I added. Bringing the committed file back in line with the generator would be a welcome cleanup but is not this PR's business, so I left those 28 lines alone. Happy to include them if you prefer. The entities for the objects that fail by design are declared in memory inside the tests rather than in `dab-config.MsSql.json`, since every MSSQL fixture initializes every configured entity. ## Sample Request(s) Table: ```sql create table dbo.Geom ( Id int identity(1,1) not null primary key, Name nvarchar(100) not null, Location geometry null ); ``` Entity — no special configuration needed: ```json "Geom": { "source": { "object": "dbo.Geom", "type": "table" }, "permissions": [ { "role": "anonymous", "actions": [ { "action": "read" } ] } ] } ``` Before this change the engine fails while reading metadata for `Geom`. After it, the entity loads and responds: ``` GET /api/Geom ``` ```json { "value": [ { "Id": 1, "Name": "Shaft collar" } ] } ``` with this in the log at startup: ``` warn: Skipping column(s) of dbo.Geom whose data type is not supported: Location (geometry). They are not exposed through REST, GraphQL or MCP. ``` --------- Co-authored-by: Aaron Burtle <aaronburtle@microsoft.com> Co-authored-by: aaronburtle <93220300+aaronburtle@users.noreply.github.com> Co-authored-by: Souvik Ghosh <souvikofficial04@gmail.com>
1 parent 5637dd8 commit befcc55

13 files changed

Lines changed: 1291 additions & 33 deletions

File tree

‎config-generators/mssql-commands.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ add VectorType --config "dab-config.MsSql.json" --source vector_type_table --res
2222
update VectorType --config "dab-config.MsSql.json" --permissions "authenticated:create,read,delete,update"
2323
update VectorOwner --config "dab-config.MsSql.json" --relationship vectors --target.entity VectorType --cardinality many --relationship.fields "id:owner_id"
2424
update VectorType --config "dab-config.MsSql.json" --relationship owner --target.entity VectorOwner --cardinality one --relationship.fields "owner_id:id"
25+
add GeometryType --config "dab-config.MsSql.json" --source geometry_type_table --rest true --graphql true --permissions "anonymous:read"
26+
add TemporalGeometryType --config "dab-config.MsSql.json" --source temporal_geometry_type_table --rest true --graphql true --permissions "anonymous:create,read,update"
2527
add Profile --config "dab-config.MsSql.json" --source profiles --rest true --graphql true --permissions "anonymous:create,read,delete,update"
2628
update Profile --config "dab-config.MsSql.json" --permissions "authenticated:create,read,delete,update"
2729
add XmlProfile --config "dab-config.MsSql.json" --source xml_profiles --rest true --graphql true --permissions "anonymous:create,read,delete,update"

‎src/Core/Authorization/AuthorizationResolver.cs‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -810,6 +810,62 @@ private static ResolvedDatabasePolicy GetPolicyWithClaimValues(string policy, Di
810810
return new ResolvedDatabasePolicy(processedPolicy, claimValues);
811811
}
812812

813+
/// <summary>
814+
/// Returns the field names a database policy references through "@item.", skipping single-quoted
815+
/// literals, in which a doubled quote is an escaped quote.
816+
/// </summary>
817+
internal static IEnumerable<string> GetFieldReferencesInDatabasePolicy(string? policy)
818+
{
819+
if (string.IsNullOrEmpty(policy))
820+
{
821+
yield break;
822+
}
823+
824+
int index = 0;
825+
while (index < policy.Length)
826+
{
827+
if (policy[index] == '\'')
828+
{
829+
index++;
830+
while (index < policy.Length)
831+
{
832+
if (policy[index++] != '\'')
833+
{
834+
continue;
835+
}
836+
837+
if (index < policy.Length && policy[index] == '\'')
838+
{
839+
index++;
840+
continue;
841+
}
842+
843+
break;
844+
}
845+
846+
continue;
847+
}
848+
849+
if (string.CompareOrdinal(policy, index, FIELD_PREFIX, 0, FIELD_PREFIX.Length) != 0)
850+
{
851+
index++;
852+
continue;
853+
}
854+
855+
int fieldStart = index + FIELD_PREFIX.Length;
856+
index = fieldStart;
857+
while (index < policy.Length && (char.IsAsciiLetterOrDigit(policy[index]) || policy[index] == '_'))
858+
{
859+
index++;
860+
}
861+
862+
if (index > fieldStart)
863+
{
864+
yield return policy[fieldStart..index];
865+
}
866+
}
867+
}
868+
813869
/// <summary>
814870
/// Emits a structured audit signal when a configured (non-empty) database authorization
815871
/// policy resolves to an empty predicate, which silently removes the intended row/column

‎src/Core/Resolvers/MsSqlQueryBuilder.cs‎

Lines changed: 26 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,30 @@ END AS is_system_object
686686
FROM all_tables AS o
687687
JOIN sys.objects AS so
688688
ON so.object_id = o.object_id
689+
),
690+
tables_with_invalid_types AS
691+
(
692+
SELECT c.object_id
693+
FROM sys.columns AS c
694+
JOIN sys.types AS ty
695+
ON c.user_type_id = ty.user_type_id
696+
WHERE ty.name IN (N'sql_variant', N'rowversion')
697+
-- Columns of CLR types such as geometry are skipped, which only fails when they are in the primary key.
698+
OR
699+
(
700+
ty.is_assembly_type = 1
701+
AND EXISTS
702+
(
703+
SELECT 1
704+
FROM sys.index_columns AS ic
705+
JOIN sys.indexes AS i
706+
ON i.object_id = ic.object_id
707+
AND i.index_id = ic.index_id
708+
WHERE ic.object_id = c.object_id
709+
AND ic.column_id = c.column_id
710+
AND i.is_primary_key = 1
711+
)
712+
)
689713
)
690714
SELECT
691715
a.schema_name AS [schema],
@@ -698,22 +722,7 @@ ELSE REPLACE(
698722
)
699723
END AS entity_name,
700724
CASE
701-
WHEN EXISTS
702-
(
703-
SELECT 1
704-
FROM sys.columns AS c
705-
JOIN sys.types AS ty
706-
ON c.user_type_id = ty.user_type_id
707-
WHERE c.object_id = a.object_id
708-
AND ty.name IN
709-
(
710-
N'geography',
711-
N'geometry',
712-
N'hierarchyid',
713-
N'sql_variant',
714-
N'rowversion'
715-
)
716-
) THEN 1
725+
WHEN a.object_id IN (SELECT object_id FROM tables_with_invalid_types) THEN 1
717726
ELSE 0
718727
END AS contains_invalid_types
719728
FROM eligible_tables AS a
@@ -742,22 +751,7 @@ WHERE a.full_name LIKE ip.pattern COLLATE DATABASE_DEFAULT ESCAPE '\'
742751
AND
743752
(
744753
@exclude_invalid_types = 0
745-
OR NOT EXISTS
746-
(
747-
SELECT 1
748-
FROM sys.columns AS c
749-
JOIN sys.types AS ty
750-
ON c.user_type_id = ty.user_type_id
751-
WHERE c.object_id = a.object_id
752-
AND ty.name IN
753-
(
754-
N'geography',
755-
N'geometry',
756-
N'hierarchyid',
757-
N'sql_variant',
758-
N'rowversion'
759-
)
760-
)
754+
OR a.object_id NOT IN (SELECT object_id FROM tables_with_invalid_types)
761755
)
762756
ORDER BY
763757
a.schema_name,

0 commit comments

Comments
 (0)