DBYOC is a Go module that simplifies database connections by providing a unified interface for both SQL and NoSQL databases. This module comes with flexible configuration, automatic retry mechanisms, connection pooling, migration support, logging, and metrics tracking.
- One-Line Setup: Connect with just environment variable
- Unified Interface: Consistent interface for various database types
- Flexible Configuration: Load configuration from environment variables, JSON, or YAML
- Auto Retry & Reconnect: Handle transient errors with automatic retry logic
- Connection Pooling: Efficient database connection management
- Built-in Migration: Manage database schema changes easily
- Integrated Logging: Automatic logging for queries and errors using Logrus
- Metrics Tracking: Monitor connection and query performance
go get github.com/yoockh/dbyocexport MONGO_URI="mongodb://localhost:27017/mydb"package main
import (
"context"
"log"
"github.com/yoockh/dbyoc/config"
"github.com/yoockh/dbyoc/db/nosql"
"github.com/yoockh/dbyoc/logger"
"go.mongodb.org/mongo-driver/bson"
)
func main() {
// Load config from MONGO_URI
cfg, err := nosql.QuickMongo()
if err != nil {
log.Fatal(err)
}
// Validate config
if err := cfg.Validate(); err != nil {
log.Fatal("Config validation error:", err)
}
// Initialize logger
logger.Init(cfg.Logger.Level)
// Connect with database and collection names
client, err := nosql.NewMongoDBClient(cfg.MongoDB.URI, "planetsdb", "planet")
if err != nil {
log.Fatal("Failed to connect to db:", err)
}
defer client.Close()
// Insert
client.Insert(bson.M{"name": "Earth", "type": "Terrestrial"})
// Find
cursor, _ := client.Find(bson.M{})
defer cursor.Close(context.Background())
for cursor.Next(context.Background()) {
var result bson.M
cursor.Decode(&result)
log.Printf("Planet: %+v", result)
}
}export DATABASE_URL="postgres://user:pass@localhost:5432/mydb?sslmode=disable"package main
import (
"log"
"github.com/yoockh/dbyoc/db/sql"
)
func main() {
// ONE LINE!
db, err := sql.QuickPostgres()
if err != nil {
log.Fatal(err)
}
defer db.Close()
rows, _ := db.Query("SELECT id, name FROM users")
defer rows.Close()
for rows.Next() {
var id int
var name string
rows.Scan(&id, &name)
log.Printf("User: %d - %s", id, name)
}
}export REDIS_URL="redis://:password@localhost:6379/0"package main
import (
"context"
"log"
"time"
"github.com/yoockh/dbyoc/db/nosql"
)
func main() {
// ONE LINE!
redis, err := nosql.QuickRedis()
if err != nil {
log.Fatal(err)
}
defer redis.Close()
ctx := context.Background()
redis.Set(ctx, "key", "value", 5*time.Minute)
val, _ := redis.Get(ctx, "key")
log.Printf("Value: %s", val)
}# MongoDB
export MONGO_URI="mongodb://localhost:27017/mydb"
# PostgreSQL
export DATABASE_URL="postgres://user:pass@localhost:5432/mydb"
# Redis
export REDIS_URL="redis://:password@localhost:6379/0"# MongoDB
export MONGO_DATABASE="mydb"
export MONGO_TIMEOUT=30
# PostgreSQL
export DATABASE_MAX_RETRIES=3
export DATABASE_MAX_POOL_SIZE=10
# Redis
export REDIS_PASSWORD="secret"
export REDIS_DB=0If you need more control, use config file:
database:
url: "postgres://user:pass@localhost:5432/mydb"
max_pool_size: 10
mongodb:
uri: mongodb://localhost:27017
database: mydb
redis:
url: "redis://:password@localhost:6379/0"cfg, err := config.LoadConfig()dbyoc/
├── config/ # Configuration management
├── db/
│ ├── sql/ # PostgreSQL, MySQL
│ └── nosql/ # MongoDB, Redis
├── migration/ # Database migrations
├── logger/ # Logging
├── metrics/ # Metrics tracking
└── utils/ # Utilities
| Library | Purpose | Repository |
|---|---|---|
| Logrus | Structured logging | github.com/sirupsen/logrus |
| Viper | Configuration management | github.com/spf13/viper |
| Mapstructure | Map to struct conversion | github.com/mitchellh/mapstructure |
| PostgreSQL Driver | PostgreSQL connectivity | github.com/lib/pq |
| MySQL Driver | MySQL connectivity | github.com/go-sql-driver/mysql |
| MongoDB Driver | MongoDB connectivity | go.mongodb.org/mongo-driver |
| Redis Client | Redis connectivity | github.com/go-redis/redis |
- Added Quick Start helpers:
QuickMongo(),QuickPostgres(),QuickRedis() - MongoDB works with just
MONGO_URIenvironment variable - PostgreSQL works with just
DATABASE_URLenvironment variable - Redis works with just
REDIS_URLenvironment variable - No complex configuration needed for basic usage
- Backward compatible with existing configuration methods
- Fixed module import resolution issues
- Improved graceful shutdown flow
- Corrected timeout handling
Contributions are welcome. To contribute:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Distributed under the MIT License. See LICENSE for more information.
Aisiya Qutwatunnada
Note: DBYOC is designed to simplify database connections. Just set one environment variable and you're ready to go.
