github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/pkg/names/remove.go (about)

     1  package names
     2  
     3  import (
     4  	"fmt"
     5  	"path/filepath"
     6  
     7  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/base"
     8  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/config"
     9  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/file"
    10  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/logger"
    11  	"github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/types"
    12  )
    13  
    14  func RemoveName(dbType DatabaseType, chain string, address base.Address) (name *types.Name, err error) {
    15  	switch dbType {
    16  	case DatabaseCustom:
    17  		return customRemoveName(chain, address)
    18  	case DatabaseRegular:
    19  		// return regularRemoveName(chain, address)
    20  		logger.Fatal("should not happen ==> remove is not supported for regular database")
    21  	default:
    22  		logger.Fatal("should not happen ==> unknown database type")
    23  	}
    24  	return
    25  }
    26  
    27  func customRemoveName(chain string, address base.Address) (*types.Name, error) {
    28  	name, exists := customNames[address]
    29  	if !exists {
    30  		return nil, fmt.Errorf("cannot remove non-existant custom name for address %s", address.Hex())
    31  	}
    32  
    33  	if !name.Deleted {
    34  		return nil, fmt.Errorf("cannot remove non-deleted custom name for address %s", address.Hex())
    35  	}
    36  
    37  	namesPath := getDatabasePath(chain, DatabaseCustom)
    38  	tmpPath := filepath.Join(config.PathToCache(chain), "tmp")
    39  
    40  	// openDatabaseForEdit truncates the file when it opens. We make
    41  	// a backup so we can restore it on an error if we need to.
    42  	backup, err := file.MakeBackup(tmpPath, namesPath)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  
    47  	db, err := openDatabaseForEdit(chain, DatabaseCustom)
    48  	if err != nil {
    49  		// The backup will replace the now truncated file.
    50  		return nil, err
    51  	}
    52  
    53  	defer func() {
    54  		_ = db.Close()
    55  		// If the backup exists, it will replace the now truncated file.
    56  		backup.Restore()
    57  	}()
    58  
    59  	customNamesMutex.Lock()
    60  	defer customNamesMutex.Unlock()
    61  	delete(customNames, address)
    62  	err = writeCustomNames(db)
    63  	if err == nil {
    64  		// Everything went okay, so we can remove the backup.
    65  		backup.Clear()
    66  	}
    67  	return &name, err
    68  }