Skip to content

Commit

Permalink
Add flag to create db
Browse files Browse the repository at this point in the history
  • Loading branch information
Starttoaster committed May 21, 2024
1 parent 26af35f commit 0e4b4a3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
7 changes: 7 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ var rootCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
// Init db package
err := db.Init(
viper.GetBool("create-db"),
viper.GetString("mysql-host"),
viper.GetString("mysql-database"),
viper.GetString("mysql-user"),
Expand Down Expand Up @@ -149,6 +150,7 @@ func init() {
rootCmd.PersistentFlags().Uint32("records", 0, "The number of records to send (defaults to 0)")
rootCmd.PersistentFlags().Uint32("max-concurrent", 1, "The max number of records to send concurrently (in individual requests.) (defaults to 1)")
rootCmd.PersistentFlags().Bool("reset", false, "This resets the mysqlpunch table at the beginning of a run, deleting all records in it and resetting the ID counter. (defaults to false)")
rootCmd.PersistentFlags().Bool("create-db", false, "When set to true, this will handle creating the database in your mysql server. (defaults to false)")

err := viper.BindPFlag("log-level", rootCmd.PersistentFlags().Lookup("log-level"))
if err != nil {
Expand Down Expand Up @@ -189,4 +191,9 @@ func init() {
if err != nil {
log.Fatalln(err.Error())
}

err = viper.BindPFlag("create-db", rootCmd.PersistentFlags().Lookup("create-db"))
if err != nil {
log.Fatalln(err.Error())
}
}
9 changes: 8 additions & 1 deletion internal/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,21 @@ var db *sql.DB

// Init accepts authentication parameters for a mysql db and creates a client
// This function may also be configured to create tables in the db on behalf of the application for setup purposes.
func Init(host, database, user, passwd string) error {
func Init(createDB bool, host, database, user, passwd string) error {
// Create db client
var err error
db, err = sql.Open("mysql", assembleDataSourceName(host, database, user, passwd))
if err != nil {
return fmt.Errorf("creating database client: %v", err)
}

if createDB {
_, err = db.Exec(`CREATE DATABASE IF NOT EXISTS mysqlpunch;`)
if err != nil {
return fmt.Errorf("creating creating mysqlpunch database (if it didn't exist): %v", err)
}
}

log.Debug("Creating table in mysql db if they don't already exist")

err = initTable()
Expand Down

0 comments on commit 0e4b4a3

Please sign in to comment.