github.com/Redstoneguy129/cli@v0.0.0-20230211220159-15dca4e91917/internal/db/dump/dump.go (about)

     1  package dump
     2  
     3  import (
     4  	"context"
     5  	_ "embed"
     6  	"errors"
     7  	"fmt"
     8  	"os"
     9  	"strings"
    10  
    11  	"github.com/Redstoneguy129/cli/internal/utils"
    12  	"github.com/spf13/afero"
    13  )
    14  
    15  var (
    16  	//go:embed templates/dump_schema.sh
    17  	dumpSchemaScript string
    18  	//go:embed templates/dump_data.sh
    19  	dumpDataScript string
    20  )
    21  
    22  func Run(ctx context.Context, path, username, password, database, host string, dataOnly bool, fsys afero.Fs) error {
    23  	var script string
    24  	if dataOnly {
    25  		fmt.Fprintln(os.Stderr, "Dumping data from remote database...")
    26  		script = dumpDataScript
    27  	} else {
    28  		fmt.Fprintln(os.Stderr, "Dumping schemas from remote database...")
    29  		script = dumpSchemaScript
    30  	}
    31  	out, err := utils.DockerRunOnce(ctx, utils.Pg15Image, []string{
    32  		"PGHOST=" + host,
    33  		"PGUSER=" + username,
    34  		"PGPASSWORD=" + password,
    35  		"EXCLUDED_SCHEMAS=" + strings.Join(utils.InternalSchemas, "|"),
    36  		"DB_URL=" + database,
    37  	}, []string{"bash", "-c", script})
    38  	if err != nil {
    39  		return errors.New("Error running pg_dump on remote database: " + err.Error())
    40  	}
    41  
    42  	if len(path) > 0 {
    43  		if err := afero.WriteFile(fsys, path, []byte(out), 0644); err != nil {
    44  			return err
    45  		}
    46  		fmt.Fprintln(os.Stderr, "Dumped schema to "+utils.Bold(path)+".")
    47  	} else {
    48  		fmt.Println(out)
    49  	}
    50  
    51  	return nil
    52  }