Nap
A Go sql.DB wrapper for master-slave topologies
Install / Use
/learn @tsenart/NapREADME
Nap
Nap is a library that abstracts access to master-slave physical SQL servers topologies as a single logical database mimicking the standard sql.DB APIs.
Nap requires Go version 1.8 or greater.
Install
$ go get github.com/tsenart/nap
Usage
package main
import (
"log"
"github.com/tsenart/nap"
_ "github.com/go-sql-driver/mysql" // Any sql.DB works
)
func main() {
// The first DSN is assumed to be the master and all
// other to be slaves
dsns := "tcp://user:password@master/dbname;"
dsns += "tcp://user:password@slave01/dbname;"
dsns += "tcp://user:password@slave02/dbname"
db, err := nap.Open("mysql", dsns)
if err != nil {
log.Fatal(err)
}
if err := db.Ping(); err != nil {
log.Fatalf("Some physical database is unreachable: %s", err)
}
// Read queries are directed to slaves with Query and QueryRow.
// Always use Query or QueryRow for SELECTS
// Load distribution is round-robin only for now.
var count int
err = db.QueryRow("SELECT COUNT(*) FROM sometable").Scan(&count)
if err != nil {
log.Fatal(err)
}
// Write queries are directed to the master with Exec.
// Always use Exec for INSERTS, UPDATES
err = db.Exec("UPDATE sometable SET something = 1")
if err != nil {
log.Fatal(err)
}
// Prepared statements are aggregates. If any of the underlying
// physical databases fails to prepare the statement, the call will
// return an error. On success, if Exec is called, then the
// master is used, if Query or QueryRow are called, then a slave
// is used.
stmt, err := db.Prepare("SELECT * FROM sometable WHERE something = ?")
if err != nil {
log.Fatal(err)
}
// Transactions always use the master
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
// Do something transactional ...
if err = tx.Commit(); err != nil {
log.Fatal(err)
}
// If needed, one can access the master or a slave explicitly.
master, slave := db.Master(), db.Slave()
}
Todo
- Support other slave load balancing algorithms.
License
See LICENSE
Related Skills
feishu-drive
339.5k|
things-mac
339.5kManage Things 3 via the `things` CLI on macOS (add/update projects+todos via URL scheme; read/search/list from the local Things database)
clawhub
339.5kUse the ClawHub CLI to search, install, update, and publish agent skills from clawhub.com
yu-ai-agent
2.0k编程导航 2025 年 AI 开发实战新项目,基于 Spring Boot 3 + Java 21 + Spring AI 构建 AI 恋爱大师应用和 ReAct 模式自主规划智能体YuManus,覆盖 AI 大模型接入、Spring AI 核心特性、Prompt 工程和优化、RAG 检索增强、向量数据库、Tool Calling 工具调用、MCP 模型上下文协议、AI Agent 开发(Manas Java 实现)、Cursor AI 工具等核心知识。用一套教程将程序员必知必会的 AI 技术一网打尽,帮你成为 AI 时代企业的香饽饽,给你的简历和求职大幅增加竞争力。
