Upgrade libreant database.

    This command can be used after an update of libreant
    in order to upgrade the database and make it aligned with the new version.

def upgrade(check_only, yes):
    '''
    Upgrade libreant database.

    This command can be used after an update of libreant
    in order to upgrade the database and make it aligned with the new version.
    '''
    from utils.es import Elasticsearch
    from libreantdb import DB, migration
    from libreantdb.exceptions import MappingsException

    try:
        db = DB(Elasticsearch(hosts=conf['ES_HOSTS']),
                              index_name=conf['ES_INDEXNAME'])
        if not db.es.indices.exists(db.index_name):
            die("The specified index does not exists: {}".format(db.index_name))

        # Migrate old special `_timestamp` field into the new `_insertion_date`
        num_to_update = migration.elements_without_insertion_date(db.es, db.index_name)
        if num_to_update > 0:
            if check_only:
                exit(123)

            if yes or click.confirm("{} entries miss the '_insertion_date' field. Do you want to proceed and update those entries?".format(num_to_update),
                             prompt_suffix='',
                             default=False):
                migration.migrate_timestamp(db.es, db.index_name)
            else:
                exit(0)

        # Upgrade the index mappings and reindex if necessary
        try:
            db.update_mappings()
        except MappingsException:
            if check_only:
                exit(123)
            count = db.es.count(index=db.index_name)['count']
            if yes or click.confirm("Some old or wrong mappings has been found for the index '"+ db.index_name +"'.\n"\
                                    "In order to upgrade them it is necessary to reindex '"+ str(count) +"' entries.\n"\
                                    "Are you sure you want to proceed?",
                                     prompt_suffix='',
                                     default=False):
                    db.reindex()

    except Exception as e:
        if conf.get('DEBUG', False):
            raise
        else:
            die(str(e))