Categorygithub.com/guregu/db
modulepackage
0.0.0-20221009124521-a68858e20c76
Repository: https://github.com/guregu/db.git
Documentation: pkg.go.dev

# README

Update from 2022

This project was made in the wild west of pre-stdlib context days to explore what was possible. Since then, we've all agreed that putting databases in your context is generally a bad idea. Transactions are arguably OK. Regardless, you probably shouldn't use this.

db GoDoc

import "github.com/guregu/db"

db is a simple helper for using x/net/context with various databases. With db you can give each of your connections a name and shove it in your context. Later you can use that name to retrieve the connection. Feel free to fork this and add your favorite drivers.

Example

First we make a context with our DB connection. Then we use kami to set up a web server and pass that context to every request. From within the request, we retrieve the DB connection and send a query.

package main

import (
	"fmt"
	"net/http"

	"github.com/guregu/db"
	"github.com/guregu/kami"
	"golang.org/x/net/context"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	ctx := context.Background()
	ctx = db.OpenSQL(ctx, "main", "mysql", "root:hunter2@unix(/tmp/mysql.sock)/myCoolDB")
	defer db.Close(ctx) // closes all DB connections
	kami.Context = ctx

	kami.Get("/hello/:name", hello)
	kami.Serve()
}

func hello(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	mainDB := db.SQL(ctx, "main") // *sql.DB
	var greeting string
	mainDB.QueryRow("SELECT content FROM greetings WHERE name = ?", kami.Param(ctx, "name")).Scan(&greeting)
	fmt.Fprint(w, greeting)
}

License

BSD

# Functions

Close closes all connections of all kinds and returns a new context without them.
CloseMongoDB closes the specified Mongo connection, panciking if Close returns an error.
CloseMongoDBAll closes all open Mongo connections and returns a new context without them.
CloseRedis closes the specified Redis connection, panciking if Close returns an error.
CloseRedisAll closes all open Redis connections and returns a new context without them.
CloseSQL closes the specified SQL connection, panciking if Close returns an error.
CloseSQLAll closes all open SQL connections and returns a new context without them.
Mongo retrieves the *mgo.Session with the given name or nil.
OpenFailoverRedis opens a failover Redis connection and returns a new context or panics.
OpenMongoDB opens a Mongo connection and returns a new context or panics.
OpenRedis opens a Redis connection and returns a new context or panics.
OpenSQL opens a SQL connection and returns a new context or panics.
Redis retrieves the *redis.Client with the given name or nil.
SQL retrieves the *sql.DB with the given name or nil.
WithMongoDB returns a new context containing the given *mgo.Session.
WithRedis returns a new context containing the given *redis.Client.
WithSQL returns a new context containing the given *sql.DB.