You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@devlake.apache.org by he...@apache.org on 2023/05/24 00:51:11 UTC

[incubator-devlake] branch main updated: [feat-4864] Support for deleting blueprints (#5227)

This is an automated email from the ASF dual-hosted git repository.

hez pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-devlake.git


The following commit(s) were added to refs/heads/main by this push:
     new 078eae861 [feat-4864] Support for deleting blueprints (#5227)
078eae861 is described below

commit 078eae86131820535fd867306d144714b55208eb
Author: Keon Amini <ke...@merico.dev>
AuthorDate: Tue May 23 19:51:06 2023 -0500

    [feat-4864] Support for deleting blueprints (#5227)
    
    * fix: make delete scopes transactional for when autocommit is off
    
    * feat: Basic support for deleting a blueprint from the backend
---
 .../pluginhelper/api/scope_generic_helper.go       | 118 +++++++++++++--------
 .../pluginhelper/services/blueprint_helper.go      |  11 ++
 backend/server/api/blueprints/blueprints.go        |  24 +++++
 backend/server/api/router.go                       |   2 +-
 backend/server/services/blueprint.go               |  13 +++
 backend/test/e2e/remote/helper.go                  |  59 +++++++++++
 backend/test/e2e/remote/python_plugin_test.go      |  63 ++++-------
 backend/test/helper/api.go                         |   9 +-
 8 files changed, 211 insertions(+), 88 deletions(-)

diff --git a/backend/helpers/pluginhelper/api/scope_generic_helper.go b/backend/helpers/pluginhelper/api/scope_generic_helper.go
index 71b37fa04..20b8be0eb 100644
--- a/backend/helpers/pluginhelper/api/scope_generic_helper.go
+++ b/backend/helpers/pluginhelper/api/scope_generic_helper.go
@@ -282,17 +282,6 @@ func (c *GenericScopeApiHelper[Conn, Scope, Tr]) DeleteScope(input *plugin.ApiRe
 	if err != nil {
 		return nil, errors.Default.Wrap(err, fmt.Sprintf("error verifying connection for connection ID %d", params.connectionId))
 	}
-	db := c.db
-	blueprintsMap, err := c.bpManager.GetBlueprintsByScopes(params.connectionId, params.scopeId)
-	if err != nil {
-		return nil, errors.Default.Wrap(err, fmt.Sprintf("error retrieving scope with scope ID %s", params.scopeId))
-	}
-	blueprints := blueprintsMap[params.scopeId]
-	// find all tables for this plugin
-	tables, err := getAffectedTables(params.plugin)
-	if err != nil {
-		return nil, errors.Default.Wrap(err, fmt.Sprintf("error getting database tables managed by plugin %s", params.plugin))
-	}
 	// delete all the plugin records referencing this scope
 	if c.reflectionParams.RawScopeParamName != "" {
 		scopeParamValue := params.scopeId
@@ -302,11 +291,14 @@ func (c *GenericScopeApiHelper[Conn, Scope, Tr]) DeleteScope(input *plugin.ApiRe
 				return nil, errors.Default.Wrap(err, fmt.Sprintf("error extracting scope parameter name for scope %s", params.scopeId))
 			}
 		}
-		for _, table := range tables {
-			err = db.Exec(createDeleteQuery(table, c.reflectionParams.RawScopeParamName, scopeParamValue))
-			if err != nil {
-				return nil, errors.Default.Wrap(err, fmt.Sprintf("error deleting data bound to scope %s for plugin %s", params.scopeId, params.plugin))
-			}
+		// find all tables for this plugin
+		tables, err := getAffectedTables(params.plugin)
+		if err != nil {
+			return nil, errors.Default.Wrap(err, fmt.Sprintf("error getting database tables managed by plugin %s", params.plugin))
+		}
+		err = c.transactionalDelete(tables, scopeParamValue)
+		if err != nil {
+			return nil, errors.Default.Wrap(err, fmt.Sprintf("error deleting data bound to scope %s for plugin %s", params.scopeId, params.plugin))
 		}
 	}
 	var impactedBlueprints []*models.Blueprint
@@ -316,36 +308,9 @@ func (c *GenericScopeApiHelper[Conn, Scope, Tr]) DeleteScope(input *plugin.ApiRe
 		if err != nil {
 			return nil, errors.Default.Wrap(err, fmt.Sprintf("error deleting scope %s", params.scopeId))
 		}
-		// update the blueprints (remove scope reference from them)
-		for _, blueprint := range blueprints {
-			settings, _ := blueprint.UnmarshalSettings()
-			var changed bool
-			err = settings.UpdateConnections(func(c *plugin.BlueprintConnectionV200) errors.Error {
-				var retainedScopes []*plugin.BlueprintScopeV200
-				for _, bpScope := range c.Scopes {
-					if bpScope.Id == params.scopeId { // we'll be removing this one
-						changed = true
-					} else {
-						retainedScopes = append(retainedScopes, bpScope)
-					}
-				}
-				c.Scopes = retainedScopes
-				return nil
-			})
-			if err != nil {
-				return nil, errors.Default.Wrap(err, fmt.Sprintf("error removing scope %s from blueprint %d", params.scopeId, blueprint.ID))
-			}
-			if changed {
-				err = blueprint.UpdateSettings(&settings)
-				if err != nil {
-					return nil, errors.Default.Wrap(err, fmt.Sprintf("error writing new settings into blueprint %s", blueprint.Name))
-				}
-				err = c.bpManager.SaveDbBlueprint(blueprint)
-				if err != nil {
-					return nil, errors.Default.Wrap(err, fmt.Sprintf("error saving the updated blueprint %s", blueprint.Name))
-				}
-				impactedBlueprints = append(impactedBlueprints, blueprint)
-			}
+		impactedBlueprints, err = c.updateBlueprints(params.connectionId, params.scopeId)
+		if err != nil {
+			return nil, err
 		}
 	}
 	return impactedBlueprints, nil
@@ -542,6 +507,67 @@ func (c *GenericScopeApiHelper[Conn, Scope, Tr]) validatePrimaryKeys(scopes []*S
 	return nil
 }
 
+func (c *GenericScopeApiHelper[Conn, Scope, Tr]) updateBlueprints(connectionId uint64, scopeId string) ([]*models.Blueprint, errors.Error) {
+	blueprintsMap, err := c.bpManager.GetBlueprintsByScopes(connectionId, scopeId)
+	if err != nil {
+		return nil, errors.Default.Wrap(err, fmt.Sprintf("error retrieving scope with scope ID %s", scopeId))
+	}
+	blueprints := blueprintsMap[scopeId]
+	var impactedBlueprints []*models.Blueprint
+	// update the blueprints (remove scope reference from them)
+	for _, blueprint := range blueprints {
+		settings, _ := blueprint.UnmarshalSettings()
+		var changed bool
+		err = settings.UpdateConnections(func(c *plugin.BlueprintConnectionV200) errors.Error {
+			var retainedScopes []*plugin.BlueprintScopeV200
+			for _, bpScope := range c.Scopes {
+				if bpScope.Id == scopeId { // we'll be removing this one
+					changed = true
+				} else {
+					retainedScopes = append(retainedScopes, bpScope)
+				}
+			}
+			c.Scopes = retainedScopes
+			return nil
+		})
+		if err != nil {
+			return nil, errors.Default.Wrap(err, fmt.Sprintf("error removing scope %s from blueprint %d", scopeId, blueprint.ID))
+		}
+		if changed {
+			err = blueprint.UpdateSettings(&settings)
+			if err != nil {
+				return nil, errors.Default.Wrap(err, fmt.Sprintf("error writing new settings into blueprint %s", blueprint.Name))
+			}
+			err = c.bpManager.SaveDbBlueprint(blueprint)
+			if err != nil {
+				return nil, errors.Default.Wrap(err, fmt.Sprintf("error saving the updated blueprint %s", blueprint.Name))
+			}
+			impactedBlueprints = append(impactedBlueprints, blueprint)
+		}
+	}
+	return impactedBlueprints, nil
+}
+
+func (c *GenericScopeApiHelper[Conn, Scope, Tr]) transactionalDelete(tables []string, scopeId string) errors.Error {
+	tx := c.db.Begin()
+	for _, table := range tables {
+		query := createDeleteQuery(table, c.reflectionParams.RawScopeParamName, scopeId)
+		err := tx.Exec(query)
+		if err != nil {
+			err2 := tx.Rollback()
+			if err2 != nil {
+				c.log.Warn(err2, fmt.Sprintf("error rolling back table data deletion transaction. query was %s", query))
+			}
+			return err
+		}
+	}
+	err := tx.Commit()
+	if err != nil {
+		return errors.Default.Wrap(err, "error committing delete transaction for plugin tables")
+	}
+	return nil
+}
+
 // Implement MarshalJSON method to flatten all fields
 func (sr *ScopeRes[T]) MarshalJSON() ([]byte, error) {
 	var flatMap map[string]interface{}
diff --git a/backend/helpers/pluginhelper/services/blueprint_helper.go b/backend/helpers/pluginhelper/services/blueprint_helper.go
index 6fa01e0d7..554bdc53d 100644
--- a/backend/helpers/pluginhelper/services/blueprint_helper.go
+++ b/backend/helpers/pluginhelper/services/blueprint_helper.go
@@ -22,6 +22,7 @@ import (
 	"github.com/apache/incubator-devlake/core/dal"
 	"github.com/apache/incubator-devlake/core/errors"
 	"github.com/apache/incubator-devlake/core/models"
+	"github.com/apache/incubator-devlake/core/models/common"
 	"github.com/apache/incubator-devlake/core/plugin"
 )
 
@@ -191,6 +192,16 @@ func (b *BlueprintManager) GetDbBlueprintByProjectName(projectName string) (*mod
 	return dbBlueprint, nil
 }
 
+// DeleteBlueprint deletes a blueprint by its id
+func (b *BlueprintManager) DeleteBlueprint(id uint64) errors.Error {
+	dbBlueprint := &models.Blueprint{
+		Model: common.Model{
+			ID: id,
+		},
+	}
+	return b.db.Delete(&dbBlueprint)
+}
+
 func (b *BlueprintManager) fillBlueprintDetail(blueprint *models.Blueprint) errors.Error {
 	err := b.db.Pluck("name", &blueprint.Labels, dal.From(&models.DbBlueprintLabel{}), dal.Where("blueprint_id = ?", blueprint.ID))
 	if err != nil {
diff --git a/backend/server/api/blueprints/blueprints.go b/backend/server/api/blueprints/blueprints.go
index 9810ba585..7f9bff3b8 100644
--- a/backend/server/api/blueprints/blueprints.go
+++ b/backend/server/api/blueprints/blueprints.go
@@ -216,3 +216,27 @@ func GetBlueprintPipelines(c *gin.Context) {
 	}
 	shared.ApiOutputSuccess(c, shared.ResponsePipelines{Pipelines: pipelines, Count: count}, http.StatusOK)
 }
+
+// @Summary delete blueprint by id
+// @Description delete blueprint by id
+// @Tags framework/blueprints
+// @Accept application/json
+// @Param blueprintId path int true "blueprint id"
+// @Success 200
+// @Failure 400  {object} shared.ApiBody "Bad Request"
+// @Failure 500  {object} shared.ApiBody "Internal Error"
+// @Router /blueprints/{blueprintId} [delete]
+func Delete(c *gin.Context) {
+	blueprintId := c.Param("blueprintId")
+	id, err := strconv.ParseUint(blueprintId, 10, 64)
+	if err != nil {
+		shared.ApiOutputError(c, errors.BadInput.Wrap(err, "bad blueprintId format supplied"))
+		return
+	}
+	err = services.DeleteBlueprint(id)
+	if err != nil {
+		shared.ApiOutputError(c, errors.Default.Wrap(err, "error deleting blueprint"))
+		return
+	}
+	shared.ApiOutputSuccess(c, nil, http.StatusOK)
+}
diff --git a/backend/server/api/router.go b/backend/server/api/router.go
index 73e21856d..217c7306b 100644
--- a/backend/server/api/router.go
+++ b/backend/server/api/router.go
@@ -42,7 +42,7 @@ func RegisterRouter(r *gin.Engine) {
 	r.GET("/pipelines/:pipelineId", pipelines.Get)
 	r.PATCH("/blueprints/:blueprintId", blueprints.Patch)
 	r.POST("/blueprints/:blueprintId/trigger", blueprints.Trigger)
-	// r.DELETE("/blueprints/:blueprintId", blueprints.Delete)
+	r.DELETE("/blueprints/:blueprintId", blueprints.Delete)
 
 	r.GET("/blueprints", blueprints.Index)
 	r.POST("/blueprints", blueprints.Post)
diff --git a/backend/server/services/blueprint.go b/backend/server/services/blueprint.go
index 0e8d5c176..f89438d6b 100644
--- a/backend/server/services/blueprint.go
+++ b/backend/server/services/blueprint.go
@@ -224,6 +224,19 @@ func PatchBlueprint(id uint64, body map[string]interface{}) (*models.Blueprint,
 	return blueprint, nil
 }
 
+// DeleteBlueprint FIXME ...
+func DeleteBlueprint(id uint64) errors.Error {
+	bp, err := bpManager.GetDbBlueprint(id)
+	if err != nil {
+		return err
+	}
+	err = bpManager.DeleteBlueprint(bp.ID)
+	if err != nil {
+		return errors.Default.Wrap(err, "Failed to delete the blueprint")
+	}
+	return nil
+}
+
 // ReloadBlueprints FIXME ...
 func ReloadBlueprints(c *cron.Cron) errors.Error {
 	enable := true
diff --git a/backend/test/e2e/remote/helper.go b/backend/test/e2e/remote/helper.go
index e47be0613..d706a19bc 100644
--- a/backend/test/e2e/remote/helper.go
+++ b/backend/test/e2e/remote/helper.go
@@ -19,6 +19,9 @@ package remote
 
 import (
 	"fmt"
+	"github.com/apache/incubator-devlake/core/models"
+	"github.com/apache/incubator-devlake/core/plugin"
+	"github.com/stretchr/testify/require"
 	"os"
 	"path/filepath"
 	"testing"
@@ -51,6 +54,13 @@ type (
 		Name string `json:"name"`
 		Env  string `json:"env"`
 	}
+	BlueprintTestParams struct {
+		connection *helper.Connection
+		projects   []models.ApiOutputProject
+		blueprints []models.Blueprint
+		rule       *FakeTxRule
+		scope      *FakeProject
+	}
 )
 
 func ConnectLocalServer(t *testing.T) *helper.DevlakeClient {
@@ -96,3 +106,52 @@ func CreateTestTransformationRule(client *helper.DevlakeClient, connectionId uin
 	rule := helper.Cast[FakeTxRule](client.CreateTransformationRule(PLUGIN_NAME, connectionId, FakeTxRule{Name: "Tx rule", Env: "test env"}))
 	return &rule
 }
+
+func CreateTestBlueprints(t *testing.T, client *helper.DevlakeClient, count int) *BlueprintTestParams {
+	t.Helper()
+	connection := CreateTestConnection(client)
+	rule := CreateTestTransformationRule(client, connection.ID)
+	scope := CreateTestScope(client, rule, connection.ID)
+	var bps []models.Blueprint
+	var projects []models.ApiOutputProject
+	for i := 1; i <= count; i++ {
+		projectName := fmt.Sprintf("Test project %d", i)
+		client.CreateProject(&helper.ProjectConfig{
+			ProjectName: projectName,
+		})
+		blueprint := client.CreateBasicBlueprintV2(
+			fmt.Sprintf("Test blueprint %d", i),
+			&helper.BlueprintV2Config{
+				Connection: &plugin.BlueprintConnectionV200{
+					Plugin:       "fake",
+					ConnectionId: connection.ID,
+					Scopes: []*plugin.BlueprintScopeV200{
+						{
+							Id:   scope.Id,
+							Name: "Test scope",
+							Entities: []string{
+								plugin.DOMAIN_TYPE_CICD,
+							},
+						},
+					},
+				},
+				SkipOnFail:  true,
+				ProjectName: projectName,
+			},
+		)
+		plan, err := blueprint.UnmarshalPlan()
+		require.NoError(t, err)
+		_ = plan
+		bps = append(bps, blueprint)
+		project := client.GetProject(projectName)
+		require.Equal(t, blueprint.Name, project.Blueprint.Name)
+		projects = append(projects, project)
+	}
+	return &BlueprintTestParams{
+		connection: connection,
+		projects:   projects,
+		blueprints: bps,
+		rule:       rule,
+		scope:      scope,
+	}
+}
diff --git a/backend/test/e2e/remote/python_plugin_test.go b/backend/test/e2e/remote/python_plugin_test.go
index 08369edb1..8dfd235b8 100644
--- a/backend/test/e2e/remote/python_plugin_test.go
+++ b/backend/test/e2e/remote/python_plugin_test.go
@@ -122,51 +122,34 @@ func TestRunPipeline(t *testing.T) {
 	require.Equal(t, "", pipeline.ErrorName)
 }
 
-func TestBlueprintV200(t *testing.T) {
+func TestBlueprintV200_withScopeDeletion(t *testing.T) {
 	client := CreateClient(t)
-	connection := CreateTestConnection(client)
-	projectName := "Test project"
-	client.CreateProject(&helper.ProjectConfig{
-		ProjectName: projectName,
-	})
-	rule := CreateTestTransformationRule(client, connection.ID)
-	scope := CreateTestScope(client, rule, connection.ID)
-
-	blueprint := client.CreateBasicBlueprintV2(
-		"Test blueprint",
-		&helper.BlueprintV2Config{
-			Connection: &plugin.BlueprintConnectionV200{
-				Plugin:       "fake",
-				ConnectionId: connection.ID,
-				Scopes: []*plugin.BlueprintScopeV200{
-					{
-						Id:   scope.Id,
-						Name: "Test scope",
-						Entities: []string{
-							plugin.DOMAIN_TYPE_CICD,
-						},
-					},
-				},
-			},
-			SkipOnFail:  true,
-			ProjectName: projectName,
-		},
-	)
-
-	plan, err := blueprint.UnmarshalPlan()
-	require.NoError(t, err)
-	_ = plan
-
-	project := client.GetProject(projectName)
-	require.Equal(t, blueprint.Name, project.Blueprint.Name)
-	client.TriggerBlueprint(blueprint.ID)
-	scopesResponse := client.ListScopes(PLUGIN_NAME, connection.ID, true)
+	params := CreateTestBlueprints(t, client, 1)
+	client.TriggerBlueprint(params.blueprints[0].ID)
+	scopesResponse := client.ListScopes(PLUGIN_NAME, params.connection.ID, true)
 	require.Equal(t, 1, len(scopesResponse))
 	require.Equal(t, 1, len(scopesResponse[0].Blueprints))
-	bps := client.DeleteScope(PLUGIN_NAME, connection.ID, scope.Id, false)
+	bps := client.DeleteScope(PLUGIN_NAME, params.connection.ID, params.scope.Id, false)
 	require.Equal(t, 1, len(bps))
-	scopesResponse = client.ListScopes(PLUGIN_NAME, connection.ID, true)
+	scopesResponse = client.ListScopes(PLUGIN_NAME, params.connection.ID, true)
 	require.Equal(t, 0, len(scopesResponse))
+	bpsResult := client.ListBlueprints()
+	require.Equal(t, 1, len(bpsResult.Blueprints))
+}
+
+func TestBlueprintV200_withBlueprintDeletion(t *testing.T) {
+	client := CreateClient(t)
+	params := CreateTestBlueprints(t, client, 2)
+	client.TriggerBlueprint(params.blueprints[0].ID)
+	scopesResponse := client.ListScopes(PLUGIN_NAME, params.connection.ID, true)
+	require.Equal(t, 1, len(scopesResponse))
+	require.Equal(t, 2, len(scopesResponse[0].Blueprints))
+	client.DeleteBlueprint(params.blueprints[0].ID)
+	scopesResponse = client.ListScopes(PLUGIN_NAME, params.connection.ID, true)
+	require.Equal(t, 1, len(scopesResponse)) //scopes are NOT cascade-deleted when bp is deleted
+	bpsList := client.ListBlueprints()
+	require.Equal(t, 1, len(bpsList.Blueprints))
+	require.Equal(t, params.blueprints[1].ID, bpsList.Blueprints[0].ID)
 }
 
 func TestCreateTxRule(t *testing.T) {
diff --git a/backend/test/helper/api.go b/backend/test/helper/api.go
index ed6d5c0e4..7765c95a1 100644
--- a/backend/test/helper/api.go
+++ b/backend/test/helper/api.go
@@ -101,7 +101,14 @@ func (d *DevlakeClient) GetBlueprint(blueprintId uint64) models.Blueprint {
 	return sendHttpRequest[models.Blueprint](d.testCtx, d.timeout, debugInfo{
 		print:      true,
 		inlineJson: false,
-	}, http.MethodGet, fmt.Sprintf("%s/blueprint/%d", d.Endpoint, blueprintId), nil, nil)
+	}, http.MethodGet, fmt.Sprintf("%s/blueprints/%d", d.Endpoint, blueprintId), nil, nil)
+}
+
+func (d *DevlakeClient) DeleteBlueprint(blueprintId uint64) {
+	sendHttpRequest[any](d.testCtx, d.timeout, debugInfo{
+		print:      true,
+		inlineJson: false,
+	}, http.MethodDelete, fmt.Sprintf("%s/blueprints/%d", d.Endpoint, blueprintId), nil, nil)
 }
 
 func (d *DevlakeClient) CreateProject(project *ProjectConfig) models.ApiOutputProject {