Quick start
Open a connection, describe a table, and run CRUD.
A complete example — open a Postgres connection, describe a table, and run each CRUD
operation. Prefer MongoDB? Swap the opener for mongo.Open(ctx, uri, dbName). Prefer
DynamoDB? Swap it for dynamodb.Open(ctx). The CRUD calls are identical (all three
satisfy dbswitch.Store) — DynamoDB just needs its primary key column named
"id"; see Backends for the details.
package main
import (
"context"
"log"
"os"
"github.com/anukool23/dbswitch"
"github.com/anukool23/dbswitch/postgres"
)
func main() {
ctx := context.Background()
db, err := postgres.Open(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Describe a table in Go — no CREATE TABLE SQL.
users := dbswitch.Table{
Name: "users",
Columns: []dbswitch.Column{
{Name: "id", Type: dbswitch.TypeUUID, PrimaryKey: true, Default: dbswitch.DefaultGenerateUUID},
{Name: "email", Type: dbswitch.TypeText, NotNull: true, Unique: true},
{Name: "created_at", Type: dbswitch.TypeTimestamp, NotNull: true, Default: dbswitch.DefaultCurrentTime},
},
}
if err := db.CreateTable(ctx, users); err != nil {
log.Fatal(err)
}
// Create.
if err := db.Insert(ctx, "users", map[string]any{"email": "a@b.com"}); err != nil {
log.Fatal(err)
}
// Read one (returns dbswitch.ErrNotFound if nothing matches).
row, err := db.FindOne(ctx, "users", map[string]any{"email": "a@b.com"})
// Read many (nil where = all rows).
rows, err := db.Find(ctx, "users", nil)
// How many active users? Same filter shape as Find/List.
n, err := db.Count(ctx, "users", map[string]any{"email": "a@b.com"})
// Update / Delete return rows-affected. Both refuse an empty condition.
n, err = db.Update(ctx, "users",
map[string]any{"email": "c@d.com"}, // set
map[string]any{"email": "a@b.com"}) // where
n, err = db.Delete(ctx, "users", map[string]any{"email": "c@d.com"})
_ = row
_ = rows
_ = n
}Next: model your schema in detail on Schema, see every CRUD operation, sort/paginate with Listing, and handle errors.