|
| 1 | +""" |
| 2 | +Check for db indexes defined in mapping.py but missing in the database. |
| 3 | +Note: pass '-c /path/to/galaxy.yml' to use the database_connection set in galaxy.yml. |
| 4 | +Otherwise the default sqlite database will be used. |
| 5 | +""" |
| 6 | +import json |
| 7 | +import os |
| 8 | +import sys |
| 9 | +from collections import namedtuple |
| 10 | + |
| 11 | +sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'lib'))) |
| 12 | + |
| 13 | +from sqlalchemy import create_engine, MetaData |
| 14 | + |
| 15 | +from galaxy.model import mapping |
| 16 | +from galaxy.model.orm.scripts import get_config |
| 17 | + |
| 18 | +Index = namedtuple('MissingIndex', 'table column_names') |
| 19 | + |
| 20 | + |
| 21 | +def tuple_from_index(index): |
| 22 | + columns = tuple([getattr(index.columns, c).name for c in dir(index.columns) if not c.startswith('__')]) |
| 23 | + if len(columns) == 1: |
| 24 | + columns = columns[0] |
| 25 | + return Index(index.table.name, columns) |
| 26 | + |
| 27 | + |
| 28 | +def find_missing_indexes(): |
| 29 | + |
| 30 | + def load_indexes(metadata): |
| 31 | + indexes = {} |
| 32 | + for t in metadata.tables.values(): |
| 33 | + for index in t.indexes: |
| 34 | + missing_index = tuple_from_index(index) |
| 35 | + indexes[missing_index] = index.name |
| 36 | + return indexes |
| 37 | + |
| 38 | + # load metadata from mapping.py |
| 39 | + metadata = mapping.metadata |
| 40 | + mapping_indexes = load_indexes(metadata) |
| 41 | + |
| 42 | + # create EMPTY metadata, then load from database |
| 43 | + db_url = get_config(sys.argv)['db_url'] |
| 44 | + metadata = MetaData(bind=create_engine(db_url)) |
| 45 | + metadata.reflect() |
| 46 | + indexes_in_db = load_indexes(metadata) |
| 47 | + |
| 48 | + missing_indexes = set(mapping_indexes.keys()) - set(indexes_in_db.keys()) |
| 49 | + if missing_indexes: |
| 50 | + return [(mapping_indexes[index], index.table, index.column_names) for index in missing_indexes] |
| 51 | + |
| 52 | + |
| 53 | +if __name__ == '__main__': |
| 54 | + indexes = find_missing_indexes() |
| 55 | + if indexes: |
| 56 | + print(json.dumps(indexes, indent=4)) |
| 57 | + sys.exit(1) |
0 commit comments