'Endpoint to fetch the list of tables for given database'

@api
@has_access_api
@expose(u'/tables/<db_id>/<schema>/<substr>/')
def tables(self, db_id, schema, substr):

    db_id = int(db_id)
    schema = utils.js_string_to_python(schema)
    substr = utils.js_string_to_python(substr)
    database = db.session.query(models.Database).filter_by(id=db_id).one()
    table_names = self.accessible_by_user(database, database.all_table_names(schema), schema)
    view_names = self.accessible_by_user(database, database.all_view_names(schema), schema)
    if substr:
        table_names = [tn for tn in table_names if (substr in tn)]
        view_names = [vn for vn in view_names if (substr in vn)]
    max_items = (config.get(u'MAX_TABLE_NAMES') or len(table_names))
    total_items = (len(table_names) + len(view_names))
    max_tables = len(table_names)
    max_views = len(view_names)
    if (total_items and substr):
        max_tables = ((max_items * len(table_names)) // total_items)
        max_views = ((max_items * len(view_names)) // total_items)
    table_options = [{u'value': tn, u'label': tn} for tn in table_names[:max_tables]]
    table_options.extend([{u'value': vn, u'label': u'[view]    {}'.format(vn)} for vn in view_names[:max_views]])
    payload = {u'tableLength': (len(table_names) + len(view_names)), u'options': table_options}
    return json_success(json.dumps(payload))
