migrations: Add create_if_not_exist() helper.

This replaces a function that was on longer in use.  We need
this helper for our old version of postgres.
This commit is contained in:
Steve Howell
2017-06-05 07:10:08 -06:00
committed by Tim Abbott
parent ff9a929d7a
commit b5ebdc7926

View File

@@ -1,5 +1,5 @@
from __future__ import print_function from __future__ import print_function
from typing import Any, Callable, Dict, List, Tuple from typing import Any, Callable, Dict, List, Tuple, Text
from django.db.models.query import QuerySet from django.db.models.query import QuerySet
import re import re
import time import time
@@ -73,18 +73,28 @@ def add_bool_columns(db, table, cols):
', '.join(['ALTER %s SET NOT NULL' % (col,) for col in cols])) ', '.join(['ALTER %s SET NOT NULL' % (col,) for col in cols]))
timed_ddl(db, stmt) timed_ddl(db, stmt)
def create_index_if_nonexistant(db, table, col, index): def create_index_if_not_exist(index_name, table_name, column_string, where_clause):
# type: (Any, str, str, str) -> None # type: (Text, Text, Text, Text) -> Text
validate(table) #
validate(col) # FUTURE TODO: When we no longer need to support postgres 9.3 for Trusty,
validate(index) # we can use "IF NOT EXISTS", which is part of postgres 9.5
test = """SELECT relname FROM pg_class # (and which already is supported on Xenial systems).
WHERE relname = %s""" stmt = '''
if len(db.execute(test, params=[index])) != 0: DO $$
print("Not creating index '%s' because it already exists" % (index,)) BEGIN
else: IF NOT EXISTS (
stmt = "CREATE INDEX %s ON %s (%s)" % (index, table, col) SELECT 1
timed_ddl(db, stmt) FROM pg_class
where relname = '%s'
) THEN
CREATE INDEX
%s
ON %s (%s)
%s;
END IF;
END$$;
''' % (index_name, index_name, table_name, column_string, where_clause)
return stmt
def act_on_message_ranges(db, orm, tasks, batch_size=5000, sleep=0.5): def act_on_message_ranges(db, orm, tasks, batch_size=5000, sleep=0.5):
# type: (Any, Dict[str, Any], List[Tuple[Callable[[QuerySet], QuerySet], Callable[[QuerySet], None]]], int , float) -> None # type: (Any, Dict[str, Any], List[Tuple[Callable[[QuerySet], QuerySet], Callable[[QuerySet], None]]], int , float) -> None