You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "hughhhh (via GitHub)" <gi...@apache.org> on 2023/07/30 01:48:34 UTC
[GitHub] [superset] hughhhh opened a new pull request, #24839: feat: Update Tags CRUD API
hughhhh opened a new pull request, #24839:
URL: https://github.com/apache/superset/pull/24839
<!---
Please write the PR title following the conventions at https://www.conventionalcommits.org/en/v1.0.0/
Example:
fix(dashboard): load charts correctly
-->
### SUMMARY
<!--- Describe the change below, including rationale and design decisions -->
### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
<!--- Skip this if not applicable -->
### TESTING INSTRUCTIONS
<!--- Required! What steps can be taken to manually verify the changes? -->
### ADDITIONAL INFORMATION
<!--- Check any relevant boxes with "x" -->
<!--- HINT: Include "Fixes #nnn" if you are fixing an existing issue -->
- [ ] Has associated issue:
- [ ] Required feature flags:
- [ ] Changes UI
- [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
- [ ] Migration is atomic, supports rollback & is backwards-compatible
- [ ] Confirm DB migration upgrade and downgrade tested
- [ ] Runtime estimates and downtime expectations provided
- [ ] Introduces new feature or API
- [ ] Removes existing feature or API
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: Update Tags CRUD API [superset]
Posted by "jordibeen (via GitHub)" <gi...@apache.org>.
jordibeen commented on PR #24839:
URL: https://github.com/apache/superset/pull/24839#issuecomment-1753035098
So I've been looking for this "New Tag" button for a while now, but it doesn't seem to exist in the `apache/superset:3.0.0` docker image.
Next to this, even though this PR was merged into `master` on August 25, it doesn't seem to exist in [the source code](https://github.com/apache/superset/blob/3.0.1rc1/superset-frontend/src/pages/Tags/index.tsx) of the [upcoming 3.0.1rc1 release candidate](https://github.com/apache/superset/releases/tag/3.0.1rc1) either.
How can I go about enabling this?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1297862512
##########
superset-frontend/src/features/tags/TagModal.tsx:
##########
@@ -0,0 +1,321 @@
+/**
+ * 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 React, { ChangeEvent, useState, useEffect } from 'react';
+import rison from 'rison';
+import Modal from 'src/components/Modal';
+import AsyncSelect from 'src/components/Select/AsyncSelect';
+import { FormLabel } from 'src/components/Form';
+import { t, SupersetClient } from '@superset-ui/core';
+import { Input } from 'antd';
+import { Divider } from 'src/components';
+import Button from 'src/components/Button';
+import { Tag } from 'src/views/CRUD/types';
+import { fetchObjects } from 'src/features/tags/tags';
+
+interface TaggableResourceOption {
+ label: string;
+ value: number;
+ key: number;
+}
+
+export enum TaggableResources {
+ Chart = 'chart',
+ Dashboard = 'dashboard',
+ SavedQuery = 'query',
+}
+
+interface TagModalProps {
+ onHide: () => void;
+ refreshData: () => void;
+ addSuccessToast: (msg: string) => void;
+ addDangerToast: (msg: string) => void;
+ show: boolean;
+ editTag?: Tag | null;
+}
+
+const TagModal: React.FC<TagModalProps> = ({
+ show,
+ onHide,
+ editTag,
+ refreshData,
+ addSuccessToast,
+ addDangerToast,
+}) => {
+ const [dashboardsToTag, setDashboardsToTag] = useState<
+ TaggableResourceOption[]
+ >([]);
+ const [chartsToTag, setChartsToTag] = useState<TaggableResourceOption[]>([]);
+ const [savedQueriesToTag, setSavedQueriesToTag] = useState<
+ TaggableResourceOption[]
+ >([]);
+
+ const [tagName, setTagName] = useState<string>('');
+ const [description, setDescription] = useState<string>('');
+
+ const isEditMode = !!editTag;
+ const modalTitle = isEditMode ? 'Edit Tag' : 'Create Tag';
+
+ const clearResources = () => {
+ setDashboardsToTag([]);
+ setChartsToTag([]);
+ setSavedQueriesToTag([]);
+ };
+
+ useEffect(() => {
+ const resourceMap: { [key: string]: TaggableResourceOption[] } = {
+ [TaggableResources.Dashboard]: [],
+ [TaggableResources.Chart]: [],
+ [TaggableResources.SavedQuery]: [],
+ };
+
+ const updateResourceOptions = (object: Tag) => {
+ const resourceOptions = resourceMap[object.type];
+ if (resourceOptions) {
+ resourceOptions.push({
Review Comment:
Nit/style, but you can simplify this:
if (resourceOptions) {
resourceOptions.push({
to just
```suggestion
resourceOptions?.push({
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1303515128
##########
superset/tags/exceptions.py:
##########
@@ -27,3 +29,11 @@ def __init__(self) -> None:
super().__init__(
[_("Tag name is invalid (cannot contain ':')")], field_name="name"
)
+
+
+class TagUpdateFailedError(UpdateFailedError):
+ message = _("Tag could not be updated.")
+
+
+class TagNotFoundError(CommandException):
+ message = _("Tag could not be found.")
Review Comment:
```suggestion
message = _("Tag could not be found.")
status = 404
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] codecov[bot] commented on pull request #24839: feat: Update Tags CRUD API
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #24839:
URL: https://github.com/apache/superset/pull/24839#issuecomment-1656995115
## [Codecov](https://app.codecov.io/gh/apache/superset/pull/24839?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
> Merging [#24839](https://app.codecov.io/gh/apache/superset/pull/24839?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) (a83fe92) into [master](https://app.codecov.io/gh/apache/superset/commit/7cd317fe2e56f00ed9c21f9233e92aa19eb62ae7?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) (7cd317f) will **increase** coverage by `2.89%`.
> Report is 6 commits behind head on master.
> The diff coverage is `88.09%`.
> :exclamation: Current head a83fe92 differs from pull request most recent head 9ffd7c7. Consider uploading reports for the commit 9ffd7c7 to get more accurate results
```diff
@@ Coverage Diff @@
## master #24839 +/- ##
==========================================
+ Coverage 55.43% 58.32% +2.89%
==========================================
Files 1903 1903
Lines 74077 74105 +28
Branches 8194 8193 -1
==========================================
+ Hits 41064 43225 +2161
+ Misses 30892 28759 -2133
Partials 2121 2121
```
| Flag | Coverage Δ | |
|---|---|---|
| presto | `54.00% <28.57%> (?)` | |
| python | `61.05% <88.09%> (+6.05%)` | :arrow_up: |
| unit | `55.05% <88.09%> (+0.06%)` | :arrow_up: |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
| [Files Changed](https://app.codecov.io/gh/apache/superset/pull/24839?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [...c/filters/components/Select/SelectFilterPlugin.tsx](https://app.codecov.io/gh/apache/superset/pull/24839?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQtZnJvbnRlbmQvc3JjL2ZpbHRlcnMvY29tcG9uZW50cy9TZWxlY3QvU2VsZWN0RmlsdGVyUGx1Z2luLnRzeA==) | `59.21% <ø> (-2.52%)` | :arrow_down: |
| [superset/tags/commands/create.py](https://app.codecov.io/gh/apache/superset/pull/24839?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvdGFncy9jb21tYW5kcy9jcmVhdGUucHk=) | `54.71% <80.95%> (+17.21%)` | :arrow_up: |
| [superset/daos/tag.py](https://app.codecov.io/gh/apache/superset/pull/24839?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvZGFvcy90YWcucHk=) | `55.83% <90.90%> (+7.20%)` | :arrow_up: |
| [superset/charts/commands/importers/v1/utils.py](https://app.codecov.io/gh/apache/superset/pull/24839?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvY2hhcnRzL2NvbW1hbmRzL2ltcG9ydGVycy92MS91dGlscy5weQ==) | `87.50% <100.00%> (ø)` | |
| [superset/databases/api.py](https://app.codecov.io/gh/apache/superset/pull/24839?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvZGF0YWJhc2VzL2FwaS5weQ==) | `52.16% <100.00%> (ø)` | |
| [superset/models/helpers.py](https://app.codecov.io/gh/apache/superset/pull/24839?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbW9kZWxzL2hlbHBlcnMucHk=) | `63.16% <100.00%> (+16.20%)` | :arrow_up: |
| [superset/views/core.py](https://app.codecov.io/gh/apache/superset/pull/24839?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvdmlld3MvY29yZS5weQ==) | `34.13% <100.00%> (+4.19%)` | :arrow_up: |
... and [79 files with indirect coverage changes](https://app.codecov.io/gh/apache/superset/pull/24839/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
:mega: We’re building smart automated test selection to slash your CI/CD build times. [Learn more](https://about.codecov.io/iterative-testing/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1302011450
##########
superset/tags/api.py:
##########
@@ -131,6 +141,131 @@ def __repr__(self) -> str:
f'{self.appbuilder.app.config["VERSION_SHA"]}'
)
+ @expose("/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
+ log_to_statsd=False,
+ )
+ def post(self) -> Response:
+ """Creates a new Tags and tag items
+ ---
+ post:
+ description: >-
+ Create a new Tag
+ requestBody:
+ description: Tag schema
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ responses:
+ 201:
+ description: Tag added
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id:
+ type: number
+ result:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 422:
+ $ref: '#/components/responses/422'
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ try:
+ item = self.add_model_schema.load(request.json)
+ except ValidationError as error:
+ return self.response_400(message=error.messages)
+ try:
+ CreateCustomTagWithRelationshipsCommand(item).run()
+ return self.response(201)
+ except TagInvalidError as ex:
+ return self.response_422(message=ex.normalized_messages())
+ except TaggedObjectDeleteFailedError as ex:
Review Comment:
I see. It looks like we're returning TagCreateFailedError from the Command after validation and after the DaoCreateFailedError. IMO, TagInvalidError would be a 422, and TagCreateFailedError a 500, and then we can return the TagCreateFailedError after all the validation has been completed, only returning the TagInvalidError for user-generated validation errors where a retry is in order. Then return the TagCreateFailedError for system errors.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] hughhhh commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1300219889
##########
superset/daos/tag.py:
##########
@@ -363,3 +364,46 @@ def favorited_ids(tags: list[Tag]) -> list[int]:
)
.all()
]
+
+ @staticmethod
+ def create_tag_relationship(
+ objects_to_tag: list[tuple[ObjectTypes, int]], tag: Tag
+ ) -> None:
+ """
+ Creates a tag relationship between the given objects and the specified tag.
+ This function iterates over a list of objects, each specified by a type
+ and an id, and creates a TaggedObject for each one, associating it with
+ the provided tag. All created TaggedObjects are collected in a list.
+ Args:
+ objects_to_tag (List[Tuple[ObjectTypes, int]]): A list of tuples, each
+ containing an ObjectType and an id, representing the objects to be tagged.
+
+ tag (Tag): The tag to be associated with the specified objects.
+ Returns:
+ None.
+ """
+ tagged_objects = []
+ if not tag:
+ raise TagNotFoundError()
Review Comment:
it's already defined in the API layer:
```
except TagNotFoundError:
return self.response_404()
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1303509210
##########
superset/tags/commands/create.py:
##########
@@ -60,3 +62,45 @@ def validate(self) -> None:
)
if exceptions:
raise TagInvalidError(exceptions=exceptions)
+
+
+class CreateCustomTagWithRelationshipsCommand(CreateMixin, BaseCommand):
+ def __init__(self, data: dict[str, Any]):
+ self._tag = data["name"]
+ self._objects_to_tag = data.get("objects_to_tag")
+ self._description = data.get("description")
+
+ def run(self) -> None:
+ self.validate()
+ try:
+ tag = TagDAO.get_by_name(self._tag.strip(), TagTypes.custom)
+ if self._objects_to_tag:
+ TagDAO.create_tag_relationship(
+ objects_to_tag=self._objects_to_tag, tag=tag
+ )
+
+ if self._description:
+ tag.description = self._description
+ db.session.commit()
+
+ except DAOCreateFailedError as ex:
+ logger.exception(ex.exception)
Review Comment:
flask will actually raise and log this error from the response. I don't think we need this.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] craig-rueda commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "craig-rueda (via GitHub)" <gi...@apache.org>.
craig-rueda commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1300420695
##########
tests/unit_tests/tags/commands/update_test.py:
##########
@@ -0,0 +1,128 @@
+import pytest
+from sqlalchemy.orm.session import Session
+
+from superset.utils.core import DatasourceType
+
+
+@pytest.fixture
+def session_with_data(session: Session):
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+ from superset.models.dashboard import Dashboard
+ from superset.models.slice import Slice
+ from superset.models.sql_lab import Query, SavedQuery
+ from superset.tags.models import Tag
+
+ engine = session.get_bind()
+ Tag.metadata.create_all(engine) # pylint: disable=no-member
+
+ slice_obj = Slice(
+ id=1,
+ datasource_id=1,
+ datasource_type=DatasourceType.TABLE,
+ datasource_name="tmp_perm_table",
+ slice_name="slice_name",
+ )
+
+ db = Database(database_name="my_database", sqlalchemy_uri="postgresql://")
+
+ columns = [
+ TableColumn(column_name="a", type="INTEGER"),
+ ]
+
+ sqla_table = SqlaTable(
+ table_name="my_sqla_table",
+ columns=columns,
+ metrics=[],
+ database=db,
+ )
+
+ dashboard_obj = Dashboard(
+ id=100,
+ dashboard_title="test_dashboard",
+ slug="test_slug",
+ slices=[],
+ published=True,
+ )
+
+ saved_query = SavedQuery(label="test_query", database=db, sql="select * from foo")
+
+ tag = Tag(name="test_name", description="test_description")
+
+ session.add(slice_obj)
+ session.add(dashboard_obj)
+ session.add(tag)
+ session.commit()
+ yield session
+
+
+def test_update_command_success(session_with_data: Session):
+ from superset.daos.tag import TagDAO
+ from superset.models.dashboard import Dashboard
+ from superset.tags.commands.update import UpdateTagCommand
+ from superset.tags.models import ObjectTypes, TaggedObject
+
+ dashboard = session_with_data.query(Dashboard).first()
+
+ objects_to_tag = [
+ (ObjectTypes.dashboard, dashboard.id),
+ ]
+
+ tag_to_update = TagDAO.find_by_name("test_name")
+ changed_model = UpdateTagCommand(
+ tag_to_update.id,
+ {
+ "name": "new_name",
+ "description": "new_description",
+ "objects_to_tag": objects_to_tag,
+ },
+ ).run()
+
+ updated_tag = TagDAO.find_by_name("new_name")
+ assert updated_tag is not None
+ assert updated_tag.description == "new_description"
+ assert len(session_with_data.query(TaggedObject).all()) == len(objects_to_tag)
+
+
+def test_update_command_success_duplicates(session_with_data: Session):
+ from superset.daos.tag import TagDAO
+ from superset.models.dashboard import Dashboard
+ from superset.models.slice import Slice
+ from superset.tags.commands.create import CreateCustomTagWithRelationshipsCommand
+ from superset.tags.commands.update import UpdateTagCommand
+ from superset.tags.models import ObjectTypes, TaggedObject
+
+ dashboard = session_with_data.query(Dashboard).first()
+ chart = session_with_data.query(Slice).first()
+
+ objects_to_tag = [
+ (ObjectTypes.dashboard, dashboard.id),
+ ]
+
+ CreateCustomTagWithRelationshipsCommand(
+ data={"name": "test_tag", "objects_to_tag": objects_to_tag}
+ ).run()
+
+ tag_to_update = TagDAO.find_by_name("test_tag")
+
+ objects_to_tag = [
+ (ObjectTypes.chart, chart.id),
+ ]
+ changed_model = UpdateTagCommand(
+ tag_to_update.id,
+ {
+ "name": "new_name",
+ "description": "new_description",
+ "objects_to_tag": objects_to_tag,
+ },
+ ).run()
+
+ updated_tag = TagDAO.find_by_name("new_name")
+ assert updated_tag is not None
+ assert updated_tag.description == "new_description"
+ assert len(session_with_data.query(TaggedObject).all()) == len(objects_to_tag)
+ assert changed_model.objects[0].object_id == chart.id
+
+
+def test_create_command_failed(session_with_data: Session):
+ pass
Review Comment:
Missing a test here
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1302008024
##########
superset/tags/api.py:
##########
@@ -131,6 +141,131 @@ def __repr__(self) -> str:
f'{self.appbuilder.app.config["VERSION_SHA"]}'
)
+ @expose("/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
+ log_to_statsd=False,
+ )
+ def post(self) -> Response:
+ """Creates a new Tags and tag items
+ ---
+ post:
+ description: >-
+ Create a new Tag
+ requestBody:
+ description: Tag schema
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ responses:
+ 201:
+ description: Tag added
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id:
+ type: number
+ result:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 422:
+ $ref: '#/components/responses/422'
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ try:
+ item = self.add_model_schema.load(request.json)
+ except ValidationError as error:
+ return self.response_400(message=error.messages)
+ try:
+ CreateCustomTagWithRelationshipsCommand(item).run()
+ return self.response(201)
+ except TagInvalidError as ex:
+ return self.response_422(message=ex.normalized_messages())
Review Comment:
can we do this instead?
`return self.response(ex.status, message=ex.message)`
It seems better to have the status on the exception itself so that the exception always returns the same error code.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] hughhhh merged pull request #24839: feat: Update Tags CRUD API
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh merged PR #24839:
URL: https://github.com/apache/superset/pull/24839
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1303513797
##########
superset/tags/commands/update.py:
##########
@@ -0,0 +1,86 @@
+# 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 Any, Optional
+
+from flask_appbuilder.models.sqla import Model
+
+from superset import db
+from superset.commands.base import BaseCommand, UpdateMixin
+from superset.daos.exceptions import DAOUpdateFailedError
+from superset.daos.tag import TagDAO
+from superset.tags.commands.exceptions import TagInvalidError, TagNotFoundError
+from superset.tags.commands.utils import to_object_type
+from superset.tags.exceptions import TagUpdateFailedError
+from superset.tags.models import Tag
+
+logger = logging.getLogger(__name__)
+
+
+class UpdateTagCommand(UpdateMixin, BaseCommand):
+ def __init__(self, model_id: int, data: dict[str, Any]):
+ self._model_id = model_id
+ self._properties = data.copy()
+ self._model: Optional[Tag] = None
+
+ def run(self) -> Model:
+ self.validate()
+
+ try:
+ if self._model:
+ if self._properties.get("objects_to_tag"):
+ # todo(hugh): can this manage duplication
+ TagDAO.create_tag_relationship(
+ objects_to_tag=self._properties["objects_to_tag"],
+ tag=self._model,
+ )
+ if description := self._properties.get("description"):
+ self._model.description = description
+ if tag_name := self._properties.get("name"):
+ self._model.name = tag_name
+
+ db.session.add(self._model)
+ db.session.commit()
+
+ return self._model
+
+ except DAOUpdateFailedError as ex:
+ logger.exception(ex.exception)
Review Comment:
don't need
##########
superset/tags/commands/update.py:
##########
@@ -0,0 +1,86 @@
+# 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 Any, Optional
+
+from flask_appbuilder.models.sqla import Model
+
+from superset import db
+from superset.commands.base import BaseCommand, UpdateMixin
+from superset.daos.exceptions import DAOUpdateFailedError
+from superset.daos.tag import TagDAO
+from superset.tags.commands.exceptions import TagInvalidError, TagNotFoundError
+from superset.tags.commands.utils import to_object_type
+from superset.tags.exceptions import TagUpdateFailedError
+from superset.tags.models import Tag
+
+logger = logging.getLogger(__name__)
+
+
+class UpdateTagCommand(UpdateMixin, BaseCommand):
+ def __init__(self, model_id: int, data: dict[str, Any]):
+ self._model_id = model_id
+ self._properties = data.copy()
+ self._model: Optional[Tag] = None
+
+ def run(self) -> Model:
+ self.validate()
+
+ try:
+ if self._model:
+ if self._properties.get("objects_to_tag"):
+ # todo(hugh): can this manage duplication
+ TagDAO.create_tag_relationship(
+ objects_to_tag=self._properties["objects_to_tag"],
+ tag=self._model,
+ )
+ if description := self._properties.get("description"):
+ self._model.description = description
+ if tag_name := self._properties.get("name"):
+ self._model.name = tag_name
+
+ db.session.add(self._model)
+ db.session.commit()
+
+ return self._model
+
+ except DAOUpdateFailedError as ex:
+ logger.exception(ex.exception)
+ raise TagUpdateFailedError() from ex
+
+ def validate(self) -> None:
+ exceptions = []
+ # Validate/populate model exists
+ self._model = TagDAO.find_by_id(self._model_id)
+ if not self._model:
+ raise TagNotFoundError()
+
+ # Validate object_id
+ if objects_to_tag := self._properties.get("objects_to_tag"):
+ if any(obj_id == 0 for obj_type, obj_id in objects_to_tag):
+ exceptions.append(TagUpdateFailedError())
Review Comment:
use a 422 here and below
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1303511598
##########
superset/tags/commands/create.py:
##########
@@ -60,3 +62,45 @@ def validate(self) -> None:
)
if exceptions:
raise TagInvalidError(exceptions=exceptions)
+
+
+class CreateCustomTagWithRelationshipsCommand(CreateMixin, BaseCommand):
+ def __init__(self, data: dict[str, Any]):
+ self._tag = data["name"]
+ self._objects_to_tag = data.get("objects_to_tag")
+ self._description = data.get("description")
+
+ def run(self) -> None:
+ self.validate()
+ try:
+ tag = TagDAO.get_by_name(self._tag.strip(), TagTypes.custom)
+ if self._objects_to_tag:
+ TagDAO.create_tag_relationship(
+ objects_to_tag=self._objects_to_tag, tag=tag
+ )
+
+ if self._description:
+ tag.description = self._description
+ db.session.commit()
+
+ except DAOCreateFailedError as ex:
+ logger.exception(ex.exception)
+ raise TagCreateFailedError() from ex
+
+ def validate(self) -> None:
+ exceptions = []
+ # Validate object_id
+ if self._objects_to_tag:
+ if any(obj_id == 0 for obj_type, obj_id in self._objects_to_tag):
+ exceptions.append(TagCreateFailedError())
Review Comment:
@hughhhh let's make this a different 422 error, not the same one that we're using for the 500.
##########
superset/tags/commands/create.py:
##########
@@ -60,3 +62,45 @@ def validate(self) -> None:
)
if exceptions:
raise TagInvalidError(exceptions=exceptions)
+
+
+class CreateCustomTagWithRelationshipsCommand(CreateMixin, BaseCommand):
+ def __init__(self, data: dict[str, Any]):
+ self._tag = data["name"]
+ self._objects_to_tag = data.get("objects_to_tag")
+ self._description = data.get("description")
+
+ def run(self) -> None:
+ self.validate()
+ try:
+ tag = TagDAO.get_by_name(self._tag.strip(), TagTypes.custom)
+ if self._objects_to_tag:
+ TagDAO.create_tag_relationship(
+ objects_to_tag=self._objects_to_tag, tag=tag
+ )
+
+ if self._description:
+ tag.description = self._description
+ db.session.commit()
+
+ except DAOCreateFailedError as ex:
+ logger.exception(ex.exception)
+ raise TagCreateFailedError() from ex
+
+ def validate(self) -> None:
+ exceptions = []
+ # Validate object_id
+ if self._objects_to_tag:
+ if any(obj_id == 0 for obj_type, obj_id in self._objects_to_tag):
+ exceptions.append(TagCreateFailedError())
+
+ # Validate object type
+ for obj_type, obj_id in self._objects_to_tag:
+ object_type = to_object_type(obj_type)
+ if not object_type:
+ exceptions.append(
+ TagCreateFailedError(f"invalid object type {object_type}")
Review Comment:
same here, 422
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: Update Tags CRUD API [superset]
Posted by "jordibeen (via GitHub)" <gi...@apache.org>.
jordibeen commented on PR #24839:
URL: https://github.com/apache/superset/pull/24839#issuecomment-1763952096
Yes, the issue I mentioned above is with the `TAGGING_SYSTEM` feature flag **already enabled**.
Enabling this *does* give us the option to create and apply tags on a Chart (by editing the Chart Properties), but it *doesn't* add the "New Tag" button on the Tag ListView page.
We're looking for some kind of "Tag management" like in the video above, but our [superset-domain]/superset/tags page doesn't have all the functionalities that the video in this PR shows, such as the "New Tag" button in the top right. (We're on 3.0.0)
Even though this PR was merged into master on August 25, it doesn't seem to exist in [the source code](https://github.com/apache/superset/blob/3.0.1rc1/superset-frontend/src/pages/Tags/index.tsx) of the [upcoming 3.0.1rc1 release candidate](https://github.com/apache/superset/releases/tag/3.0.1rc1).
I guess my question is: which Superset version will contain this great new `Tag` ListView page?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] Antonio-RiveroMartnez commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "Antonio-RiveroMartnez (via GitHub)" <gi...@apache.org>.
Antonio-RiveroMartnez commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1293555233
##########
superset-frontend/src/features/tags/TagModal.tsx:
##########
@@ -0,0 +1,323 @@
+/**
+ * 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 React, { ChangeEvent, useState, useEffect } from 'react';
+import rison from 'rison';
+import Modal from 'src/components/Modal';
+import AsyncSelect from 'src/components/Select/AsyncSelect';
+import { FormLabel } from 'src/components/Form';
+import { t, SupersetClient } from '@superset-ui/core';
+import { Input } from 'antd';
+import { Divider } from 'src/components';
+import Button from 'src/components/Button';
+import { Tag } from 'src/views/CRUD/types';
+import { fetchObjects } from 'src/features/tags/tags';
+
+interface TaggableResourceOption {
+ label: string;
+ value: number;
+ key: number;
+}
+
+enum TaggableResources {
+ Chart = 'chart',
+ Dashboard = 'dashboard',
+ SavedQuery = 'query',
+}
+
+interface TagModalProps {
+ onHide: () => void;
+ refreshData: () => void;
+ addSuccessToast: (msg: string) => void;
+ addDangerToast: (msg: string) => void;
+ show: boolean;
+ editTag: Tag | null;
Review Comment:
Could we use `?`
##########
superset-frontend/src/features/tags/TagModal.tsx:
##########
@@ -0,0 +1,323 @@
+/**
+ * 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 React, { ChangeEvent, useState, useEffect } from 'react';
+import rison from 'rison';
+import Modal from 'src/components/Modal';
+import AsyncSelect from 'src/components/Select/AsyncSelect';
+import { FormLabel } from 'src/components/Form';
+import { t, SupersetClient } from '@superset-ui/core';
+import { Input } from 'antd';
+import { Divider } from 'src/components';
+import Button from 'src/components/Button';
+import { Tag } from 'src/views/CRUD/types';
+import { fetchObjects } from 'src/features/tags/tags';
+
+interface TaggableResourceOption {
+ label: string;
+ value: number;
+ key: number;
+}
+
+enum TaggableResources {
+ Chart = 'chart',
+ Dashboard = 'dashboard',
+ SavedQuery = 'query',
+}
+
+interface TagModalProps {
+ onHide: () => void;
+ refreshData: () => void;
+ addSuccessToast: (msg: string) => void;
+ addDangerToast: (msg: string) => void;
+ show: boolean;
+ editTag: Tag | null;
+}
+
+const TagModal: React.FC<TagModalProps> = ({
+ show,
+ onHide,
+ editTag,
+ refreshData,
+ addSuccessToast,
+ addDangerToast,
+}) => {
+ const [dashboardsToTag, setDashboardsToTag] = useState<
+ TaggableResourceOption[]
+ >([]);
+ const [chartsToTag, setChartsToTag] = useState<TaggableResourceOption[]>([]);
+ const [savedQueriesToTag, setSavedQueriesToTag] = useState<
+ TaggableResourceOption[]
+ >([]);
+
+ const [tagName, setTagName] = useState<string>('');
+ const [description, setDescription] = useState<string>('');
+
+ const isEditMode = !!editTag;
+ const modalTitle = isEditMode ? 'Edit Tag' : 'Create Tag';
+
+ useEffect(() => {
+ setDashboardsToTag([]);
+ setChartsToTag([]);
+ setSavedQueriesToTag([]);
+ const dashboards: TaggableResourceOption[] = [];
+ const charts: TaggableResourceOption[] = [];
+ const queries: TaggableResourceOption[] = [];
+ if (isEditMode) {
+ fetchObjects(
+ { tags: editTag.name, types: null },
+ (data: Tag[]) => {
+ data.forEach(function (object) {
Review Comment:
DRY nit:
```
const resourceArrays = {
[TaggableResources.Dashboard]: dashboards,
[TaggableResources.Chart]: charts,
[TaggableResources.SavedQuery]: queries,
};
data.forEach((object) => {
const resourceOption = {
value: object.id,
label: object.name,
key: object.id,
};
if (resourceArrays[object.type]) {
resourceArrays[object.type].push(resourceOption);
}
});
```
##########
superset-frontend/src/features/tags/TagModal.tsx:
##########
@@ -0,0 +1,323 @@
+/**
+ * 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 React, { ChangeEvent, useState, useEffect } from 'react';
+import rison from 'rison';
+import Modal from 'src/components/Modal';
+import AsyncSelect from 'src/components/Select/AsyncSelect';
+import { FormLabel } from 'src/components/Form';
+import { t, SupersetClient } from '@superset-ui/core';
+import { Input } from 'antd';
+import { Divider } from 'src/components';
+import Button from 'src/components/Button';
+import { Tag } from 'src/views/CRUD/types';
+import { fetchObjects } from 'src/features/tags/tags';
+
+interface TaggableResourceOption {
+ label: string;
+ value: number;
+ key: number;
+}
+
+enum TaggableResources {
+ Chart = 'chart',
+ Dashboard = 'dashboard',
+ SavedQuery = 'query',
+}
+
+interface TagModalProps {
+ onHide: () => void;
+ refreshData: () => void;
+ addSuccessToast: (msg: string) => void;
+ addDangerToast: (msg: string) => void;
+ show: boolean;
+ editTag: Tag | null;
+}
+
+const TagModal: React.FC<TagModalProps> = ({
Review Comment:
Could we add some tests for this component?
##########
superset-frontend/src/views/CRUD/hooks.ts:
##########
@@ -746,6 +746,7 @@ export function useDatabaseValidation() {
);
const getValidation = useCallback(
(database: Partial<DatabaseObject> | null, onCreate = false) => {
+ console.log(database?.parameters);
Review Comment:
leftover
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat: Update Tags CRUD API [superset]
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on PR #24839:
URL: https://github.com/apache/superset/pull/24839#issuecomment-1762221339
Hi @jordibeen, you can test out the feature by turning on the `TAGGING_SYSTEM` feature flag in your config. It's still in a development/testing stage, so you may find it a little buggy until it's ready for GA, which will likely be around the 3.1 release.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1304570969
##########
superset/tags/commands/create.py:
##########
@@ -60,3 +62,45 @@ def validate(self) -> None:
)
if exceptions:
raise TagInvalidError(exceptions=exceptions)
+
+
+class CreateCustomTagWithRelationshipsCommand(CreateMixin, BaseCommand):
+ def __init__(self, data: dict[str, Any]):
+ self._tag = data["name"]
+ self._objects_to_tag = data.get("objects_to_tag")
+ self._description = data.get("description")
+
+ def run(self) -> None:
+ self.validate()
+ try:
+ tag = TagDAO.get_by_name(self._tag.strip(), TagTypes.custom)
+ if self._objects_to_tag:
+ TagDAO.create_tag_relationship(
+ objects_to_tag=self._objects_to_tag, tag=tag
+ )
+
+ if self._description:
+ tag.description = self._description
+ db.session.commit()
+
+ except DAOCreateFailedError as ex:
+ logger.exception(ex.exception)
+ raise TagCreateFailedError() from ex
+
+ def validate(self) -> None:
+ exceptions = []
+ # Validate object_id
+ if self._objects_to_tag:
+ if any(obj_id == 0 for obj_type, obj_id in self._objects_to_tag):
+ exceptions.append(TagCreateFailedError())
Review Comment:
```suggestion
exceptions.append(TagInvalidError())
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] zhaoyongjie commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "zhaoyongjie (via GitHub)" <gi...@apache.org>.
zhaoyongjie commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1302946326
##########
superset/tags/api.py:
##########
@@ -131,6 +141,131 @@ def __repr__(self) -> str:
f'{self.appbuilder.app.config["VERSION_SHA"]}'
)
+ @expose("/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
+ log_to_statsd=False,
+ )
+ def post(self) -> Response:
+ """Creates a new Tags and tag items
+ ---
+ post:
+ description: >-
+ Create a new Tag
+ requestBody:
+ description: Tag schema
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ responses:
+ 201:
+ description: Tag added
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id:
+ type: number
+ result:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 422:
+ $ref: '#/components/responses/422'
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ try:
+ item = self.add_model_schema.load(request.json)
+ except ValidationError as error:
+ return self.response_400(message=error.messages)
+ try:
+ CreateCustomTagWithRelationshipsCommand(item).run()
+ return self.response(201)
+ except TagInvalidError as ex:
+ return self.response_422(message=ex.normalized_messages())
+ except TagCreateFailedError as ex:
+ logger.error(
+ "Error creating model %s: %s",
+ self.__class__.__name__,
+ str(ex),
+ exc_info=True,
+ )
+ return self.response_500(message=str(ex))
Review Comment:
Hey @hughhhh 500 error means that the server encountered an [unexpected condition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500), you've got `TagCreateFailedError` why you raise 500 error still?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1303504318
##########
superset/daos/tag.py:
##########
@@ -363,3 +364,46 @@ def favorited_ids(tags: list[Tag]) -> list[int]:
)
.all()
]
+
+ @staticmethod
+ def create_tag_relationship(
+ objects_to_tag: list[tuple[ObjectTypes, int]], tag: Tag
+ ) -> None:
+ """
+ Creates a tag relationship between the given objects and the specified tag.
+ This function iterates over a list of objects, each specified by a type
+ and an id, and creates a TaggedObject for each one, associating it with
+ the provided tag. All created TaggedObjects are collected in a list.
+ Args:
+ objects_to_tag (List[Tuple[ObjectTypes, int]]): A list of tuples, each
+ containing an ObjectType and an id, representing the objects to be tagged.
+
+ tag (Tag): The tag to be associated with the specified objects.
+ Returns:
+ None.
+ """
+ tagged_objects = []
+ if not tag:
+ raise TagNotFoundError()
Review Comment:
@Antonio-RiveroMartnez I'm going to take a pass at cleaning up this logic in the future and move all status codes to the exceptions instead of the api.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1303515349
##########
superset/tags/exceptions.py:
##########
@@ -27,3 +29,11 @@ def __init__(self) -> None:
super().__init__(
[_("Tag name is invalid (cannot contain ':')")], field_name="name"
)
+
+
+class TagUpdateFailedError(UpdateFailedError):
+ message = _("Tag could not be updated.")
Review Comment:
```suggestion
message = _("Tag could not be updated.")
status = 422
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1303507770
##########
superset/tags/api.py:
##########
@@ -131,6 +141,131 @@ def __repr__(self) -> str:
f'{self.appbuilder.app.config["VERSION_SHA"]}'
)
+ @expose("/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
+ log_to_statsd=False,
+ )
+ def post(self) -> Response:
+ """Creates a new Tags and tag items
+ ---
+ post:
+ description: >-
+ Create a new Tag
+ requestBody:
+ description: Tag schema
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ responses:
+ 201:
+ description: Tag added
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id:
+ type: number
+ result:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 422:
+ $ref: '#/components/responses/422'
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ try:
+ item = self.add_model_schema.load(request.json)
+ except ValidationError as error:
+ return self.response_400(message=error.messages)
+ try:
+ CreateCustomTagWithRelationshipsCommand(item).run()
+ return self.response(201)
+ except TagInvalidError as ex:
+ return self.response_422(message=ex.normalized_messages())
+ except TagCreateFailedError as ex:
+ logger.error(
+ "Error creating model %s: %s",
+ self.__class__.__name__,
+ str(ex),
+ exc_info=True,
+ )
+ return self.response_500(message=str(ex))
Review Comment:
TagCreateFailedError is a 500 error.
##########
superset/tags/api.py:
##########
@@ -131,6 +141,131 @@ def __repr__(self) -> str:
f'{self.appbuilder.app.config["VERSION_SHA"]}'
)
+ @expose("/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
+ log_to_statsd=False,
+ )
+ def post(self) -> Response:
+ """Creates a new Tags and tag items
+ ---
+ post:
+ description: >-
+ Create a new Tag
+ requestBody:
+ description: Tag schema
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ responses:
+ 201:
+ description: Tag added
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id:
+ type: number
+ result:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 422:
+ $ref: '#/components/responses/422'
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ try:
+ item = self.add_model_schema.load(request.json)
+ except ValidationError as error:
+ return self.response_400(message=error.messages)
+ try:
+ CreateCustomTagWithRelationshipsCommand(item).run()
+ return self.response(201)
+ except TagInvalidError as ex:
+ return self.response_422(message=ex.normalized_messages())
+ except TagCreateFailedError as ex:
+ logger.error(
+ "Error creating model %s: %s",
+ self.__class__.__name__,
+ str(ex),
+ exc_info=True,
+ )
+ return self.response_500(message=str(ex))
Review Comment:
TagCreateFailedError is a 500 exception.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1303506564
##########
superset/tags/api.py:
##########
@@ -131,6 +141,131 @@ def __repr__(self) -> str:
f'{self.appbuilder.app.config["VERSION_SHA"]}'
)
+ @expose("/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
+ log_to_statsd=False,
+ )
+ def post(self) -> Response:
+ """Creates a new Tags and tag items
+ ---
+ post:
+ description: >-
+ Create a new Tag
+ requestBody:
+ description: Tag schema
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ responses:
+ 201:
+ description: Tag added
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id:
+ type: number
+ result:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 422:
+ $ref: '#/components/responses/422'
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ try:
+ item = self.add_model_schema.load(request.json)
+ except ValidationError as error:
+ return self.response_400(message=error.messages)
+ try:
+ CreateCustomTagWithRelationshipsCommand(item).run()
+ return self.response(201)
+ except TagInvalidError as ex:
+ return self.response_422(message=ex.normalized_messages())
Review Comment:
Per previous comment, I'll take this as a separate follow up item.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1303514623
##########
superset/tags/exceptions.py:
##########
@@ -27,3 +29,11 @@ def __init__(self) -> None:
super().__init__(
[_("Tag name is invalid (cannot contain ':')")], field_name="name"
)
+
+
+class TagUpdateFailedError(UpdateFailedError):
+ message = _("Tag could not be updated.")
+
+
+class TagNotFoundError(CommandException):
+ message = _("Tag could not be found.")
Review Comment:
while you're here, can you add
`status = 404`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] Antonio-RiveroMartnez commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "Antonio-RiveroMartnez (via GitHub)" <gi...@apache.org>.
Antonio-RiveroMartnez commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1297436301
##########
tests/integration_tests/tags/api_tests.py:
##########
@@ -457,3 +458,46 @@ def test_delete_favorite_tag_user_not_found(self, flask_g):
rv = self.client.delete(uri, follow_redirects=True)
self.assertEqual(rv.status_code, 422)
+
+ @pytest.mark.usefixtures("load_world_bank_dashboard_with_slices")
Review Comment:
Could we test the fail cases for this and the `put` one?
##########
superset/daos/tag.py:
##########
@@ -363,3 +364,46 @@ def favorited_ids(tags: list[Tag]) -> list[int]:
)
.all()
]
+
+ @staticmethod
+ def create_tag_relationship(
+ objects_to_tag: list[tuple[ObjectTypes, int]], tag: Tag
+ ) -> None:
+ """
+ Creates a tag relationship between the given objects and the specified tag.
+ This function iterates over a list of objects, each specified by a type
+ and an id, and creates a TaggedObject for each one, associating it with
+ the provided tag. All created TaggedObjects are collected in a list.
+ Args:
+ objects_to_tag (List[Tuple[ObjectTypes, int]]): A list of tuples, each
+ containing an ObjectType and an id, representing the objects to be tagged.
+
+ tag (Tag): The tag to be associated with the specified objects.
+ Returns:
+ None.
+ """
+ tagged_objects = []
+ if not tag:
+ raise TagNotFoundError()
Review Comment:
Could we add status 404 to this exception? or probably use the `ObjectNotFoundError`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1300557326
##########
superset/tags/api.py:
##########
@@ -131,6 +141,131 @@ def __repr__(self) -> str:
f'{self.appbuilder.app.config["VERSION_SHA"]}'
)
+ @expose("/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
+ log_to_statsd=False,
+ )
+ def post(self) -> Response:
+ """Creates a new Tags and tag items
+ ---
+ post:
+ description: >-
+ Create a new Tag
+ requestBody:
+ description: Tag schema
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ responses:
+ 201:
+ description: Tag added
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id:
+ type: number
+ result:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 422:
+ $ref: '#/components/responses/422'
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ try:
+ item = self.add_model_schema.load(request.json)
+ except ValidationError as error:
+ return self.response_400(message=error.messages)
+ try:
+ CreateCustomTagWithRelationshipsCommand(item).run()
+ return self.response(201)
+ except TagInvalidError as ex:
+ return self.response_422(message=ex.normalized_messages())
+ except TaggedObjectDeleteFailedError as ex:
Review Comment:
did you mean TagCreateFailedError and TagInvalidError here?
Also since TagCreateFailedError raises after validation, I don't think it would be a 422 any more. wdyt?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] hughhhh commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1300670543
##########
superset/tags/api.py:
##########
@@ -131,6 +141,131 @@ def __repr__(self) -> str:
f'{self.appbuilder.app.config["VERSION_SHA"]}'
)
+ @expose("/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
+ log_to_statsd=False,
+ )
+ def post(self) -> Response:
+ """Creates a new Tags and tag items
+ ---
+ post:
+ description: >-
+ Create a new Tag
+ requestBody:
+ description: Tag schema
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ responses:
+ 201:
+ description: Tag added
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id:
+ type: number
+ result:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 422:
+ $ref: '#/components/responses/422'
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ try:
+ item = self.add_model_schema.load(request.json)
+ except ValidationError as error:
+ return self.response_400(message=error.messages)
+ try:
+ CreateCustomTagWithRelationshipsCommand(item).run()
+ return self.response(201)
+ except TagInvalidError as ex:
+ return self.response_422(message=ex.normalized_messages())
+ except TaggedObjectDeleteFailedError as ex:
Review Comment:
yea wrong error, but 422 seems fitting:
```
422 Unprocessable Entity: This can be used if the request was well-formed but semantically incorrect, such as if it violates business logic rules.
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1297862931
##########
superset-frontend/src/features/tags/TagModal.tsx:
##########
@@ -0,0 +1,321 @@
+/**
+ * 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 React, { ChangeEvent, useState, useEffect } from 'react';
+import rison from 'rison';
+import Modal from 'src/components/Modal';
+import AsyncSelect from 'src/components/Select/AsyncSelect';
+import { FormLabel } from 'src/components/Form';
+import { t, SupersetClient } from '@superset-ui/core';
+import { Input } from 'antd';
+import { Divider } from 'src/components';
+import Button from 'src/components/Button';
+import { Tag } from 'src/views/CRUD/types';
+import { fetchObjects } from 'src/features/tags/tags';
+
+interface TaggableResourceOption {
+ label: string;
+ value: number;
+ key: number;
+}
+
+export enum TaggableResources {
+ Chart = 'chart',
+ Dashboard = 'dashboard',
+ SavedQuery = 'query',
+}
+
+interface TagModalProps {
+ onHide: () => void;
+ refreshData: () => void;
+ addSuccessToast: (msg: string) => void;
+ addDangerToast: (msg: string) => void;
+ show: boolean;
+ editTag?: Tag | null;
+}
+
+const TagModal: React.FC<TagModalProps> = ({
+ show,
+ onHide,
+ editTag,
+ refreshData,
+ addSuccessToast,
+ addDangerToast,
+}) => {
+ const [dashboardsToTag, setDashboardsToTag] = useState<
+ TaggableResourceOption[]
+ >([]);
+ const [chartsToTag, setChartsToTag] = useState<TaggableResourceOption[]>([]);
+ const [savedQueriesToTag, setSavedQueriesToTag] = useState<
+ TaggableResourceOption[]
+ >([]);
+
+ const [tagName, setTagName] = useState<string>('');
+ const [description, setDescription] = useState<string>('');
+
+ const isEditMode = !!editTag;
+ const modalTitle = isEditMode ? 'Edit Tag' : 'Create Tag';
+
+ const clearResources = () => {
+ setDashboardsToTag([]);
+ setChartsToTag([]);
+ setSavedQueriesToTag([]);
+ };
+
+ useEffect(() => {
+ const resourceMap: { [key: string]: TaggableResourceOption[] } = {
+ [TaggableResources.Dashboard]: [],
+ [TaggableResources.Chart]: [],
+ [TaggableResources.SavedQuery]: [],
+ };
+
+ const updateResourceOptions = (object: Tag) => {
Review Comment:
another nit/style, I would recommend destructuring your object type in the parameters for this function to make the below block cleaner.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1297863178
##########
superset-frontend/src/features/tags/TagModal.tsx:
##########
@@ -0,0 +1,321 @@
+/**
+ * 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 React, { ChangeEvent, useState, useEffect } from 'react';
+import rison from 'rison';
+import Modal from 'src/components/Modal';
+import AsyncSelect from 'src/components/Select/AsyncSelect';
+import { FormLabel } from 'src/components/Form';
+import { t, SupersetClient } from '@superset-ui/core';
+import { Input } from 'antd';
+import { Divider } from 'src/components';
+import Button from 'src/components/Button';
+import { Tag } from 'src/views/CRUD/types';
+import { fetchObjects } from 'src/features/tags/tags';
+
+interface TaggableResourceOption {
+ label: string;
+ value: number;
+ key: number;
+}
+
+export enum TaggableResources {
+ Chart = 'chart',
+ Dashboard = 'dashboard',
+ SavedQuery = 'query',
+}
+
+interface TagModalProps {
+ onHide: () => void;
+ refreshData: () => void;
+ addSuccessToast: (msg: string) => void;
+ addDangerToast: (msg: string) => void;
+ show: boolean;
+ editTag?: Tag | null;
+}
+
+const TagModal: React.FC<TagModalProps> = ({
+ show,
+ onHide,
+ editTag,
+ refreshData,
+ addSuccessToast,
+ addDangerToast,
+}) => {
+ const [dashboardsToTag, setDashboardsToTag] = useState<
+ TaggableResourceOption[]
+ >([]);
+ const [chartsToTag, setChartsToTag] = useState<TaggableResourceOption[]>([]);
+ const [savedQueriesToTag, setSavedQueriesToTag] = useState<
+ TaggableResourceOption[]
+ >([]);
+
+ const [tagName, setTagName] = useState<string>('');
+ const [description, setDescription] = useState<string>('');
+
+ const isEditMode = !!editTag;
+ const modalTitle = isEditMode ? 'Edit Tag' : 'Create Tag';
+
+ const clearResources = () => {
+ setDashboardsToTag([]);
+ setChartsToTag([]);
+ setSavedQueriesToTag([]);
+ };
+
+ useEffect(() => {
+ const resourceMap: { [key: string]: TaggableResourceOption[] } = {
+ [TaggableResources.Dashboard]: [],
+ [TaggableResources.Chart]: [],
+ [TaggableResources.SavedQuery]: [],
+ };
+
+ const updateResourceOptions = (object: Tag) => {
Review Comment:
```suggestion
const updateResourceOptions = ({type, id, name}: Tag) => {
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1302008436
##########
superset/tags/api.py:
##########
@@ -131,6 +141,131 @@ def __repr__(self) -> str:
f'{self.appbuilder.app.config["VERSION_SHA"]}'
)
+ @expose("/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
+ log_to_statsd=False,
+ )
+ def post(self) -> Response:
+ """Creates a new Tags and tag items
+ ---
+ post:
+ description: >-
+ Create a new Tag
+ requestBody:
+ description: Tag schema
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ responses:
+ 201:
+ description: Tag added
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id:
+ type: number
+ result:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 422:
+ $ref: '#/components/responses/422'
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ try:
+ item = self.add_model_schema.load(request.json)
+ except ValidationError as error:
+ return self.response_400(message=error.messages)
+ try:
+ CreateCustomTagWithRelationshipsCommand(item).run()
+ return self.response(201)
+ except TagInvalidError as ex:
+ return self.response_422(message=ex.normalized_messages())
Review Comment:
I know there are currently two ways of returning in the codebase. As long as they both do the same thing, I would recommend this pattern.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1303501313
##########
superset/tags/api.py:
##########
@@ -131,6 +141,131 @@ def __repr__(self) -> str:
f'{self.appbuilder.app.config["VERSION_SHA"]}'
)
+ @expose("/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
+ log_to_statsd=False,
+ )
+ def post(self) -> Response:
+ """Creates a new Tags and tag items
+ ---
+ post:
+ description: >-
+ Create a new Tag
+ requestBody:
+ description: Tag schema
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ responses:
+ 201:
+ description: Tag added
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ id:
+ type: number
+ result:
+ $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 422:
+ $ref: '#/components/responses/422'
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ try:
+ item = self.add_model_schema.load(request.json)
+ except ValidationError as error:
+ return self.response_400(message=error.messages)
+ try:
+ CreateCustomTagWithRelationshipsCommand(item).run()
+ return self.response(201)
+ except TagInvalidError as ex:
+ return self.response_422(message=ex.normalized_messages())
+ except TagCreateFailedError as ex:
+ logger.error(
+ "Error creating model %s: %s",
+ self.__class__.__name__,
+ str(ex),
+ exc_info=True,
+ )
+ return self.response_500(message=str(ex))
Review Comment:
We don't know why it failed in other words.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1303514820
##########
superset/tags/exceptions.py:
##########
@@ -27,3 +29,11 @@ def __init__(self) -> None:
super().__init__(
[_("Tag name is invalid (cannot contain ':')")], field_name="name"
)
+
+
+class TagUpdateFailedError(UpdateFailedError):
+ message = _("Tag could not be updated.")
Review Comment:
`status = 422`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
[GitHub] [superset] eschutho commented on a diff in pull request #24839: feat: Update Tags CRUD API
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #24839:
URL: https://github.com/apache/superset/pull/24839#discussion_r1304570617
##########
superset/tags/commands/create.py:
##########
@@ -60,3 +62,45 @@ def validate(self) -> None:
)
if exceptions:
raise TagInvalidError(exceptions=exceptions)
+
+
+class CreateCustomTagWithRelationshipsCommand(CreateMixin, BaseCommand):
+ def __init__(self, data: dict[str, Any]):
+ self._tag = data["name"]
+ self._objects_to_tag = data.get("objects_to_tag")
+ self._description = data.get("description")
+
+ def run(self) -> None:
+ self.validate()
+ try:
+ tag = TagDAO.get_by_name(self._tag.strip(), TagTypes.custom)
+ if self._objects_to_tag:
+ TagDAO.create_tag_relationship(
+ objects_to_tag=self._objects_to_tag, tag=tag
+ )
+
+ if self._description:
+ tag.description = self._description
+ db.session.commit()
+
+ except DAOCreateFailedError as ex:
+ logger.exception(ex.exception)
+ raise TagCreateFailedError() from ex
+
+ def validate(self) -> None:
+ exceptions = []
+ # Validate object_id
+ if self._objects_to_tag:
+ if any(obj_id == 0 for obj_type, obj_id in self._objects_to_tag):
+ exceptions.append(TagCreateFailedError())
+
+ # Validate object type
+ for obj_type, obj_id in self._objects_to_tag:
+ object_type = to_object_type(obj_type)
+ if not object_type:
+ exceptions.append(
+ TagCreateFailedError(f"invalid object type {object_type}")
Review Comment:
```suggestion
TagInvalidError(f"invalid object type {object_type}")
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org