Skip to content

Instantly share code, notes, and snippets.

View sonus21's full-sized avatar

Sonu Kumar sonus21

View GitHub Profile
@sonus21
sonus21 / order_service.go
Last active April 9, 2023 13:59
Order Service
func doesOrderExist(ctx context.Context, db *sql.DB, req *OrderCreateRequest) (bool, error) {
cntResult := db.QueryRowContext(ctx, "SELECT COUNT(id) from orders WHERE merchant_id=? AND merchant_order_id=?", req.MerchantId, req.MerchantOrderId)
err := cntResult.Err()
if err != nil {
return false, err
}
var count int
err = cntResult.Scan(&count)
if err != nil {
return false, err
@sonus21
sonus21 / utils.go
Last active April 9, 2023 11:02
Database utils
// determineDbName this method is used to determine the actual database name from request method and path
// here more complex logic can be placed like for this path, path regex, header parameters etc
func determineDbName(method, path string, header http.Header) string {
if method == http.MethodGet {
return Secondary
}
// add any other logic
return Primary
}
@sonus21
sonus21 / middlewares.go
Last active April 9, 2023 11:01
Database middleware
// Middleware a middleware that is used in chi to set the database context
func Middleware() func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// identify database name from request
name := dbNameFromRequest(r)
// set db name in the context
ctx := SetDb(r.Context(), name)
// call next handler with database context
next.ServeHTTP(w, r.WithContext(ctx))
@sonus21
sonus21 / db_context.go
Last active April 9, 2023 11:02
Database context
const (
_dbCtxKey = "DBCtx"
)
var (
_dbs map[string]*sql.DB
_defaultDB string
)
// Init initialize the database context internal state
@sonus21
sonus21 / database.go
Last active April 9, 2023 11:56
Database initialiser for mysql
// MySqlConfig this is used to store the different MySQL configuration
type MySqlConfig struct {
Host string
Port int
Database string
Username string
Password string
MaxConnectionRetries int
MaxOpenConnection int
MaxIdleConnection int
@sonus21
sonus21 / consumer.py
Last active April 9, 2023 15:07
db_wrapper usage in consumer.py
from .constants import SECONDARY, PRIMARY
from CoreApp.middlewares import db_wrapper
@db_wrapper(PRIMARY)
def reserve_driver(request):
# logic goes here
pass
@sonus21
sonus21 / middlewares.py
Last active April 9, 2023 15:07
Database Middleware and decorator
from functools import wraps
from .utils import db_from_the_request
from .db_router import set_db_for_router, clear_db_for_router
class DatabaseMiddleware(object):
"""
DatabaseMiddleware sets the db in the thread local context and used
across multiple calls to handle the DB calls.
@sonus21
sonus21 / settings.py
Last active April 9, 2023 15:07
DB Setting
INSTALLED_APPS = [
# ...
"CoreApp"
# ...
]
MIDDLEWARE = [
@sonus21
sonus21 / db_router.py
Last active April 9, 2023 15:07
Django DB Router
import threading
threadLocal = threading.local()
def get_current_db_name():
return getattr(threadLocal, "DB", None)
def set_db_for_router(db):
@sonus21
sonus21 / utils.py
Last active April 9, 2023 11:48
Utils to find the database name based on the http reqeust
def _determine_db_name(method, path):
# If you have multiple read databases, you can use DNS to direct them to one database.
# Alternatively, you can randomly select a database from the list if you prefer not to
# use DNS.
if method in ["GET"]:
return SECONDARY
# in many cases POST method can be read only as well
# and in some cases GET method can be performing CUD operations as well
# in these cases we can add a check on the path
return PRIMARY