github.com/munnerz/test-infra@v0.0.0-20190108210205-ce3d181dc989/velodrome/sql/mysql.go (about)

     1  /*
     2  Copyright 2016 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package sql
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"github.com/jinzhu/gorm"
    23  	"github.com/spf13/cobra"
    24  )
    25  
    26  // MySQLConfig is specific to this database
    27  type MySQLConfig struct {
    28  	Host     string
    29  	Port     int
    30  	Db       string
    31  	User     string
    32  	Password string
    33  }
    34  
    35  func (config *MySQLConfig) getDSN(db string) string {
    36  	var password string
    37  	if config.Password != "" {
    38  		password = ":" + config.Password
    39  	}
    40  
    41  	return fmt.Sprintf("%v%v@tcp(%v:%d)/%s?parseTime=True",
    42  		config.User,
    43  		password,
    44  		config.Host,
    45  		config.Port,
    46  		db)
    47  }
    48  
    49  // CreateDatabase for the MySQLConfig
    50  func (config *MySQLConfig) CreateDatabase() (*gorm.DB, error) {
    51  	db, err := gorm.Open("mysql", config.getDSN(""))
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  
    56  	db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %v;", config.Db))
    57  	db.Close()
    58  
    59  	db, err = gorm.Open("mysql", config.getDSN(config.Db))
    60  	err = db.AutoMigrate(&Assignee{}, &Issue{}, &IssueEvent{}, &Label{}, &Comment{}).Error
    61  	if err != nil {
    62  		return nil, err
    63  	}
    64  
    65  	return db, nil
    66  }
    67  
    68  // AddFlags parses options for database configuration
    69  func (config *MySQLConfig) AddFlags(cmd *cobra.Command) {
    70  	cmd.PersistentFlags().StringVar(&config.User, "user", "root", "MySql user")
    71  	cmd.PersistentFlags().StringVar(&config.Password, "password", "", "MySql password")
    72  	cmd.PersistentFlags().StringVar(&config.Host, "host", "localhost", "MySql server IP")
    73  	cmd.PersistentFlags().IntVar(&config.Port, "port", 3306, "MySql server port")
    74  	cmd.PersistentFlags().StringVar(&config.Db, "database", "github", "MySql server database name")
    75  }