Skip to content

Commit

Permalink
feat: add database dropdown to dashboard import (#10118)
Browse files Browse the repository at this point in the history
* feat: add database dropdown to dashboard import

Currently, when importing a database from a JSON file, the process
looks at the database name from the source (the info is in the file)
and matches the datasources to that name. If no database by that name
exists, it simply fails.

With this PR, we add a database dropdown that allows the user to specify
which databases the datasources should target as the get upserted.

I want to stress that the code in this area is not in a great shape,
and that the challenge of serializing/deser the nested objects is
challenging, but that there should be a much better way to do this.
One of the improvement (out of scope for this PR) that would allow to
simplify those import/export would be to use UUIDs for
importable/exportable objects.

Another identified issue is the indirections between
`utils/import_expor_{model}.py` on top of `{Model}.import_object`. Not
addressing that here.

Next topic is the MVC stuff. Decided to stick with it for now as this is
more of a [obious missing feat:] than a rewrite.

* isort \!? 0%^$%Y$&?%$^?%0^?

* fix tests

* pre-committing to py3.6

* address dpgaspar's comments

* revert isort
  • Loading branch information
mistercrunch committed Jul 5, 2020
1 parent 33584a8 commit 2314aad
Show file tree
Hide file tree
Showing 10 changed files with 130 additions and 52 deletions.
5 changes: 4 additions & 1 deletion superset-frontend/src/components/FlashProvider.tsx
Expand Up @@ -31,6 +31,7 @@ interface Props {

const flashObj = {
info: 'addInfoToast',
alert: 'addDangerToast',
danger: 'addDangerToast',
warning: 'addWarningToast',
success: 'addSuccessToast',
Expand All @@ -42,7 +43,9 @@ class FlashProvider extends React.PureComponent<Props> {
flashMessages.forEach(message => {
const [type, text] = message;
const flash = flashObj[type];
this.props[flash](text);
if (this.props[flash]) {
this.props[flash](text);
}
});
}
render() {
Expand Down
12 changes: 10 additions & 2 deletions superset/connectors/sqla/models.py
Expand Up @@ -1238,7 +1238,10 @@ def fetch_metadata(self, commit: bool = True) -> None:

@classmethod
def import_obj(
cls, i_datasource: "SqlaTable", import_time: Optional[int] = None
cls,
i_datasource: "SqlaTable",
database_id: Optional[int] = None,
import_time: Optional[int] = None,
) -> int:
"""Imports the datasource from the object to the database.
Expand Down Expand Up @@ -1275,7 +1278,12 @@ def lookup_database(table_: SqlaTable) -> Database:
)

return import_datasource.import_datasource(
db.session, i_datasource, lookup_database, lookup_sqlatable, import_time
db.session,
i_datasource,
lookup_database,
lookup_sqlatable,
import_time,
database_id,
)

@classmethod
Expand Down
4 changes: 4 additions & 0 deletions superset/exceptions.py
Expand Up @@ -77,3 +77,7 @@ class DatabaseNotFound(SupersetException):

class QueryObjectValidationError(SupersetException):
status = 400


class DashboardImportException(SupersetException):
pass
10 changes: 7 additions & 3 deletions superset/models/dashboard.py
Expand Up @@ -247,7 +247,7 @@ def position(self) -> Dict[str, Any]:

@classmethod
def import_obj( # pylint: disable=too-many-locals,too-many-branches,too-many-statements
cls, dashboard_to_import: "Dashboard", import_time: Optional[int] = None
cls, dashboard_to_import: "Dashboard", import_time: Optional[int] = None,
) -> int:
"""Imports the dashboard from the object to the database.
Expand Down Expand Up @@ -311,6 +311,10 @@ def alter_positions(
# copy slices object as Slice.import_slice will mutate the slice
# and will remove the existing dashboard - slice association
slices = copy(dashboard_to_import.slices)

# Clearing the slug to avoid conflicts
dashboard_to_import.slug = None

old_json_metadata = json.loads(dashboard_to_import.json_metadata or "{}")
old_to_new_slc_id_dict: Dict[int, int] = {}
new_timed_refresh_immune_slices = []
Expand All @@ -332,8 +336,8 @@ def alter_positions(
new_slc_id = Slice.import_obj(slc, remote_slc, import_time=import_time)
old_to_new_slc_id_dict[slc.id] = new_slc_id
# update json metadata that deals with slice ids
new_slc_id_str = "{}".format(new_slc_id)
old_slc_id_str = "{}".format(slc.id)
new_slc_id_str = str(new_slc_id)
old_slc_id_str = str(slc.id)
if (
"timed_refresh_immune_slices" in i_params_dict
and old_slc_id_str in i_params_dict["timed_refresh_immune_slices"]
Expand Down
61 changes: 39 additions & 22 deletions superset/templates/superset/import_dashboards.html
Expand Up @@ -24,29 +24,46 @@
{% include "superset/flash_wrapper.html" %}

<div class="container">
<h1>Import dashboards</h1>
<div class="panel">
<div class="panel-heading"><h3>{{ _("Import Dashboard(s)") }}</h3></div>
<div class="panel-body">

<form method="post" enctype="multipart/form-data">
<input
type="hidden"
name="csrf_token"
id="csrf_token"
value="{{ csrf_token() if csrf_token else '' }}" />
<p>
<label class="btn btn-default btn-sm" for="my-file-selector">
<form method="post" enctype="multipart/form-data">
<input
id="my-file-selector"
type="file"
name="file"
style="display:none;"
onchange="$('#upload-file-info').html(this.files[0].name)"/>
Choose File
</label>
<span class='label label-info' id="upload-file-info"></span>
<br/>
<br/>
<input type="submit" value="Upload" class="btn btn-primary btn-sm" />
</p>
</form>
type="hidden"
name="csrf_token"
id="csrf_token"
value="{{ csrf_token() if csrf_token else '' }}" />
<table class="table table-bordered">
<tr>
<td>{{ _("File") }}</td>
<td>
<label class="btn btn-default btn-sm" for="my-file-selector">
<input
id="my-file-selector"
type="file"
name="file"
style="display:none;"
onchange="$('#upload-file-info').html(this.files[0].name)"/>
{{ _("Choose File") }}
</label>
<span class='label label-info' id="upload-file-info"></span>
</td>
</tr>
<tr>
<td>{{ _("Database") }}</td>
<td>
<select id="db_id" name="db_id" class="form-control input-sm" style="width: 300px">
{% for db in databases %}
<option value="{{ db.id }}">{{ db.name }}</option>
{% endfor %}
</select>
</td>
</tr>
</table>
<input type="submit" value="{{ _("Upload") }}" class="btn btn-primary btn-sm" />
</form>
</div>
</div>
</div>
{% endblock %}
11 changes: 9 additions & 2 deletions superset/utils/dashboard_import_export.py
Expand Up @@ -21,9 +21,11 @@
from io import BytesIO
from typing import Any, Dict, Optional

from flask_babel import lazy_gettext as _
from sqlalchemy.orm import Session

from superset.connectors.sqla.models import SqlaTable, SqlMetric, TableColumn
from superset.exceptions import DashboardImportException
from superset.models.dashboard import Dashboard
from superset.models.slice import Slice

Expand Down Expand Up @@ -69,14 +71,19 @@ def decode_dashboards( # pylint: disable=too-many-return-statements


def import_dashboards(
session: Session, data_stream: BytesIO, import_time: Optional[int] = None
session: Session,
data_stream: BytesIO,
database_id: Optional[int] = None,
import_time: Optional[int] = None,
) -> None:
"""Imports dashboards from a stream to databases"""
current_tt = int(time.time())
import_time = current_tt if import_time is None else import_time
data = json.loads(data_stream.read(), object_hook=decode_dashboards)
if not data:
raise DashboardImportException(_("No data in file"))
for table in data["datasources"]:
type(table).import_obj(table, import_time=import_time)
type(table).import_obj(table, database_id, import_time=import_time)
session.commit()
for dashboard in data["dashboards"]:
Dashboard.import_obj(dashboard, import_time=import_time)
Expand Down
7 changes: 5 additions & 2 deletions superset/utils/import_datasource.py
Expand Up @@ -24,12 +24,13 @@
logger = logging.getLogger(__name__)


def import_datasource(
def import_datasource( # pylint: disable=too-many-arguments
session: Session,
i_datasource: Model,
lookup_database: Callable[[Model], Model],
lookup_datasource: Callable[[Model], Model],
import_time: Optional[int] = None,
database_id: Optional[int] = None,
) -> int:
"""Imports the datasource from the object to the database.
Expand All @@ -41,7 +42,9 @@ def import_datasource(
logger.info("Started import of the datasource: %s", i_datasource.to_json())

i_datasource.id = None
i_datasource.database_id = lookup_database(i_datasource).id
i_datasource.database_id = (
database_id if database_id else lookup_database(i_datasource).id
)
i_datasource.alter_params(import_time=import_time)

# override the datasource
Expand Down
11 changes: 8 additions & 3 deletions superset/utils/log.py
Expand Up @@ -24,6 +24,7 @@
from typing import Any, Callable, cast, Optional, Type

from flask import current_app, g, request
from sqlalchemy.exc import SQLAlchemyError

from superset.stats_logger import BaseStatsLogger

Expand Down Expand Up @@ -169,6 +170,10 @@ def log( # pylint: disable=too-many-locals
)
logs.append(log)

sesh = current_app.appbuilder.get_session
sesh.bulk_save_objects(logs)
sesh.commit()
try:
sesh = current_app.appbuilder.get_session
sesh.bulk_save_objects(logs)
sesh.commit()
except SQLAlchemyError as ex:
logging.error("DBEventLogger failed to log event(s)")
logging.exception(ex)
22 changes: 17 additions & 5 deletions superset/views/core.py
Expand Up @@ -75,6 +75,7 @@
SupersetTimeoutException,
)
from superset.jinja_context import get_template_processor
from superset.models.core import Database
from superset.models.dashboard import Dashboard
from superset.models.datasource_access_request import DatasourceAccessRequest
from superset.models.slice import Slice
Expand Down Expand Up @@ -541,10 +542,15 @@ def explore_json(
@expose("/import_dashboards", methods=["GET", "POST"])
def import_dashboards(self) -> FlaskResponse:
"""Overrides the dashboards using json instances from the file."""
f = request.files.get("file")
if request.method == "POST" and f:
import_file = request.files.get("file")
if request.method == "POST" and import_file:
success = False
database_id = request.form.get("db_id")
try:
dashboard_import_export.import_dashboards(db.session, f.stream)
dashboard_import_export.import_dashboards(
db.session, import_file.stream, database_id
)
success = True
except DatabaseNotFound as ex:
logger.exception(ex)
flash(
Expand All @@ -565,8 +571,14 @@ def import_dashboards(self) -> FlaskResponse:
),
"danger",
)
return redirect("/dashboard/list/")
return self.render_template("superset/import_dashboards.html")
if success:
flash("Dashboard(s) have been imported", "success")
return redirect("/dashboard/list/")

databases = db.session.query(Database).all()
return self.render_template(
"superset/import_dashboards.html", databases=databases
)

@event_logger.log_this
@has_access
Expand Down

0 comments on commit 2314aad

Please sign in to comment.