Skip to content

SQL Server migrations should use QUOTENAME when constructing SQL for EXEC #36264

Closed

Description

@duncansmart

I was just reviewing the SQL generated for a migration and noticed the following snippet generated for a DropColumnOperation:

IF @var IS NOT NULL EXEC(N'ALTER TABLE [FooBar] DROP CONSTRAINT [' + @var + '];');

Strictly speaking, QUOTENAME should be used here in case the constraint name contained a ']' - i.e.:

IF @var IS NOT NULL EXEC(N'ALTER TABLE [FooBar] DROP CONSTRAINT ' + QUOTENAME(@var) + ';');

The code that generates this is at:

.Append(" IS NOT NULL EXEC(")
.Append(
stringTypeMapping.GenerateSqlLiteral(
"ALTER TABLE " + Dependencies.SqlGenerationHelper.DelimitIdentifier(tableName, schema) + " DROP CONSTRAINT ["))
.Append(" + ")
.Append(variable)
.Append(" + ']")

A cursory search shows a few more places where QUOTENAME should be used when concatenating dynamic SQL.

Not sure that it's security issue as I'm having difficulty imagining the threat model (a developer intentionally names a constraint with a SQL injection??)

Happy to submit a PR.

Activity

  1. roji commented on Jun 19, 2025

    @roji
    Member

    Thanks. For all cases where we know the identifier, we escape and quote it ourselves (though if you see any issues for those cases am more than happy to know as well). But I agree in any case that where the identifier is a variable (as above), it makes sense to use QUOTENAME() indeed. As you write above, since identifier names (table/column/constraint names) are part of the EF model, we don't consider this a security issue - but it's still a good to fix it.

    More than happy to accept a PR from you on this!

  2. added theissue type on Jun 19, 2025
  3. added this to the Backlog milestone on Jun 19, 2025
  4. self-assigned this
    on Jun 19, 2025
  5. duncansmart commented on Jun 20, 2025

    @duncansmart
    ContributorAuthor

    Turns out you can't use an expressions in an EXEC other than string concatenation, so the QUOTENAME will have to move to the SELECT, i.e

    SELECT @var = QUOTENAME([d].[name]) 👈
    ...
    IF @var IS NOT NULL EXEC(N'ALTER TABLE [Entity] DROP CONSTRAINT ' + @var + ';');
    

    Will have a PR soon ...

  6. added 4 commits that reference this issue on Jun 20, 2025
    ca609a1
    6e4f2ed
    b7567fc
    17e2d21
  7. modified the milestones: Backlog, 10.0.0 on Jun 23, 2025
  8. added a commit that references this issue on Jun 23, 2025
    4f44953
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions