github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/workload/driver.go (about)

     1  // Copyright 2017 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package workload
    12  
    13  import (
    14  	gosql "database/sql"
    15  	"database/sql/driver"
    16  	"strings"
    17  	"sync/atomic"
    18  
    19  	"github.com/lib/pq"
    20  )
    21  
    22  // cockroachDriver is a wrapper around lib/pq which provides for round-robin
    23  // load balancing amongst a list of URLs. The name passed to Open() is a space
    24  // separated list of "postgres" URLs to connect to.
    25  //
    26  // Note that the round-robin load balancing can lead to imbalances in
    27  // connections across the cluster. This is currently only suitable for
    28  // simplistic setups where nodes in the cluster are stable and do not go up and
    29  // down.
    30  type cockroachDriver struct {
    31  	idx uint32
    32  }
    33  
    34  func (d *cockroachDriver) Open(name string) (driver.Conn, error) {
    35  	urls := strings.Split(name, " ")
    36  	i := atomic.AddUint32(&d.idx, 1) - 1
    37  	return pq.Open(urls[i%uint32(len(urls))])
    38  }
    39  
    40  func init() {
    41  	gosql.Register("cockroach", &cockroachDriver{})
    42  }