'Fetches the metadata for the table and merges it in'

def fetch_metadata(self):

    try:
        table = self.get_sqla_table_object()
    except Exception:
        raise Exception("Table    doesn't    seem    to    exist    in    the    specified    database,    couldn't    fetch    column    information")
    TC = TableColumn
    M = SqlMetric
    metrics = []
    any_date_col = None
    db_dialect = self.database.get_sqla_engine().dialect
    for col in table.columns:
        try:
            datatype = '{}'.format(col.type).upper()
        except Exception as e:
            datatype = 'UNKNOWN'
            logging.error('Unrecognized    data    type    in    {}.{}'.format(table, col.name))
            logging.exception(e)
        dbcol = db.session.query(TC).filter((TC.table == self)).filter((TC.column_name == col.name)).first()
        db.session.flush()
        if (not dbcol):
            dbcol = TableColumn(column_name=col.name, type=datatype)
            dbcol.groupby = dbcol.is_string
            dbcol.filterable = dbcol.is_string
            dbcol.sum = dbcol.is_num
            dbcol.avg = dbcol.is_num
            dbcol.is_dttm = dbcol.is_time
        db.session.merge(self)
        self.columns.append(dbcol)
        if ((not any_date_col) and dbcol.is_time):
            any_date_col = col.name
        quoted = '{}'.format(col.compile(dialect=db_dialect))
        if dbcol.sum:
            metrics.append(M(metric_name=('sum__' + dbcol.column_name), verbose_name=('sum__' + dbcol.column_name), metric_type='sum', expression='SUM({})'.format(quoted)))
        if dbcol.avg:
            metrics.append(M(metric_name=('avg__' + dbcol.column_name), verbose_name=('avg__' + dbcol.column_name), metric_type='avg', expression='AVG({})'.format(quoted)))
        if dbcol.max:
            metrics.append(M(metric_name=('max__' + dbcol.column_name), verbose_name=('max__' + dbcol.column_name), metric_type='max', expression='MAX({})'.format(quoted)))
        if dbcol.min:
            metrics.append(M(metric_name=('min__' + dbcol.column_name), verbose_name=('min__' + dbcol.column_name), metric_type='min', expression='MIN({})'.format(quoted)))
        if dbcol.count_distinct:
            metrics.append(M(metric_name=('count_distinct__' + dbcol.column_name), verbose_name=('count_distinct__' + dbcol.column_name), metric_type='count_distinct', expression='COUNT(DISTINCT    {})'.format(quoted)))
        dbcol.type = datatype
        db.session.merge(self)
        db.session.commit()
    metrics.append(M(metric_name='count', verbose_name='COUNT(*)', metric_type='count', expression='COUNT(*)'))
    for metric in metrics:
        m = db.session.query(M).filter((M.metric_name == metric.metric_name)).filter((M.table_id == self.id)).first()
        metric.table_id = self.id
        if (not m):
            db.session.add(metric)
            db.session.commit()
    if (not self.main_dttm_col):
        self.main_dttm_col = any_date_col
