Skip to content

ensure_migrations_table sys.tables lookup fails for schema-qualified table names #12

@pabl-o-ce

Description

@pabl-o-ce

Bug

File: sqlx-mssql/src/migrate.rs, ensure_migrations_table

The IF NOT EXISTS check queries sys.tables.name with the full table_name value:

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = '{lit}')
CREATE TABLE {ident} (...)

sys.tables.name stores only the unqualified table name. If table_name is schema-qualified (e.g., dbo._sqlx_migrations), the literal 'dbo._sqlx_migrations' will never match '_sqlx_migrations' in sys.tables, causing the table to be re-created on every migration run (or fail with a duplicate).

This is a pre-existing issue that existed before the escaping fix in #4.

Suggested Fix

Parse the schema and table parts, then query with schema awareness:

IF NOT EXISTS (
    SELECT * FROM sys.tables t
    JOIN sys.schemas s ON t.schema_id = s.schema_id
    WHERE t.name = @table AND s.name = @schema
)
CREATE TABLE [schema].[table] (...)

Or use OBJECT_ID() which handles qualified names natively:

IF OBJECT_ID('{escaped_qualified_name}', 'U') IS NULL
CREATE TABLE {ident} (...)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions