Passed
Push — master ( 0d15c3...61e1d5 )
by Tolga
01:25 queued 14s
created

memory.*TenantWriter.DeleteTenant   B

Complexity

Conditions 7

Size

Total Lines 45
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 29
nop 2
dl 0
loc 45
rs 7.784
c 0
b 0
f 0
1
package memory
2
3
import (
4
	"context"
5
	"errors"
6
	"fmt"
7
	"time"
8
9
	"github.com/Permify/permify/internal/storage"
10
	"github.com/Permify/permify/internal/storage/memory/constants"
11
	db "github.com/Permify/permify/pkg/database/memory"
12
	base "github.com/Permify/permify/pkg/pb/base/v1"
13
)
14
15
// TenantWriter - Structure for Tenant Writer
16
type TenantWriter struct {
17
	database *db.Memory
18
}
19
20
// NewTenantWriter creates a new TenantWriter
21
func NewTenantWriter(database *db.Memory) *TenantWriter {
22
	return &TenantWriter{
23
		database: database,
24
	}
25
}
26
27
// CreateTenant -
28
func (w *TenantWriter) CreateTenant(_ context.Context, id, name string) (result *base.Tenant, err error) {
29
	tenant := storage.Tenant{
30
		ID:        id,
31
		Name:      name,
32
		CreatedAt: time.Now(),
33
	}
34
	txn := w.database.DB.Txn(true)
35
	defer txn.Abort()
36
	if err = txn.Insert(constants.TenantsTable, tenant); err != nil {
37
		return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
38
	}
39
	txn.Commit()
40
	return tenant.ToTenant(), nil
41
}
42
43
// DeleteTenant -
44
func (w *TenantWriter) DeleteTenant(_ context.Context, tenantID string) (result *base.Tenant, err error) {
45
	txn := w.database.DB.Txn(true)
46
	defer txn.Abort()
47
48
	// Define a slice of tables to delete associated records
49
	tables := []string{
50
		constants.AttributesTable,
51
		constants.BundlesTable,
52
		constants.RelationTuplesTable,
53
		constants.SchemaDefinitionsTable,
54
	}
55
56
	// Iterate through each table and delete records associated with the tenant
57
	totalDeleted := 0
58
	for _, table := range tables {
59
		if _, err := txn.First(table, "tenant_id", tenantID); err == nil {
60
			numDeleted, deleteErr := txn.DeleteAll(table, "tenant_id", tenantID)
61
			if deleteErr != nil {
62
				return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
63
			}
64
			totalDeleted += numDeleted
65
		}
66
	}
67
68
	// Retrieve the tenant first
69
	raw, err := txn.First(constants.TenantsTable, "id", tenantID)
70
	if err != nil {
71
		if totalDeleted > 0 {
72
			raw = storage.Tenant{
73
				ID:        tenantID,
74
				Name:      fmt.Sprintf("Affected rows: %d", totalDeleted),
75
				CreatedAt: time.Now(),
76
			}
77
		} else {
78
			return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
79
		}
80
	} else {
81
		// Finally, delete the tenant record
82
		if _, err = txn.DeleteAll(constants.TenantsTable, "id", tenantID); err != nil {
83
			return nil, errors.New(base.ErrorCode_ERROR_CODE_EXECUTION.String())
84
		}
85
	}
86
87
	txn.Commit()
88
	return raw.(storage.Tenant).ToTenant(), nil
89
90
}
91