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