github.com/fanux/shipyard@v0.0.0-20161009071005-6515ce223235/controller/plugin/manager/cmd/db.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/jinzhu/gorm"
     8  	_ "github.com/jinzhu/gorm/dialects/postgres"
     9  )
    10  
    11  func initDB(host, port, user, dbname, passwd string) *gorm.DB {
    12  	s := fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=disable password=%s",
    13  		host, port, user, dbname, passwd)
    14  	log.Print("db info %s", s)
    15  	db, err := gorm.Open("postgres", s)
    16  
    17  	if err != nil {
    18  		log.Print("error init db", err)
    19  		return nil
    20  	}
    21  
    22  	if !db.HasTable(&Plugin{}) {
    23  		db.CreateTable(&Plugin{})
    24  		db.Set("gorm:table_options", "ENGINE=InnoDB").CreateTable(&Plugin{})
    25  	} else {
    26  		log.Print("plugins table already exist")
    27  	}
    28  
    29  	if !db.HasTable(&Strategy{}) {
    30  		db.CreateTable(&Strategy{})
    31  		db.Set("gorm:table_options", "ENGINE=InnoDB").CreateTable(&Strategy{})
    32  	} else {
    33  		log.Print("strategies table already exist")
    34  	}
    35  	/*
    36  		p := Plugin{Name: "pipeline", Kind: "nil", Status: "enable", Description: "nil", SpecJsonStr: "nil", Manual: "nil"}
    37  
    38  		db.NewRecord(p)
    39  		db.Create(&p)
    40  	*/
    41  
    42  	return db
    43  	//defer db.Close()
    44  }