@@ -96,9 +96,7 @@ def _drop_mat_view(cursor, view_name):
96
96
97
97
98
98
@transaction .atomic ()
99
- def create_materialized_view (
100
- connection , view_name , view_query : ViewSQL , concurrent_index = None , with_data = True , check_sql_changed = False
101
- ):
99
+ def create_materialized_view (connection , view_cls , check_sql_changed = False ):
102
100
"""
103
101
Create a materialized view on a connection.
104
102
@@ -110,6 +108,16 @@ def create_materialized_view(
110
108
already with the same SQL, if there is, it will not do anything. Otherwise the materialized view gets dropped
111
109
and recreated.
112
110
"""
111
+ view_name = view_cls ._meta .db_table
112
+ view_query = view_cls .get_sql ()
113
+ concurrent_index = view_cls ._concurrent_index
114
+
115
+ try :
116
+ schema_name = connection .schema_name
117
+ schema_name_log = f"schema { schema_name } "
118
+ except AttributeError :
119
+ schema_name_log = "default schema"
120
+
113
121
vschema , vname = _schema_and_name (connection , view_name )
114
122
115
123
cursor_wrapper = connection .cursor ()
@@ -146,13 +154,24 @@ def create_materialized_view(
146
154
147
155
if view_exists :
148
156
_drop_mat_view (cursor , view_name )
157
+ log .info ("pgview dropped materialized view %s (%s)" , view_name , schema_name_log )
158
+
159
+ _create_mat_view (cursor , view_name , query , view_query .params , with_data = view_cls .with_data )
160
+ log .info ("pgview created materialized view %s (%s)" , view_name , schema_name_log )
149
161
150
- _create_mat_view (cursor , view_name , query , view_query .params , with_data = with_data )
151
162
if concurrent_index is not None :
152
163
index_sub_name = "_" .join ([s .strip () for s in concurrent_index .split ("," )])
153
164
cursor .execute (
154
165
"CREATE UNIQUE INDEX {0}_{1}_index ON {0} ({2})" .format (view_name , index_sub_name , concurrent_index )
155
166
)
167
+ log .info ("pgview created concurrent index on view %s (%s)" , view_name , schema_name_log )
168
+
169
+ if view_cls ._meta .indexes :
170
+ schema_editor = connection .schema_editor ()
171
+
172
+ for index in view_cls ._meta .indexes :
173
+ schema_editor .add_index (view_cls , index )
174
+ log .info ("pgview created index %s on view %s (%s)" , index .name , view_name , schema_name_log )
156
175
157
176
if view_exists :
158
177
return "UPDATED"
0 commit comments