コード例 #1
0
// closeDB closes a database
func closeDB(db *dtype.Database) error {
	if db.Active {
		err := db.Executor.Close()
		if err != nil {
			return err
		}
		db.Active = false
	}
	return nil
}
コード例 #2
0
// openDB opens a database and verifies connection by calling ping to it
func openDB(db *dtype.Database) error {
	var dsn string

	// if port is not defined, set defaults
	if isEmpty(db.Port) {
		db.Port = getDefaultPort(db.Driver)
	}

	switch db.Driver {
	case "postgres":
		dsn = fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable",
			db.Username, db.Password, db.Host, db.Port, db.DBName)

	case "mysql":
		dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s",
			db.Username, db.Password, db.Host, db.Port, db.DBName)

	default:
		return fmt.Errorf("SQL Driver %s is not supported", db.Driver)
	}
	err := db.Executor.Open(db.Driver, dsn)
	if err != nil {
		return err
	}

	// ping db to verify a connection
	if err = db.Executor.Ping(); err != nil {
		return err
	}

	if db.SelectDB != "" {
		// switch the connection when SelectDB is defined in cfg
		err = db.Executor.SwitchToDB(db.SelectDB)
		if err != nil {
			return err
		}
	}

	db.Active = true

	return nil
}