添加表
我们在superset上添加表之后,表的列和指标就自动展示出来了,这个主要是在tablemodelview的post_add()函数中做的操作。
class TableModelView(DatasourceModelView, DeleteMixin, YamlExportMixin): # noqa
datamodel = SQLAInterface(models.SqlaTable)
pass
def post_add(self, table, flash_message=True):
table.fetch_metadata() # 主要是这个函数获取表的基本信息
security_manager.merge_perm('datasource_access', table.get_perm())
if table.schema:
security_manager.merge_perm('schema_access', table.schema_perm)
if flash_message:
flash(_(
'The table was created. '
'As part of this two phase configuration '
'process, you should now click the edit button by '
'the new table to configure it.'), 'info')
def fetch_metadata(self):
"""Fetches the metadata for the table and merges it in"""
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").format(self.table_name))
M = SqlMetric # noqa
metrics = []
any_date_col = None
db_dialect = self.database.get_dialect()
#获取mysql的comment信息
comment_info_dict=self.init_table(table)
dbcols = (
db.session.query(TableColumn)
.filter(TableColumn.table == self)
.filter(or_(TableColumn.column_name == col.name
for col in table.columns)))
dbcols = {dbcol.column_name: dbcol for dbcol in dbcols}
count=0
for col in table.columns:
try:
datatype = col.type.compile(dialect=db_dialect).upper()
except Exception as e:
datatype = 'UNKNOWN'
logging.error(
'Unrecognized data type in {}.{}'.format(table, col.name))
logging.exception(e)
dbcol = dbcols.get(col.name, None)
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
dbcol.order_number=count*100
count+=1
if comment_info_dict:
dbcol.verbose_name=comment_info_dict[dbcol.column_name]
else:
dbcol.type = datatype
self.columns.append(dbcol)
if not any_date_col and dbcol.is_time:
any_date_col = col.name
metrics += dbcol.get_metrics().values()
metrics.append(M(
metric_name='count',
verbose_name='COUNT(*)',
metric_type='count',
expression='COUNT(*)',
))
if not self.main_dttm_col:
self.main_dttm_col = any_date_col
self.add_missing_metrics(metrics)
db.session.merge(self)
db.session.commit()
如果表的信息更新了,可以使用Refresh Metadata 来更新表的内容。
编辑表
编辑表之后在页面跳转到数据查询页面
@expose('/edit/<pk>', methods=['GET', 'POST'])
@has_access
def edit(self, pk):
"""Simple hack to redirect to explore view after saving"""
resp = super(TableModelView, self).edit(pk)
if isinstance(resp, basestring):
return resp
return redirect('/superset/explore/table/{}/'.format(pk)) # 页面跳转