]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
Add support for filtered indexes for mssql dialect 4658/head
authormollardthomas <mollardthomas@gmail.com>
Fri, 3 May 2019 12:43:12 +0000 (14:43 +0200)
committermollardthomas <mollardthomas@gmail.com>
Fri, 3 May 2019 12:46:50 +0000 (14:46 +0200)
lib/sqlalchemy/dialects/mssql/base.py
test/dialect/mssql/test_compiler.py

index 507fcfdcb5b5679098a068c748648e251de64c44..f18c72b8ccc3b601773263eee468e92e77576d1a 100644 (file)
@@ -540,6 +540,16 @@ names::
 
 would render the index as ``CREATE INDEX my_index ON table (x) INCLUDE (y)``
 
+Filtered Indexes
+^^^^^^^^^^^^^^^^
+
+The ``mssql_where`` option renders WHERE(condition) for the given string
+names::
+
+    Index("my_index", table.c.x, mssql_where=table.c.x > 10)
+
+would render the index as ``CREATE INDEX my_index ON table (x) WHERE x > 10``
+
 Index ordering
 ^^^^^^^^^^^^^^
 
@@ -1950,6 +1960,14 @@ class MSDDLCompiler(compiler.DDLCompiler):
             ),
         )
 
+        whereclause = index.dialect_options["mssql"]["where"]
+
+        if whereclause is not None:
+            where_compiled = self.sql_compiler.process(
+                whereclause, include_table=False, literal_binds=True
+            )
+            text += " WHERE " + where_compiled
+
         # handle other included columns
         if index.dialect_options["mssql"]["include"]:
             inclusions = [
@@ -2182,7 +2200,7 @@ class MSDialect(default.DefaultDialect):
     construct_arguments = [
         (sa_schema.PrimaryKeyConstraint, {"clustered": None}),
         (sa_schema.UniqueConstraint, {"clustered": None}),
-        (sa_schema.Index, {"clustered": None, "include": None}),
+        (sa_schema.Index, {"clustered": None, "include": None, "where": None}),
         (sa_schema.Column, {"identity_start": 1, "identity_increment": 1}),
     ]
 
index 339cc75907db0c4763c9cda3a406c96d52a4b5a5..30a11d16b2f170962e29f4dc7a4d85f4f70b7245 100644 (file)
@@ -1129,6 +1129,15 @@ class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
             schema.CreateIndex(idx), "CREATE CLUSTERED INDEX foo ON test (id)"
         )
 
+    def test_index_where(self):
+        metadata = MetaData()
+        tbl = Table("test", metadata, Column("data", Integer))
+        idx = Index("test_idx_data_1", tbl.c.data, mssql_where=tbl.c.data > 1)
+        self.assert_compile(
+            schema.CreateIndex(idx),
+            "CREATE INDEX test_idx_data_1 ON test (data) WHERE data > 1"
+        )
+
     def test_index_ordering(self):
         metadata = MetaData()
         tbl = Table(