Skip to content

Repository files navigation

rwdb

Build StatusGoDocCoverage StatusGo Report Card

Database wrapper that manage read write connections

Install

go get github.com/andizzle/rwdb

Create connections

package main
import"github.com/andizzle/rwdb"varconns= []string{
"tcp://user:pass@write/dbname",
"tcp://user:pass@read1/dbname",
"tcp://user:pass@read2/dbname",
"tcp://user:pass@read3/dbname",
}
// unable to open write will cause an errordb, err:=rwdb.Open("driver", conns...)

Rotation read and Sticky read

Query a database rotate the use of database connections

Basic usage

db, err:=rwdb.Open("driver", conns...)
// Use the first connectiondb.QueryContext(ctx)
// Use the next connectiondb.QueryContext(ctx)

Execute a statement will cause all subsequent queries to use the write connection (sticky connection). This is to allow the immediate reading of records that have been written to the database during the current request cycle.

db, err:=rwdb.Open("driver", conns...)
// Use the next connectiondb.QueryContext(ctx)
// Use the write conenctiondb.ExecContext(ctx)
// Use the write connectiondb.Query()

Sticky can be turned off

db.SetSticky(false)

A more practical example

The db is marked as modified if there's a successful Write to the databse, which turns on the sticky logic. However, the real world usecase would require modified value to be reset on each request session.

Here's what we can do:

db, err:=rwdb.Open("driver", conns...)
funcRecordUserLogin() {
d:=db.New() // This will make sure the following read are not affected by // other sessions' write actiond.Query("SELECT * from `users` where id = ?")
...d.Exec("UPDATE `users` set last_login_at = now();")
d.Query(...) // Connection is set to the writer
}

License

License

About

Database wrapper that manage read write connections

Resources

Stars

21 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages