Skip to content

Commit

Permalink
Add special handling for SQL Server create_index mssql_includes
Browse files Browse the repository at this point in the history
Fixed issue where usage of the SQL Server ``mssql_include`` option within a
:meth:`.Operations.create_index` would raise a KeyError, as the additional
column(s) need to be added to the table object used by the construct
internally.

Change-Id: If58fa35b9db8af473a9654e5a2c8861741810511
Fixes: #513
  • Loading branch information
zzzeek committed Oct 19, 2018
1 parent 2b85a80 commit e01041b
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
10 changes: 10 additions & 0 deletions alembic/ddl/mssql.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
format_table_name, format_column_name, ColumnNullable, alter_column,\
format_server_default, ColumnDefault, format_type, ColumnType
from sqlalchemy.sql.expression import ClauseElement, Executable
from sqlalchemy.schema import CreateIndex, Column
from sqlalchemy import types as sqltypes


class MSSQLImpl(DefaultImpl):
Expand Down Expand Up @@ -87,6 +89,13 @@ def alter_column(self, table_name, column_name,
schema=schema,
name=name)

def create_index(self, index):
mssql_include = index.kwargs.get('mssql_include', ())
for col in mssql_include:
if col not in index.table.c:
index.table.append_column(Column(col, sqltypes.NullType))
self._exec(CreateIndex(index))

def bulk_insert(self, table, rows, **kw):
if self.as_sql:
self._exec(
Expand Down Expand Up @@ -231,3 +240,4 @@ def visit_rename_table(element, compiler, **kw):
format_table_name(compiler, element.table_name, element.schema),
format_table_name(compiler, element.new_table_name, None)
)

8 changes: 8 additions & 0 deletions docs/build/unreleased/513.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.. change::
:tags: bug, mssql
:tickets: 513

Fixed issue where usage of the SQL Server ``mssql_include`` option within a
:meth:`.Operations.create_index` would raise a KeyError, as the additional
column(s) need to be added to the table object used by the construct
internally.
9 changes: 9 additions & 0 deletions tests/test_mssql.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,3 +275,12 @@ def test_alter_column_rename_mssql_schema(self):
context.assert_(
"EXEC sp_rename 'y.t.c', x, 'COLUMN'"
)

def test_create_index_mssql_include(self):
context = op_fixture('mssql')
op.create_index(
op.f('ix_mytable_a_b'), 'mytable', ['col_a', 'col_b'],
unique=False, mssql_include=['col_c'])
context.assert_contains(
"CREATE INDEX ix_mytable_a_b ON mytable "
"(col_a, col_b) INCLUDE (col_c)")

0 comments on commit e01041b

Please sign in to comment.