hasql manages high-availability database clusters by wrapping standard database/sql connection pools.
Workflow:
- Create
*sql.DB objects for each database node. - Use a
NodeDiscoverer to provide these nodes to a Cluster. - Initialize a
Cluster with a NodeChecker (e.g., hasql.PostgreSQLChecker). - Retrieve a suitable node using methods like
Primary() or Node(criterion).
Note: hasql does not configure your connection pools; you must set them up properly. However, hasql manages their lifetime and will close the pools when the Cluster object is closed.
dbFoo, _ := sql.Open("pgx", "host=foo")
dbBar, _ := sql.Open("pgx", "host=bar")
discoverer := NewStaticNodeDiscoverer(
NewNode("foo", dbFoo),
NewNode("bar", dbBar),
)
cl, err := hasql.NewCluster(discoverer, hasql.PostgreSQLChecker)
if err != nil { ... }
node := cl.Primary()
if node == nil {
err := cl.Err() // most recent errors for all nodes in the cluster
}
fmt.Printf("got node %s\n", node)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if err = node.DB().PingContext(ctx); err != nil { ... }