github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/cmd/hkserver/commands/db.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package commands
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/pkg/errors"
    10  	"github.com/spf13/cobra"
    11  
    12  	"github.com/masterhung0112/hk_server/v5/config"
    13  	"github.com/masterhung0112/hk_server/v5/store/sqlstore"
    14  )
    15  
    16  var DbCmd = &cobra.Command{
    17  	Use:   "db",
    18  	Short: "Commands related to the database",
    19  }
    20  
    21  var InitDbCmd = &cobra.Command{
    22  	Use:   "init",
    23  	Short: "Initialize the database",
    24  	Long: `Initialize the database for a given DSN, executing the migrations and loading the custom defaults if any.
    25  
    26  This command should be run using a database configuration DSN.`,
    27  	Example: `  # you can use the config flag to pass the DSN
    28    $ mattermost db init --config postgres://localhost/mattermost
    29  
    30    # or you can use the MM_CONFIG environment variable
    31    $ MM_CONFIG=postgres://localhost/mattermost mattermost db init
    32  
    33    # and you can set a custom defaults file to be loaded into the database
    34    $ MM_CUSTOM_DEFAULTS_PATH=custom.json MM_CONFIG=postgres://localhost/mattermost mattermost db init`,
    35  	Args: cobra.NoArgs,
    36  	RunE: initDbCmdF,
    37  }
    38  
    39  func init() {
    40  	DbCmd.AddCommand(
    41  		InitDbCmd,
    42  	)
    43  
    44  	RootCmd.AddCommand(
    45  		DbCmd,
    46  	)
    47  }
    48  
    49  func initDbCmdF(command *cobra.Command, _ []string) error {
    50  	dsn := getConfigDSN(command, config.GetEnvironment())
    51  	if !config.IsDatabaseDSN(dsn) {
    52  		return errors.New("this command should be run using a database configuration DSN")
    53  	}
    54  
    55  	customDefaults, err := loadCustomDefaults()
    56  	if err != nil {
    57  		return errors.Wrap(err, "error loading custom configuration defaults")
    58  	}
    59  
    60  	configStore, err := config.NewStoreFromDSN(getConfigDSN(command, config.GetEnvironment()), false, false, customDefaults)
    61  	if err != nil {
    62  		return errors.Wrap(err, "failed to load configuration")
    63  	}
    64  	defer configStore.Close()
    65  
    66  	sqlStore := sqlstore.New(configStore.Get().SqlSettings, nil)
    67  	defer sqlStore.Close()
    68  
    69  	fmt.Println("Database store correctly initialised")
    70  
    71  	return nil
    72  }