Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[charts] New, bulk delete API endpoint #9387

Merged
merged 3 commits into from
Mar 27, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 73 additions & 2 deletions superset/charts/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@
import logging

from flask import g, request, Response
from flask_appbuilder.api import expose, protect, safe
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import ngettext

from superset.charts.commands.bulk_delete import BulkDeleteChartCommand
from superset.charts.commands.create import CreateChartCommand
from superset.charts.commands.delete import DeleteChartCommand
from superset.charts.commands.exceptions import (
ChartBulkDeleteFailedError,
ChartCreateFailedError,
ChartDeleteFailedError,
ChartForbiddenError,
Expand All @@ -32,7 +35,12 @@
)
from superset.charts.commands.update import UpdateChartCommand
from superset.charts.filters import ChartFilter
from superset.charts.schemas import ChartPostSchema, ChartPutSchema
from superset.charts.schemas import (
ChartPostSchema,
ChartPutSchema,
get_delete_ids_schema,
)
from superset.constants import RouteMethod
from superset.models.slice import Slice
from superset.views.base_api import BaseSupersetModelRestApi

Expand All @@ -45,6 +53,11 @@ class ChartRestApi(BaseSupersetModelRestApi):
resource_name = "chart"
allow_browser_login = True

include_route_methods = RouteMethod.REST_MODEL_VIEW_CRUD_SET | {
RouteMethod.EXPORT,
RouteMethod.RELATED,
"bulk_delete", # not using RouteMethod since locally defined
}
class_permission_name = "SliceModelView"
show_columns = [
"slice_name",
Expand Down Expand Up @@ -269,3 +282,61 @@ def delete(self, pk: int) -> Response: # pylint: disable=arguments-differ
except ChartDeleteFailedError as e:
logger.error(f"Error deleting model {self.__class__.__name__}: {e}")
return self.response_422(message=str(e))

@expose("/", methods=["DELETE"])
@protect()
@safe
@rison(get_delete_ids_schema)
def bulk_delete(self, **kwargs) -> Response: # pylint: disable=arguments-differ
"""Delete bulk Charts
---
delete:
description: >-
Deletes multiple Charts in a bulk operation
parameters:
- in: query
name: q
content:
application/json:
schema:
type: array
items:
type: integer
responses:
200:
description: Charts bulk delete
content:
application/json:
schema:
type: object
properties:
message:
type: string
401:
$ref: '#/components/responses/401'
403:
$ref: '#/components/responses/403'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
item_ids = kwargs["rison"]
try:
BulkDeleteChartCommand(g.user, item_ids).run()
return self.response(
200,
message=ngettext(
f"Deleted %(num)d chart",
f"Deleted %(num)d charts",
num=len(item_ids),
),
)
except ChartNotFoundError:
return self.response_404()
except ChartForbiddenError:
return self.response_403()
except ChartBulkDeleteFailedError as e:
return self.response_422(message=str(e))
61 changes: 61 additions & 0 deletions superset/charts/commands/bulk_delete.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
from typing import List, Optional

from flask_appbuilder.security.sqla.models import User

from superset.charts.commands.exceptions import (
ChartBulkDeleteFailedError,
ChartForbiddenError,
ChartNotFoundError,
)
from superset.charts.dao import ChartDAO
from superset.commands.base import BaseCommand
from superset.commands.exceptions import DeleteFailedError
from superset.exceptions import SupersetSecurityException
from superset.models.slice import Slice
from superset.views.base import check_ownership

logger = logging.getLogger(__name__)


class BulkDeleteChartCommand(BaseCommand):
def __init__(self, user: User, model_ids: List[int]):
self._actor = user
self._model_ids = model_ids
self._models: Optional[List[Slice]] = None

def run(self):
self.validate()
try:
ChartDAO.bulk_delete(self._models)
except DeleteFailedError as e:
logger.exception(e.exception)
raise ChartBulkDeleteFailedError()

def validate(self) -> None:
# Validate/populate model exists
self._models = ChartDAO.find_by_ids(self._model_ids)
if not self._models or len(self._models) != len(self._model_ids):
raise ChartNotFoundError()
# Check ownership
for model in self._models:
try:
check_ownership(model)
except SupersetSecurityException:
raise ChartForbiddenError()
4 changes: 4 additions & 0 deletions superset/charts/commands/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,7 @@ class ChartDeleteFailedError(DeleteFailedError):

class ChartForbiddenError(ForbiddenError):
message = _("Changing this chart is forbidden")


class ChartBulkDeleteFailedError(CreateFailedError):
message = _("Charts could not be deleted.")
24 changes: 24 additions & 0 deletions superset/charts/dao.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,13 @@
# specific language governing permissions and limitations
# under the License.
import logging
from typing import List

from sqlalchemy.exc import SQLAlchemyError

from superset.charts.filters import ChartFilter
from superset.dao.base import BaseDAO
from superset.extensions import db
from superset.models.slice import Slice

logger = logging.getLogger(__name__)
Expand All @@ -26,3 +30,23 @@
class ChartDAO(BaseDAO):
model_cls = Slice
base_filter = ChartFilter

@staticmethod
def bulk_delete(models: List[Slice], commit=True):
item_ids = [model.id for model in models]
# bulk delete, first delete related data
for model in models:
model.owners = []
model.dashboards = []
db.session.merge(model)
# bulk delete itself
try:
db.session.query(Slice).filter(Slice.id.in_(item_ids)).delete(
synchronize_session="fetch"
)
if commit:
db.session.commit()
except SQLAlchemyError as e:
if commit:
db.session.rollback()
raise e
2 changes: 2 additions & 0 deletions superset/charts/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
from superset.exceptions import SupersetException
from superset.utils import core as utils

get_delete_ids_schema = {"type": "array", "items": {"type": "integer"}}


def validate_json(value):
try:
Expand Down
20 changes: 18 additions & 2 deletions superset/dao/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from typing import Dict, Optional
from typing import Dict, List, Optional

from flask_appbuilder.models.filters import BaseFilter
from flask_appbuilder.models.sqla import Model
Expand Down Expand Up @@ -48,7 +48,7 @@ class BaseDAO:
@classmethod
def find_by_id(cls, model_id: int) -> Model:
"""
Retrives a model by id, if defined applies `base_filter`
Find a model by id, if defined applies `base_filter`
"""
query = db.session.query(cls.model_cls)
if cls.base_filter:
Expand All @@ -58,6 +58,22 @@ def find_by_id(cls, model_id: int) -> Model:
).apply(query, None)
return query.filter_by(id=model_id).one_or_none()

@classmethod
def find_by_ids(cls, model_ids: List[int]) -> List[Model]:
"""
Find a List of models by a list of ids, if defined applies `base_filter`
"""
id_col = getattr(cls.model_cls, "id", None)
if id_col is None:
return []
query = db.session.query(cls.model_cls).filter(id_col.in_(model_ids))
if cls.base_filter:
data_model = SQLAInterface(cls.model_cls, db.session)
query = cls.base_filter( # pylint: disable=not-callable
"id", data_model
).apply(query, None)
return query.all()

@classmethod
def create(cls, properties: Dict, commit=True) -> Optional[Model]:
"""
Expand Down
8 changes: 0 additions & 8 deletions superset/dashboards/dao.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import logging
from typing import List

from flask_appbuilder.models.sqla.interface import SQLAInterface
from sqlalchemy.exc import SQLAlchemyError

from superset.dao.base import BaseDAO
Expand All @@ -32,13 +31,6 @@ class DashboardDAO(BaseDAO):
model_cls = Dashboard
base_filter = DashboardFilter

@staticmethod
def find_by_ids(model_ids: List[int]) -> List[Dashboard]:
query = db.session.query(Dashboard).filter(Dashboard.id.in_(model_ids))
data_model = SQLAInterface(Dashboard, db.session)
query = DashboardFilter("id", data_model).apply(query, None)
return query.all()

@staticmethod
def validate_slug_uniqueness(slug: str) -> bool:
if not slug:
Expand Down
Loading