Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def import_obj(cls, slc_to_import, slc_to_override, import_time=None):
session = db.session
make_transient(slc_to_import)
slc_to_import.dashboards = []
slc_to_import.alter_params(
remote_id=slc_to_import.id, import_time=im... | [
"Inserts or overrides slc in the database.\n\n remote_id and import_time fields in params_dict are set to track the\n slice origin and ensure correct overrides for multiple imports.\n Slice.perm is used to find the datasources and connect them.\n\n :param Slice slc_to_import: Slice objec... |
Please provide a description of the function:def import_obj(cls, dashboard_to_import, import_time=None):
def alter_positions(dashboard, old_to_new_slc_id_dict):
position_data = json.loads(dashboard.position_json)
position_json = position_data.values()
fo... | [
"Imports the dashboard from the object to the database.\n\n Once dashboard is imported, json_metadata field is extended and stores\n remote_id and import_time. It helps to decide if the dashboard has to\n be overridden or just copies over. Slices that belong to this\n dashboard will ... |
Please provide a description of the function:def get_effective_user(self, url, user_name=None):
effective_username = None
if self.impersonate_user:
effective_username = url.username
if user_name:
effective_username = user_name
elif (
... | [
"\n Get the effective user, especially during impersonation.\n :param url: SQL Alchemy URL object\n :param user_name: Default username\n :return: The effective username\n "
] |
Please provide a description of the function:def select_star(
self, table_name, schema=None, limit=100, show_cols=False,
indent=True, latest_partition=False, cols=None):
eng = self.get_sqla_engine(
schema=schema, source=utils.sources.get('sql_lab', None))
ret... | [
"Generates a ``select *`` statement in the proper dialect"
] |
Please provide a description of the function:def all_table_names_in_database(self, cache=False,
cache_timeout=None, force=False):
if not self.allow_multi_schema_metadata_fetch:
return []
return self.db_engine_spec.fetch_result_sets(self, 'table') | [
"Parameters need to be passed as keyword arguments."
] |
Please provide a description of the function:def all_table_names_in_schema(self, schema, cache=False,
cache_timeout=None, force=False):
tables = []
try:
tables = self.db_engine_spec.get_table_names(
inspector=self.inspector, schema=s... | [
"Parameters need to be passed as keyword arguments.\n\n For unused parameters, they are referenced in\n cache_util.memoized_func decorator.\n\n :param schema: schema name\n :type schema: str\n :param cache: whether cache is enabled for the function\n :type cache: bool\n ... |
Please provide a description of the function:def all_view_names_in_schema(self, schema, cache=False,
cache_timeout=None, force=False):
views = []
try:
views = self.db_engine_spec.get_view_names(
inspector=self.inspector, schema=schema... | [
"Parameters need to be passed as keyword arguments.\n\n For unused parameters, they are referenced in\n cache_util.memoized_func decorator.\n\n :param schema: schema name\n :type schema: str\n :param cache: whether cache is enabled for the function\n :type cache: bool\n ... |
Please provide a description of the function:def all_schema_names(self, cache=False, cache_timeout=None, force=False):
return self.db_engine_spec.get_schema_names(self.inspector) | [
"Parameters need to be passed as keyword arguments.\n\n For unused parameters, they are referenced in\n cache_util.memoized_func decorator.\n\n :param cache: whether cache is enabled for the function\n :type cache: bool\n :param cache_timeout: timeout in seconds for the cache\n ... |
Please provide a description of the function:def grains_dict(self):
d = {grain.duration: grain for grain in self.grains()}
d.update({grain.label: grain for grain in self.grains()})
return d | [
"Allowing to lookup grain by either label or duration\n\n For backward compatibility"
] |
Please provide a description of the function:def log_this(cls, f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
user_id = None
if g.user:
user_id = g.user.get_id()
d = request.form.to_dict() or {}
# request parameters can ove... | [
"Decorator to log user actions"
] |
Please provide a description of the function:def api(f):
def wraps(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except Exception as e:
logging.exception(e)
return json_error_response(get_error_msg())
return functools.update_wrapper(wraps,... | [
"\n A decorator to label an endpoint as an API. Catches uncaught exceptions and\n return the response in the JSON format\n "
] |
Please provide a description of the function:def handle_api_exception(f):
def wraps(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except SupersetSecurityException as e:
logging.exception(e)
return json_error_response(utils.error_msg_from_except... | [
"\n A decorator to catch superset exceptions. Use it after the @api decorator above\n so superset exception handler is triggered before the handler for generic exceptions.\n "
] |
Please provide a description of the function:def check_ownership(obj, raise_if_false=True):
if not obj:
return False
security_exception = SupersetSecurityException(
"You don't have the rights to alter [{}]".format(obj))
if g.user.is_anonymous:
if raise_if_false:
ra... | [
"Meant to be used in `pre_update` hooks on models to enforce ownership\n\n Admin have all access, and other users need to be referenced on either\n the created_by field that comes with the ``AuditMixin``, or in a field\n named ``owners`` which is expected to be a one-to-many with the User\n model. It is... |
Please provide a description of the function:def bind_field(
self,
form: DynamicForm,
unbound_field: UnboundField,
options: Dict[Any, Any],
) -> Field:
filters = unbound_field.kwargs.get('filters', [])
filters.append(lambda x: x.strip() if isinstance(x, str) else x)
... | [
"\n Customize how fields are bound by stripping all whitespace.\n\n :param form: The form\n :param unbound_field: The unbound field\n :param options: The field options\n :returns: The bound field\n "
] |
Please provide a description of the function:def common_bootsrap_payload(self):
messages = get_flashed_messages(with_categories=True)
locale = str(get_locale())
return {
'flash_messages': messages,
'conf': {k: conf.get(k) for k in FRONTEND_CONF_KEYS},
... | [
"Common data always sent to the client"
] |
Please provide a description of the function:def _delete(self, pk):
item = self.datamodel.get(pk, self._base_filters)
if not item:
abort(404)
try:
self.pre_delete(item)
except Exception as e:
flash(str(e), 'danger')
else:
v... | [
"\n Delete function logic, override to implement diferent logic\n deletes the record with primary_key = pk\n\n :param pk:\n record primary key to delete\n "
] |
Please provide a description of the function:def get_all_permissions(self):
perms = set()
for role in self.get_user_roles():
for perm_view in role.permissions:
t = (perm_view.permission.name, perm_view.view_menu.name)
perms.add(t)
return perms | [
"Returns a set of tuples with the perm name and view menu name"
] |
Please provide a description of the function:def get_view_menus(self, permission_name):
vm = set()
for perm_name, vm_name in self.get_all_permissions():
if perm_name == permission_name:
vm.add(vm_name)
return vm | [
"Returns the details of view_menus for a perm name"
] |
Please provide a description of the function:def destroy_webdriver(driver):
# This is some very flaky code in selenium. Hence the retries
# and catch-all exceptions
try:
retry_call(driver.close, tries=2)
except Exception:
pass
try:
driver.quit()
except Exception:
... | [
"\n Destroy a driver\n "
] |
Please provide a description of the function:def deliver_dashboard(schedule):
dashboard = schedule.dashboard
dashboard_url = _get_url_path(
'Superset.dashboard',
dashboard_id=dashboard.id,
)
# Create a driver, fetch the page, wait for the page to render
driver = create_webdriv... | [
"\n Given a schedule, delivery the dashboard as an email report\n "
] |
Please provide a description of the function:def deliver_slice(schedule):
if schedule.email_format == SliceEmailReportFormat.data:
email = _get_slice_data(schedule)
elif schedule.email_format == SliceEmailReportFormat.visualization:
email = _get_slice_visualization(schedule)
else:
... | [
"\n Given a schedule, delivery the slice as an email report\n "
] |
Please provide a description of the function:def schedule_window(report_type, start_at, stop_at, resolution):
model_cls = get_scheduler_model(report_type)
dbsession = db.create_scoped_session()
schedules = dbsession.query(model_cls).filter(model_cls.active.is_(True))
for schedule in schedules:
... | [
"\n Find all active schedules and schedule celery tasks for\n each of them with a specific ETA (determined by parsing\n the cron schedule for the schedule)\n "
] |
Please provide a description of the function:def schedule_hourly():
if not config.get('ENABLE_SCHEDULED_EMAIL_REPORTS'):
logging.info('Scheduled email reports not enabled in config')
return
resolution = config.get('EMAIL_REPORTS_CRON_RESOLUTION', 0) * 60
# Get the top of the hour
... | [
" Celery beat job meant to be invoked hourly "
] |
Please provide a description of the function:def dedup(l, suffix='__', case_sensitive=True):
new_l = []
seen = {}
for s in l:
s_fixed_case = s if case_sensitive else s.lower()
if s_fixed_case in seen:
seen[s_fixed_case] += 1
s += suffix + str(seen[s_fixed_case])
... | [
"De-duplicates a list of string by suffixing a counter\n\n Always returns the same number of entries as provided, and always returns\n unique values. Case sensitive comparison by default.\n\n >>> print(','.join(dedup(['foo', 'bar', 'bar', 'bar', 'Bar'])))\n foo,bar,bar__1,bar__2,Bar\n >>> print(','.j... |
Please provide a description of the function:def db_type(cls, dtype):
if isinstance(dtype, ExtensionDtype):
return cls.type_map.get(dtype.kind)
elif hasattr(dtype, 'char'):
return cls.type_map.get(dtype.char) | [
"Given a numpy dtype, Returns a generic database type"
] |
Please provide a description of the function:def columns(self):
if self.df.empty:
return None
columns = []
sample_size = min(INFER_COL_TYPES_SAMPLE_SIZE, len(self.df.index))
sample = self.df
if sample_size:
sample = self.df.sample(sample_size)
... | [
"Provides metadata about columns for data visualization.\n\n :return: dict, with the fields name, type, is_date, is_dim and agg.\n "
] |
Please provide a description of the function:def get_timestamp_expression(self, time_grain):
label = utils.DTTM_ALIAS
db = self.table.database
pdf = self.python_date_format
is_epoch = pdf in ('epoch_s', 'epoch_ms')
if not self.expression and not time_grain and not is_ep... | [
"Getting the time component of the query"
] |
Please provide a description of the function:def dttm_sql_literal(self, dttm, is_epoch_in_utc):
tf = self.python_date_format
if self.database_expression:
return self.database_expression.format(dttm.strftime('%Y-%m-%d %H:%M:%S'))
elif tf:
if is_epoch_in_utc:
... | [
"Convert datetime object to a SQL expression string\n\n If database_expression is empty, the internal dttm\n will be parsed as the string with the pattern that\n the user inputted (python_date_format)\n If database_expression is not empty, the internal dttm\n will be parsed as the... |
Please provide a description of the function:def make_sqla_column_compatible(self, sqla_col, label=None):
label_expected = label or sqla_col.name
db_engine_spec = self.database.db_engine_spec
if db_engine_spec.supports_column_aliases:
label = db_engine_spec.make_label_compat... | [
"Takes a sql alchemy column object and adds label info if supported by engine.\n :param sqla_col: sql alchemy column instance\n :param label: alias/label that column is expected to have\n :return: either a sql alchemy column or label instance if supported by engine\n "
] |
Please provide a description of the function:def values_for_column(self, column_name, limit=10000):
cols = {col.column_name: col for col in self.columns}
target_col = cols[column_name]
tp = self.get_template_processor()
qry = (
select([target_col.get_sqla_col()])
... | [
"Runs query against sqla to retrieve some\n sample values for the given column.\n "
] |
Please provide a description of the function:def mutate_query_from_config(self, sql):
SQL_QUERY_MUTATOR = config.get('SQL_QUERY_MUTATOR')
if SQL_QUERY_MUTATOR:
username = utils.get_username()
sql = SQL_QUERY_MUTATOR(sql, username, security_manager, self.database)
... | [
"Apply config's SQL_QUERY_MUTATOR\n\n Typically adds comments to the query with context"
] |
Please provide a description of the function:def adhoc_metric_to_sqla(self, metric, cols):
expression_type = metric.get('expressionType')
label = utils.get_metric_name(metric)
if expression_type == utils.ADHOC_METRIC_EXPRESSION_TYPES['SIMPLE']:
column_name = metric.get('col... | [
"\n Turn an adhoc metric into a sqlalchemy column.\n\n :param dict metric: Adhoc metric definition\n :param dict cols: Columns for the current table\n :returns: The metric defined as a sqlalchemy column\n :rtype: sqlalchemy.sql.column\n "
] |
Please provide a description of the function:def get_sqla_query( # sqla
self,
groupby, metrics,
granularity,
from_dttm, to_dttm,
filter=None, # noqa
is_timeseries=True,
timeseries_limit=15,
timeseries_limit_metric=None,
... | [
"Querying any sqla table from this common interface"
] |
Please provide a description of the function:def fetch_metadata(self):
try:
table = self.get_sqla_table_object()
except Exception as e:
logging.exception(e)
raise Exception(_(
"Table [{}] doesn't seem to exist in the specified database, "
... | [
"Fetches the metadata for the table and merges it in"
] |
Please provide a description of the function:def import_obj(cls, i_datasource, import_time=None):
def lookup_sqlatable(table):
return db.session.query(SqlaTable).join(Database).filter(
SqlaTable.table_name == table.table_name,
SqlaTable.schema == table.schema... | [
"Imports the datasource from the object to the database.\n\n Metrics and columns and datasource will be overrided if exists.\n This function can be used to import/export dashboards between multiple\n superset instances. Audit metadata isn't copies over.\n "
] |
Please provide a description of the function:def load_long_lat_data():
data = get_example_data('san_francisco.csv.gz', make_bytes=True)
pdf = pd.read_csv(data, encoding='utf-8')
start = datetime.datetime.now().replace(
hour=0, minute=0, second=0, microsecond=0)
pdf['datetime'] = [
s... | [
"Loading lat/long data from a csv file in the repo"
] |
Please provide a description of the function:def external_metadata(self, datasource_type=None, datasource_id=None):
if datasource_type == 'druid':
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, db.session)
elif datasource_type == 'tabl... | [
"Gets column info from the source system"
] |
Please provide a description of the function:def filter_not_empty_values(value):
if not value:
return None
data = [x for x in value if x]
if not data:
return None
return data | [
"Returns a list of non empty values or None"
] |
Please provide a description of the function:def at_least_one_schema_is_allowed(database):
if (security_manager.database_access(database) or
security_manager.all_datasource_access()):
return True
schemas = database.get_schema_access_for_csv_upload()
if (schem... | [
"\n If the user has access to the database or all datasource\n 1. if schemas_allowed_for_csv_upload is empty\n a) if database does not support schema\n user is able to upload csv without specifying schema name\n b) if database supports schema\n ... |
Please provide a description of the function:def apply(
self,
query: BaseQuery,
func: Callable) -> BaseQuery:
if security_manager.can_only_access_owned_queries():
query = (
query
.filter(Query.user_id == g.user.get_user_id(... | [
"\n Filter queries to only those owned by current user if\n can_only_access_owned_queries permission is set.\n\n :returns: query\n "
] |
Please provide a description of the function:def edit(self, pk):
resp = super(TableModelView, self).edit(pk)
if isinstance(resp, str):
return resp
return redirect('/superset/explore/table/{}/'.format(pk)) | [
"Simple hack to redirect to explore view after saving"
] |
Please provide a description of the function:def get_language_pack(locale):
pack = ALL_LANGUAGE_PACKS.get(locale)
if not pack:
filename = DIR + '/{}/LC_MESSAGES/messages.json'.format(locale)
try:
with open(filename) as f:
pack = json.load(f)
ALL_L... | [
"Get/cache a language pack\n\n Returns the langugage pack from cache if it exists, caches otherwise\n\n >>> get_language_pack('fr')['Dashboards']\n \"Tableaux de bords\"\n "
] |
Please provide a description of the function:def get_form_data(chart_id, dashboard=None):
form_data = {'slice_id': chart_id}
if dashboard is None or not dashboard.json_metadata:
return form_data
json_metadata = json.loads(dashboard.json_metadata)
# do not apply filters if chart is immune... | [
"\n Build `form_data` for chart GET request from dashboard's `default_filters`.\n\n When a dashboard has `default_filters` they need to be added as extra\n filters in the GET request for charts.\n\n "
] |
Please provide a description of the function:def get_url(params):
baseurl = 'http://{SUPERSET_WEBSERVER_ADDRESS}:{SUPERSET_WEBSERVER_PORT}/'.format(
**app.config)
with app.test_request_context():
return urllib.parse.urljoin(
baseurl,
url_for('Superset.explore_json', ... | [
"Return external URL for warming up a given chart/table cache."
] |
Please provide a description of the function:def cache_warmup(strategy_name, *args, **kwargs):
logger.info('Loading strategy')
class_ = None
for class_ in strategies:
if class_.name == strategy_name:
break
else:
message = f'No strategy {strategy_name} found!'
log... | [
"\n Warm up cache.\n\n This task periodically hits charts to warm up the cache.\n\n "
] |
Please provide a description of the function:def fetch_logs(self, max_rows=1024,
orientation=None):
from pyhive import hive
from TCLIService import ttypes
from thrift import Thrift
orientation = orientation or ttypes.TFetchOrientation.FETCH_NEXT
try:
req = ttypes.TGetLogR... | [
"Mocked. Retrieve the logs produced by the execution of the query.\n Can be called multiple times to fetch the logs produced after\n the previous call.\n :returns: list<str>\n :raises: ``ProgrammingError`` when no query has been started\n .. note::\n This is not a part of DB-API.\n "
] |
Please provide a description of the function:def refresh_datasources(
self,
datasource_name=None,
merge_flag=True,
refreshAll=True):
ds_list = self.get_datasources()
blacklist = conf.get('DRUID_DATA_SOURCE_BLACKLIST', [])
ds_refresh = []
... | [
"Refresh metadata of all datasources in the cluster\n If ``datasource_name`` is specified, only that datasource is updated\n "
] |
Please provide a description of the function:def refresh(self, datasource_names, merge_flag, refreshAll):
session = db.session
ds_list = (
session.query(DruidDatasource)
.filter(DruidDatasource.cluster_name == self.cluster_name)
.filter(DruidDatasource.dataso... | [
"\n Fetches metadata for the specified datasources and\n merges to the Superset database\n "
] |
Please provide a description of the function:def refresh_metrics(self):
metrics = self.get_metrics()
dbmetrics = (
db.session.query(DruidMetric)
.filter(DruidMetric.datasource_id == self.datasource_id)
.filter(DruidMetric.metric_name.in_(metrics.keys()))
... | [
"Refresh metrics based on the column metadata"
] |
Please provide a description of the function:def import_obj(cls, i_datasource, import_time=None):
def lookup_datasource(d):
return db.session.query(DruidDatasource).filter(
DruidDatasource.datasource_name == d.datasource_name,
DruidCluster.cluster_name == d.c... | [
"Imports the datasource from the object to the database.\n\n Metrics and columns and datasource will be overridden if exists.\n This function can be used to import/export dashboards between multiple\n superset instances. Audit metadata isn't copies over.\n "
] |
Please provide a description of the function:def sync_to_db_from_config(
cls,
druid_config,
user,
cluster,
refresh=True):
session = db.session
datasource = (
session.query(cls)
.filter_by(datasource_name=druid_c... | [
"Merges the ds config from druid_config into one stored in the db."
] |
Please provide a description of the function:def get_post_agg(mconf):
if mconf.get('type') == 'javascript':
return JavascriptPostAggregator(
name=mconf.get('name', ''),
field_names=mconf.get('fieldNames', []),
function=mconf.get('function', ''... | [
"\n For a metric specified as `postagg` returns the\n kind of post aggregation for pydruid.\n "
] |
Please provide a description of the function:def find_postaggs_for(postagg_names, metrics_dict):
postagg_metrics = [
metrics_dict[name] for name in postagg_names
if metrics_dict[name].metric_type == POST_AGG_TYPE
]
# Remove post aggregations that were found
... | [
"Return a list of metrics that are post aggregations"
] |
Please provide a description of the function:def values_for_column(self,
column_name,
limit=10000):
logging.info(
'Getting values for columns [{}] limited to [{}]'
.format(column_name, limit))
# TODO: Use Lexicographic ... | [
"Retrieve some values for the given column"
] |
Please provide a description of the function:def get_aggregations(metrics_dict, saved_metrics, adhoc_metrics=[]):
aggregations = OrderedDict()
invalid_metric_names = []
for metric_name in saved_metrics:
if metric_name in metrics_dict:
metric = metrics_dict[me... | [
"\n Returns a dictionary of aggregation metric names to aggregation json objects\n\n :param metrics_dict: dictionary of all the metrics\n :param saved_metrics: list of saved metric names\n :param adhoc_metrics: list of adhoc metric names\n :raise SupersetExcept... |
Please provide a description of the function:def _dimensions_to_values(dimensions):
values = []
for dimension in dimensions:
if isinstance(dimension, dict):
if 'extractionFn' in dimension:
values.append(dimension)
elif 'dimension' ... | [
"\n Replace dimensions specs with their `dimension`\n values, and ignore those without\n "
] |
Please provide a description of the function:def run_query( # noqa / druid
self,
groupby, metrics,
granularity,
from_dttm, to_dttm,
filter=None, # noqa
is_timeseries=True,
timeseries_limit=None,
timeseries_limit_metric=Non... | [
"Runs a query against Druid and returns a dataframe.\n "
] |
Please provide a description of the function:def homogenize_types(df, groupby_cols):
for col in groupby_cols:
df[col] = df[col].fillna('<NULL>').astype('unicode')
return df | [
"Converting all GROUPBY columns to strings\n\n When grouping by a numeric (say FLOAT) column, pydruid returns\n strings in the dataframe. This creates issues downstream related\n to having mixed types in the dataframe\n\n Here we replace None with <NULL> and make the whole series a\n ... |
Please provide a description of the function:def get_filters(cls, raw_filters, num_cols, columns_dict): # noqa
filters = None
for flt in raw_filters:
col = flt.get('col')
op = flt.get('op')
eq = flt.get('val')
if (
not col or
... | [
"Given Superset filter data structure, returns pydruid Filter(s)"
] |
Please provide a description of the function:def get_env_variable(var_name, default=None):
try:
return os.environ[var_name]
except KeyError:
if default is not None:
return default
else:
error_msg = 'The environment variable {} was missing, abort...'\
... | [
"Get the environment variable or raise exception."
] |
Please provide a description of the function:def get_eager_datasource(cls, session, datasource_type, datasource_id):
datasource_class = ConnectorRegistry.sources[datasource_type]
return (
session.query(datasource_class)
.options(
subqueryload(datasource_c... | [
"Returns datasource with columns and metrics."
] |
Please provide a description of the function:def load_misc_dashboard():
print('Creating the dashboard')
db.session.expunge_all()
dash = db.session.query(Dash).filter_by(slug=DASH_SLUG).first()
if not dash:
dash = Dash()
js = textwrap.dedent()
pos = json.loads(js)
slices = (
... | [
"Loading a dashboard featuring misc charts",
"\\\n{\n \"CHART-BkeVbh8ANQ\": {\n \"children\": [],\n \"id\": \"CHART-BkeVbh8ANQ\",\n \"meta\": {\n \"chartId\": 4004,\n \"height\": 34,\n \"sliceName\": \"Multi Line\",\n \"width\": 8\n },\n ... |
Please provide a description of the function:def load_world_bank_health_n_pop():
tbl_name = 'wb_health_population'
data = get_example_data('countries.json.gz')
pdf = pd.read_json(data)
pdf.columns = [col.replace('.', '_') for col in pdf.columns]
pdf.year = pd.to_datetime(pdf.year)
pdf.to_sq... | [
"Loads the world bank health dataset, slices and a dashboard",
"\\\n{\n \"CHART-36bfc934\": {\n \"children\": [],\n \"id\": \"CHART-36bfc934\",\n \"meta\": {\n \"chartId\": 40,\n \"height\": 25,\n \"sliceName\": \"Region Filter\",\n \"width\": 2\... |
Please provide a description of the function:def load_country_map_data():
csv_bytes = get_example_data(
'birth_france_data_for_country_map.csv', is_gzip=False, make_bytes=True)
data = pd.read_csv(csv_bytes, encoding='utf-8')
data['dttm'] = datetime.datetime.now().date()
data.to_sql( # pyli... | [
"Loading data for map with country map"
] |
Please provide a description of the function:def get_statements(self):
statements = []
for statement in self._parsed:
if statement:
sql = str(statement).strip(' \n;\t')
if sql:
statements.append(sql)
return statements | [
"Returns a list of SQL statements as strings, stripped"
] |
Please provide a description of the function:def as_create_table(self, table_name, overwrite=False):
exec_sql = ''
sql = self.stripped()
if overwrite:
exec_sql = f'DROP TABLE IF EXISTS {table_name};\n'
exec_sql += f'CREATE TABLE {table_name} AS \n{sql}'
retur... | [
"Reformats the query into the create table as query.\n\n Works only for the single select SQL statements, in all other cases\n the sql query is not modified.\n :param superset_query: string, sql query that will be executed\n :param table_name: string, will contain the results of the\n ... |
Please provide a description of the function:def get_query_with_new_limit(self, new_limit):
if not self._limit:
return self.sql + ' LIMIT ' + str(new_limit)
limit_pos = None
tokens = self._parsed[0].tokens
# Add all items to before_str until there is a limit... | [
"returns the query with the specified limit",
"does not change the underlying query"
] |
Please provide a description of the function:def url_param(param, default=None):
if request.args.get(param):
return request.args.get(param, default)
# Supporting POST as well as get
if request.form.get('form_data'):
form_data = json.loads(request.form.get('form_data'))
url_param... | [
"Read a url or post parameter and use it in your SQL Lab query\n\n When in SQL Lab, it's possible to add arbitrary URL \"query string\"\n parameters, and use those in your SQL code. For instance you can\n alter your url and add `?foo=bar`, as in\n `{domain}/superset/sqllab?foo=bar`. Then if your query i... |
Please provide a description of the function:def filter_values(column, default=None):
form_data = json.loads(request.form.get('form_data', '{}'))
return_val = []
for filter_type in ['filters', 'extra_filters']:
if filter_type not in form_data:
continue
for f in form_data[fi... | [
" Gets a values for a particular filter as a list\n\n This is useful if:\n - you want to use a filter box to filter a query where the name of filter box\n column doesn't match the one in the select statement\n - you want to have the ability for filter inside the main query for speed purpos... |
Please provide a description of the function:def process_template(self, sql, **kwargs):
template = self.env.from_string(sql)
kwargs.update(self.context)
return template.render(kwargs) | [
"Processes a sql template\n\n >>> sql = \"SELECT '{{ datetime(2017, 1, 1).isoformat() }}'\"\n >>> process_template(sql)\n \"SELECT '2017-01-01T00:00:00'\"\n "
] |
Please provide a description of the function:def get_datasource_info(datasource_id, datasource_type, form_data):
datasource = form_data.get('datasource', '')
if '__' in datasource:
datasource_id, datasource_type = datasource.split('__')
# The case where the datasource has been deleted
... | [
"Compatibility layer for handling of datasource info\n\n datasource_id & datasource_type used to be passed in the URL\n directory, now they should come as part of the form_data,\n This function allows supporting both without duplicating code"
] |
Please provide a description of the function:def can_access(self, permission_name, view_name):
user = g.user
if user.is_anonymous:
return self.is_item_public(permission_name, view_name)
return self._has_view_access(user, permission_name, view_name) | [
"Protecting from has_access failing from missing perms/view"
] |
Please provide a description of the function:def create_missing_perms(self):
from superset import db
from superset.models import core as models
logging.info(
'Fetching a set of all perms to lookup which ones are missing')
all_pvs = set()
for pv in self.get_s... | [
"Creates missing perms for datasources, schemas and metrics",
"Create permission view menu only if it doesn't exist"
] |
Please provide a description of the function:def clean_perms(self):
logging.info('Cleaning faulty perms')
sesh = self.get_session
pvms = (
sesh.query(ab_models.PermissionView)
.filter(or_(
ab_models.PermissionView.permission == None, # NOQA
... | [
"FAB leaves faulty permissions that need to be cleaned up"
] |
Please provide a description of the function:def sync_role_definitions(self):
from superset import conf
logging.info('Syncing role definition')
self.create_custom_permissions()
# Creating default roles
self.set_role('Admin', self.is_admin_pvm)
self.set_role('Al... | [
"Inits the Superset application with security roles and such"
] |
Please provide a description of the function:def export_schema_to_dict(back_references):
databases = [Database.export_schema(recursive=True,
include_parent_ref=back_references)]
clusters = [DruidCluster.export_schema(recursive=True,
include_parent_ref=back_references)]
... | [
"Exports the supported import/export schema to a dictionary"
] |
Please provide a description of the function:def export_to_dict(session,
recursive,
back_references,
include_defaults):
logging.info('Starting export')
dbs = session.query(Database)
databases = [database.export_to_dict(recursive=recursive,
... | [
"Exports databases and druid clusters to a dictionary"
] |
Please provide a description of the function:def import_from_dict(session, data, sync=[]):
if isinstance(data, dict):
logging.info('Importing %d %s',
len(data.get(DATABASES_KEY, [])),
DATABASES_KEY)
for database in data.get(DATABASES_KEY, []):
... | [
"Imports databases and druid clusters from dictionary"
] |
Please provide a description of the function:def query(self):
query_context = QueryContext(**json.loads(request.form.get('query_context')))
security_manager.assert_datasource_permission(query_context.datasource)
payload_json = query_context.get_payload()
return json.dumps(
... | [
"\n Takes a query_obj constructed in the client and returns payload data response\n for the given query_obj.\n params: query_context: json_blob\n "
] |
Please provide a description of the function:def query_form_data(self):
form_data = {}
slice_id = request.args.get('slice_id')
if slice_id:
slc = db.session.query(models.Slice).filter_by(id=slice_id).one_or_none()
if slc:
form_data = slc.form_data... | [
"\n Get the formdata stored in the database for existing slice.\n params: slice_id: integer\n "
] |
Please provide a description of the function:def load_css_templates():
print('Creating default CSS templates')
obj = db.session.query(CssTemplate).filter_by(template_name='Flat').first()
if not obj:
obj = CssTemplate(template_name='Flat')
css = textwrap.dedent()
obj.css = css
db.se... | [
"Loads 2 css templates to demonstrate the feature",
"\\\n .gridster div.widget {\n transition: background-color 0.5s ease;\n background-color: #FAFAFA;\n border: 1px solid #CCC;\n box-shadow: none;\n border-radius: 0px;\n }\n .gridster div.widget:hover {\n border... |
Please provide a description of the function:def _parent_foreign_key_mappings(cls):
parent_rel = cls.__mapper__.relationships.get(cls.export_parent)
if parent_rel:
return {l.name: r.name for (l, r) in parent_rel.local_remote_pairs}
return {} | [
"Get a mapping of foreign name to the local name of foreign keys"
] |
Please provide a description of the function:def _unique_constrains(cls):
unique = [{c.name for c in u.columns} for u in cls.__table_args__
if isinstance(u, UniqueConstraint)]
unique.extend({c.name} for c in cls.__table__.columns if c.unique)
return unique | [
"Get all (single column and multi column) unique constraints"
] |
Please provide a description of the function:def export_schema(cls, recursive=True, include_parent_ref=False):
parent_excludes = {}
if not include_parent_ref:
parent_ref = cls.__mapper__.relationships.get(cls.export_parent)
if parent_ref:
parent_excludes ... | [
"Export schema as a dictionary"
] |
Please provide a description of the function:def import_from_dict(cls, session, dict_rep, parent=None,
recursive=True, sync=[]):
parent_refs = cls._parent_foreign_key_mappings()
export_fields = set(cls.export_fields) | set(parent_refs.keys())
new_children = {c: ... | [
"Import obj from a dictionary"
] |
Please provide a description of the function:def export_to_dict(self, recursive=True, include_parent_ref=False,
include_defaults=False):
cls = self.__class__
parent_excludes = {}
if recursive and not include_parent_ref:
parent_ref = cls.__mapper__.rela... | [
"Export obj to dictionary"
] |
Please provide a description of the function:def override(self, obj):
for field in obj.__class__.export_fields:
setattr(self, field, getattr(obj, field)) | [
"Overrides the plain fields of the dashboard."
] |
Please provide a description of the function:def update_time_range(form_data):
if 'since' in form_data or 'until' in form_data:
form_data['time_range'] = '{} : {}'.format(
form_data.pop('since', '') or '',
form_data.pop('until', '') or '',
) | [
"Move since and until to time_range."
] |
Please provide a description of the function:def memoized_func(key=view_cache_key, attribute_in_key=None):
def wrap(f):
if tables_cache:
def wrapped_f(self, *args, **kwargs):
if not kwargs.get('cache', True):
return f(self, *args, **kwargs)
... | [
"Use this decorator to cache functions that have predefined first arg.\n\n enable_cache is treated as True by default,\n except enable_cache = False is passed to the decorated function.\n\n force means whether to force refresh the cache and is treated as False by default,\n except force = True is passed... |
Please provide a description of the function:def name(self):
ts = datetime.now().isoformat()
ts = ts.replace('-', '').replace(':', '').split('.')[0]
tab = (self.tab_name.replace(' ', '_').lower()
if self.tab_name else 'notab')
tab = re.sub(r'\W+', '', tab)
... | [
"Name property"
] |
Please provide a description of the function:def check_datasource_perms(self, datasource_type=None, datasource_id=None):
form_data = get_form_data()[0]
datasource_id, datasource_type = get_datasource_info(
datasource_id, datasource_type, form_data)
viz_obj = get_viz(
datasource_type=dat... | [
"\n Check if user can access a cached response from explore_json.\n\n This function takes `self` since it must have the same signature as the\n the decorated method.\n\n "
] |
Please provide a description of the function:def check_slice_perms(self, slice_id):
form_data, slc = get_form_data(slice_id, use_slice_data=True)
datasource_type = slc.datasource.type
datasource_id = slc.datasource.id
viz_obj = get_viz(
datasource_type=datasource_type,
datasource_id... | [
"\n Check if user can access a cached response from slice_json.\n\n This function takes `self` since it must have the same signature as the\n the decorated method.\n\n "
] |
Please provide a description of the function:def apply_caching(response):
for k, v in config.get('HTTP_HEADERS').items():
response.headers[k] = v
return response | [
"Applies the configuration's http headers to all responses"
] |
Please provide a description of the function:def override_role_permissions(self):
data = request.get_json(force=True)
role_name = data['role_name']
databases = data['database']
db_ds_names = set()
for dbs in databases:
for schema in dbs['schema']:
... | [
"Updates the role with the give datasource permissions.\n\n Permissions not in the request will be revoked. This endpoint should\n be available to admins only. Expects JSON in the format:\n {\n 'role_name': '{role_name}',\n 'database': [{\n 'datasourc... |
Please provide a description of the function:def import_dashboards(self):
f = request.files.get('file')
if request.method == 'POST' and f:
dashboard_import_export.import_dashboards(db.session, f.stream)
return redirect('/dashboard/list/')
return self.render_templ... | [
"Overrides the dashboards using json instances from the file."
] |
Please provide a description of the function:def explorev2(self, datasource_type, datasource_id):
return redirect(url_for(
'Superset.explore',
datasource_type=datasource_type,
datasource_id=datasource_id,
**request.args)) | [
"Deprecated endpoint, here for backward compatibility of urls"
] |
Please provide a description of the function:def filter(self, datasource_type, datasource_id, column):
# TODO: Cache endpoint by user, datasource and column
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, db.session)
if not datasource:
... | [
"\n Endpoint to retrieve values for specified column.\n\n :param datasource_type: Type of datasource e.g. table\n :param datasource_id: Datasource id\n :param column: Column name to retrieve values for\n :return:\n "
] |
Please provide a description of the function:def save_or_overwrite_slice(
self, args, slc, slice_add_perm, slice_overwrite_perm, slice_download_perm,
datasource_id, datasource_type, datasource_name):
slice_name = args.get('slice_name')
action = args.get('action')
... | [
"Save or overwrite a slice"
] |
Please provide a description of the function:def checkbox(self, model_view, id_, attr, value):
modelview_to_model = {
'{}ColumnInlineView'.format(name.capitalize()): source.column_class
for name, source in ConnectorRegistry.sources.items()
}
model = modelview_to_... | [
"endpoint for checking/unchecking any boolean in a sqla model"
] |
Please provide a description of the function:def tables(self, db_id, schema, substr, force_refresh='false'):
db_id = int(db_id)
force_refresh = force_refresh.lower() == 'true'
schema = utils.js_string_to_python(schema)
substr = utils.js_string_to_python(substr)
database ... | [
"Endpoint to fetch the list of tables for given database"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.