/* * Copyright 2026 Oleg Borodin */ package main import ( "bytes" "context" "io" "os" "mbase/app/config" "mbase/app/maindb" "mbase/pkg/descr" "mbase/pkg/logger" "github.com/spf13/cobra" "go.yaml.in/yaml/v4" ) func (util *Util) RestoreDatabase(cmd *cobra.Command, args []string) { util.restoreDatabaseParams.Filename = args[0] res, err := util.restoreDatabase(util.restoreDatabaseParams) printResponse(res, err) } type restoreDatabaseParams struct { Filename string DeleteAllRecords bool } type restoreDatabaseResult struct{} func (util *Util) restoreDatabase(params restoreDatabaseParams) (restoreDatabaseResult, error) { var err error res := restoreDatabaseResult{} ctx := context.Background() log := logger.NewLogger("restore") conf := config.NewConfig() err = conf.ReadFile() if err != nil { return res, err } err = conf.ReadEnv() if err != nil { return res, err } db, err := maindb.NewDatabase(conf.DataDir) if err != nil { return res, err } err = db.OpenDatabase() if err != nil { return res, err } file := os.Stdin if params.Filename != "-" { file, err = os.Open(params.Filename) if err != nil { return res, err } defer file.Close() } buffer := bytes.NewBuffer(nil) _, err = io.Copy(buffer, file) if err != nil { return res, err } dump := descr.Dump{} err = yaml.Unmarshal(buffer.Bytes(), &dump) if err != nil { return res, err } if params.DeleteAllRecords { err = db.CleanDatabase(ctx) if err != nil { return res, err } } for _, account := range dump.Accounts { log.Infof("Insert account %s", account.Username) err = db.InsertAccount(ctx, &account) if err != nil { log.Errorf("Insert account error: %v", err) } } for _, grant := range dump.Grants { log.Infof("Insert grant %s for account %d", grant.Operation, grant.AccountID) err = db.InsertGrant(ctx, &grant) if err != nil { log.Errorf("Insert account error: %v", err) } } return res, err }