Exemplo n.º 1
0
// ParseURL parses s into a ConnectionURL struct.
func ParseURL(s string) (conn ConnectionURL, err error) {
	var cfg *config

	if cfg, err = parseDSN(s); err != nil {
		return
	}

	conn.User = cfg.user
	conn.Password = cfg.passwd

	if cfg.net == "unix" {
		conn.Address = db.Socket(cfg.addr)
	} else if cfg.net == "tcp" {
		conn.Address = db.ParseAddress(cfg.addr)
	}

	conn.Database = cfg.dbname

	conn.Options = map[string]string{}

	for k, v := range cfg.params {
		conn.Options[k] = v
	}

	return
}
Exemplo n.º 2
0
func TestConnectionURL(t *testing.T) {

	c := ConnectionURL{}

	// Zero value equals to an empty string.
	if c.String() != "" {
		t.Fatal(`Expecting default connectiong string to be empty, got:`, c.String())
	}

	// Adding a database name.
	c.Database = "mydbname"

	if c.String() != "/mydbname?charset=utf8" {
		t.Fatal(`Test failed, got:`, c.String())
	}

	// Adding an option.
	c.Options = map[string]string{
		"charset": "utf8mb4,utf8",
		"sys_var": "esc@ped",
	}

	if c.String() != "/mydbname?charset=utf8mb4%2Cutf8&sys_var=esc%40ped" {
		t.Fatal(`Test failed, got:`, c.String())
	}

	// Setting default options
	c.Options = nil

	// Setting user and password.
	c.User = "******"
	c.Password = "******"

	if c.String() != `user:pass@/mydbname?charset=utf8` {
		t.Fatal(`Test failed, got:`, c.String())
	}

	// Setting host.
	c.Address = db.HostPort("1.2.3.4", 3306)

	if c.String() != `user:pass@tcp(1.2.3.4:3306)/mydbname?charset=utf8` {
		t.Fatal(`Test failed, got:`, c.String())
	}

	// Setting socket.
	c.Address = db.Socket("/path/to/socket")

	if c.String() != `user:pass@unix(/path/to/socket)/mydbname?charset=utf8` {
		t.Fatal(`Test failed, got:`, c.String())
	}

}
Exemplo n.º 3
0
// Attempts to connect to a database using the stored settings.
func (s *source) Open() error {
	var err error

	// Before db.ConnectionURL we used a unified db.Settings struct. This
	// condition checks for that type and provides backwards compatibility.
	if settings, ok := s.connURL.(db.Settings); ok {

		// User is providing a db.Settings struct, let's translate it into a
		// ConnectionURL{}.
		conn := ConnectionURL{
			User:     settings.User,
			Password: settings.Password,
			Database: settings.Database,
			Options: map[string]string{
				"charset": settings.Charset,
			},
		}

		// Connection charset, UTF-8 by default.
		if conn.Options["charset"] == "" {
			conn.Options["charset"] = "utf8"
		}

		if settings.Socket != "" {
			conn.Address = db.Socket(settings.Socket)
		} else {
			if settings.Host == "" {
				settings.Host = "127.0.0.1"
			}
			if settings.Port == 0 {
				settings.Port = defaultPort
			}
			conn.Address = db.HostPort(settings.Host, uint(settings.Port))
		}

		// Replace original s.connURL
		s.connURL = conn
	}

	if s.session, err = sql.Open(`mysql`, s.connURL.String()); err != nil {
		return err
	}

	if err = s.populateSchema(); err != nil {
		return err
	}

	return nil
}