// Create a new database connection with a valid DSN.
489221
func NewHostWithDSN(connectionString string, dbname string) *Host {

	db, err := sql.Open("mysql", connectionString)
	if err != nil {
		log.Fatalln("Could not connect to " + connectionString + "!")
	}
	host := &Host{db, dbname, false}
	if err := host.Ping(); err != nil {
		log.Fatalln("Host does not reply to ping: " + err.Error())
	}
	if err := host.createDatabase(); err != nil {
		log.Fatalln("Could not create database " + host.dbname + ": " + err.Error())
	}
	if err := host.useDatabase(); err != nil {
		panic("Could not use database " + host.dbname + ": " + err.Error())
	}
	return host
}
1315911
func NewDb(db *sql.DB, driverName string) *DB {
	return &DB{DB: db, driverName: driverName, Mapper: mapper()}
}
596392
func NewUserConnection() (*Conn, error) {
	return NewConnection(func() (*dbus.Conn, error) {
		return dbusAuthHelloConnection(dbus.SessionBusPrivate)
	})
}
682553
func newConnection() (*Conn, error) {
	c := new(Conn)
	if err := c.initConnection(); err != nil {
		return nil, err
	}

	return c, nil
}
342585
func New() (interface{}, error) {
	db := new()
	dbType := dbplugin.NewDatabaseErrorSanitizerMiddleware(db, db.secretValues)

	return dbType, nil
}
886143
func New(dsn string) (*Client, error) {
	client := newClient(nil)
	return client, client.SetDSN(dsn)
}
995795
func CreateConnectionDefinition(couchDBAddress, username, password string, maxRetries,
	maxRetriesOnStartup int, requestTimeout time.Duration, createGlobalChangesDB bool) (*CouchConnectionDef, error) {

	logger.Debugf("Entering CreateConnectionDefinition()")

	connectURL := &url.URL{
		Host:   couchDBAddress,
		Scheme: "http",
	}

	//parse the constructed URL to verify no errors
	finalURL, err := url.Parse(connectURL.String())
	if err != nil {
		logger.Errorf("URL parse error: %s", err)
		return nil, errors.Wrapf(err, "error parsing connect URL: %s", connectURL)
	}

	logger.Debugf("Created database configuration  URL=[%s]", finalURL.String())
	logger.Debugf("Exiting CreateConnectionDefinition()")

	//return an object containing the connection information
	return &CouchConnectionDef{finalURL.String(), username, password, maxRetries,
		maxRetriesOnStartup, requestTimeout, createGlobalChangesDB}, nil

}
1150395
func (c *Transport) createConnection() (*Connection, error) {
	conn, err := dial(c.Version, c.hostAddr, c.tlsConfig)
	if err != nil {
		return nil, driver.WithStack(err)
	}

	// Record connection
	c.connMutex.Lock()
	c.connections = append(c.connections, conn)
	startCleanup := len(c.connections) == 1
	c.connMutex.Unlock()

	if startCleanup {
		// TODO enable cleanup
		go c.cleanup()
	}

	return conn, nil
}
803117
func createServerConn(rawaddr []byte, addr string) (remote *ss.Conn, err error) {
	const baseFailCnt = 20
	n := len(servers.srvCipher)
	skipped := make([]int, 0)
	for i := 0; i < n; i++ {
		// skip failed server, but try it with some probability
		if servers.failCnt[i] > 0 && rand.Intn(servers.failCnt[i]+baseFailCnt) != 0 {
			skipped = append(skipped, i)
			continue
		}
		remote, err = connectToServer(i, rawaddr, addr)
		if err == nil {
			return
		}
	}
	// last resort, try skipped servers, not likely to succeed
	for _, i := range skipped {
		remote, err = connectToServer(i, rawaddr, addr)
		if err == nil {
			return
		}
	}
	return nil, err
}
777969
func Open(driverName, dsn string) (*DB, error) {
	sqlDB, err := sql.Open(driverName, dsn)
	if err != nil {
		return nil, err
	}

	return NewFromDB(sqlDB, driverName), nil
}
789058
func (api *DatabaseAPI) New(values *sacloud.CreateDatabaseValue) *sacloud.Database {
	return sacloud.CreateNewDatabase(values)
}
460897
func New(t *testing.T) *DB {
	// Pick a path for our socket.
	socketDir, err := ioutil.TempDir("", "fakesqldb")
	if err != nil {
		t.Fatalf("ioutil.TempDir failed: %v", err)
	}
	socketFile := path.Join(socketDir, "fakesqldb.sock")

	// Create our DB.
	db := &DB{
		t:            t,
		socketFile:   socketFile,
		name:         "fakesqldb",
		data:         make(map[string]*ExpectedResult),
		rejectedData: make(map[string]error),
		queryCalled:  make(map[string]int),
		connections:  make(map[uint32]*mysql.Conn),
	}

	db.Handler = db

	authServer := &mysql.AuthServerNone{}

	// Start listening.
	db.listener, err = mysql.NewListener("unix", socketFile, authServer, db, 0, 0)
	if err != nil {
		t.Fatalf("NewListener failed: %v", err)
	}

	db.acceptWG.Add(1)
	go func() {
		defer db.acceptWG.Done()
		db.listener.Accept()
	}()

	// Return the db.
	return db
}
1320548
func NewDatabase(path string) (Database, error) {
	storage, err := util.NewFileStorage(path)
	if err != nil {
		return nil, err
	}

	return NewDatabaseWithStorage(storage), nil
}
417965
func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
	if _, err := d.getNetwork(id); err == nil {
		return types.ForbiddenErrorf("network %s exists", id)
	}

	genData, ok := option[netlabel.GenericData].(map[string]string)
	if !ok {
		return fmt.Errorf("Unknown generic data option")
	}

	// Parse and validate the config. It should not conflict with existing networks' config
	config, err := d.parseNetworkOptions(id, genData)
	if err != nil {
		return err
	}

	err = config.processIPAM(id, ipV4Data, ipV6Data)
	if err != nil {
		return err
	}

	err = d.createNetwork(config)

	if err != nil {
		return err
	}

	// A non blank hnsid indicates that the network was discovered
	// from HNS. No need to call HNS if this network was discovered
	// from HNS
	if config.HnsID == "" {
		subnets := []hcsshim.Subnet{}

		for _, ipData := range ipV4Data {
			subnet := hcsshim.Subnet{
				AddressPrefix: ipData.Pool.String(),
			}

			if ipData.Gateway != nil {
				subnet.GatewayAddress = ipData.Gateway.IP.String()
			}

			subnets = append(subnets, subnet)
		}

		network := &hcsshim.HNSNetwork{
			Name:               config.Name,
			Type:               d.name,
			Subnets:            subnets,
			DNSServerList:      config.DNSServers,
			DNSSuffix:          config.DNSSuffix,
			MacPools:           config.MacPools,
			SourceMac:          config.SourceMac,
			NetworkAdapterName: config.NetworkAdapterName,
		}

		if config.VLAN != 0 {
			vlanPolicy, err := json.Marshal(hcsshim.VlanPolicy{
				Type: "VLAN",
				VLAN: config.VLAN,
			})

			if err != nil {
				return err
			}
			network.Policies = append(network.Policies, vlanPolicy)
		}

		if config.VSID != 0 {
			vsidPolicy, err := json.Marshal(hcsshim.VsidPolicy{
				Type: "VSID",
				VSID: config.VSID,
			})

			if err != nil {
				return err
			}
			network.Policies = append(network.Policies, vsidPolicy)
		}

		if network.Name == "" {
			network.Name = id
		}

		configurationb, err := json.Marshal(network)
		if err != nil {
			return err
		}

		configuration := string(configurationb)
		logrus.Debugf("HNSNetwork Request =%v Address Space=%v", configuration, subnets)

		hnsresponse, err := hcsshim.HNSNetworkRequest("POST", "", configuration)
		if err != nil {
			return err
		}

		config.HnsID = hnsresponse.Id
		genData[HNSID] = config.HnsID

	} else {
		// Delete any stale HNS endpoints for this network.
		if endpoints, err := hcsshim.HNSListEndpointRequest(); err == nil {
			for _, ep := range endpoints {
				if ep.VirtualNetwork == config.HnsID {
					logrus.Infof("Removing stale HNS endpoint %s", ep.Id)
					_, err = hcsshim.HNSEndpointRequest("DELETE", ep.Id, "")
					if err != nil {
						logrus.Warnf("Error removing HNS endpoint %s", ep.Id)
					}
				}
			}
		} else {
			logrus.Warnf("Error listing HNS endpoints for network %s", config.HnsID)
		}
	}

	n, err := d.getNetwork(id)
	if err != nil {
		return err
	}
	n.created = true
	return d.storeUpdate(config)
}
972231
func New() (*Conn, error) {
	conn, err := NewSystemConnection()
	if err != nil && os.Geteuid() == 0 {
		return NewSystemdConnection()
	}
	return conn, err
}
725413
func NewConn(gw string, crt string, key string) (Conn, error) {
	cert, err := tls.X509KeyPair([]byte(crt), []byte(key))
	if err != nil {
		return Conn{}, err
	}

	return NewConnWithCert(gw, cert), nil
}
684
func NewClient(dsn string) (client *Client, err error) {
	u, err := url.Parse(dsn)
	if err != nil {
		return nil, err
	}

	basePath := path.Dir(u.Path)
	project := path.Base(u.Path)

	if u.User == nil {
		return nil, fmt.Errorf("the DSN must contain a public and secret key")
	}
	publicKey := u.User.Username()
	secretKey, keyIsSet := u.User.Password()
	if !keyIsSet {
		return nil, fmt.Errorf("the DSN must contain a secret key")
	}

	u.Path = basePath

	check := func(req *http.Request, via []*http.Request) error {
		fmt.Printf("%+v", req)
		return nil
	}

	httpConnectTimeout := defaultTimeout
	httpReadWriteTimeout := defaultTimeout
	if st := u.Query().Get("timeout"); st != "" {
		if timeout, err := strconv.Atoi(st); err == nil {
			httpConnectTimeout = time.Duration(timeout) * time.Second
			httpReadWriteTimeout = time.Duration(timeout) * time.Second
		} else {
			return nil, fmt.Errorf("Timeout should have an Integer argument")
		}
	}

	transport := &transport{
		httpTransport: &http.Transport{
			Dial:  timeoutDialer(httpConnectTimeout),
			Proxy: http.ProxyFromEnvironment,
		}, timeout: httpReadWriteTimeout}
	httpClient := &http.Client{
		Transport:     transport,
		CheckRedirect: check,
	}
	return &Client{URL: u, PublicKey: publicKey, SecretKey: secretKey, httpClient: httpClient, Project: project}, nil
}