database

package module
v0.0.0-...-598706a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 6, 2024 License: Apache-2.0 Imports: 6 Imported by: 0

README

Database Package

Version License

This package provides functionality for creating and managing database connections using GORM (Go Object Relational Mapper).

Features

  • PostgreSQL Implementation: Implements an interface for PostgreSQL database connections using GORM.
  • Connection Pool Management: Methods to set maximum and minimum connection pools.
  • Custom Logging: Customizable logging setup, including debug mode for detailed query and transaction logs.

Installation

go get github.com/dexterdmonkey/go-database

Usage

Initialize PostgreSQL Database
package main

import (
	"fmt"
	"time"

	"github.com/dexterdmonkey/go-database"
)

func main() {
	cfg := &database.Config{
		Host:              "localhost",
		Port:              5432,
		User:              "username",
		Pass:              "password",
		Name:              "dbname",
		MaxConnectionPool: 20,
		MinConnectionPool: 5,
		Timezone:          "Asia/Jakarta",
	}

	db, err := database.CreatePostgreSQL(cfg)
	if err != nil {
		fmt.Println("Error creating PostgreSQL connection:", err)
		return
	}

	defer db.Close()

	// Use the database connection...
}
Set Connection Pool Limits
// Set maximum connection pool limit
err := db.SetMaxConnectionPool(20)
if err != nil {
	fmt.Println("Error setting max connection pool:", err)
}

// Set minimum connection pool
err = db.SetMinConnectionPool(5)
if err != nil {
	fmt.Println("Error setting min connection pool:", err)
}
Enable Debug Mode
// Enable debug mode for detailed logging
db.DebugMode()

// Execute queries or transactions...

API Reference

CreatePostgreSQL(cfg *Config) (*PostgreSQL, error)

Creates a new PostgreSQL database connection.

  • cfg: Configuration parameters including database credentials and connection settings.
SetMaxConnectionPool(n int) error

Sets the maximum number of open connections to the database.

  • n: Maximum number of open connections. Set to 0 or a negative value for unlimited connections.
SetMinConnectionPool(n int) error

Sets the minimum number of idle connections to the database.

  • n: Minimum number of idle connections. Set to 0 or a negative value to disable idle connections.
SetLogger(writer logger.Writer)

Sets a custom logger for the database.

  • writer: Custom logger writer implementing the gorm.io/gorm/logger.Writer interface.
DebugMode()

Enables debug mode for detailed logging of SQL queries and transactions.

  • Enables detailed logging including SQL statements, execution time, and affected rows.

License

This package is licensed under the Apache License 2.0. See the LICENSE file for details.

Author

Written by dexterdmonkey.

Feel free to customize and expand the README further based on additional features, examples, or specific usage scenarios of your package.

Documentation

Overview

Package database provides a custom logger implementation for GORM, a popular ORM library for Go. This logger allows customization of logger messages and formatting, including support for colorful output.

Version: 0.0.1 License: Apache License 2.0

Author: dexterdmonkey

This package includes a custom logger that integrates with GORM's logging interface to provide customizable logging behavior for database operations. It supports different log levels and formatting options, including colorful output for enhanced readability.

Example usage:

// Initialize a new logger with custom configurations
logger := NewLogger(os.Stdout, logger.Config{
    Colorful: true,
    LogLevel: logger.Info,
})

// Integrate the logger with a GORM database instance
db := &PostgreSQL{
    DB: gormDB,
    DatabaseLogger: logger,
}

// Use the database instance with integrated logger for database operations

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewLogger

func NewLogger(writer logger.Writer, config logger.Config) *dbLogger

NewLogger creates a new instance of the custom database logger with the given writer and configuration.

Types

type Config

type Config struct {
	Host              string // Database host address.
	Port              int    // Database port number.
	User              string // Database user name.
	Pass              string // Database password.
	Name              string // Database name.
	MaxConnectionPool int    // Maximum size of the connection pool. Set to <= 0 for unlimited connections. Default is 0.
	MinConnectionPool int    // Minimum size of the connection pool. Set to <= 0 for no connection pooling. Default is 0.
	Timezone          string // Timezone of the database server. Default is "Asia/Jakarta".
}

Config holds configuration parameters for connecting to a database.

func (Config) DSN

func (cfg Config) DSN() string

DSN returns the Data Source Name (DSN) string used for connecting to the database.

func (Config) String

func (cfg Config) String() string

String returns a formatted string representation of the Config, including connection details and pool settings.

type PostgreSQL

type PostgreSQL struct {
	*gorm.DB
	// contains filtered or unexported fields
}

PostgreSQL implements the Interface for a PostgreSQL database using GORM.

func CreatePostgreSQL

func CreatePostgreSQL(cfg *Config) (*PostgreSQL, error)

CreatePostgreSQL initializes a new PostgreSQL database connection using the provided configuration.

func (*PostgreSQL) DebugMode

func (db *PostgreSQL) DebugMode()

DebugMode sets the logger to debug mode for detailed logging of SQL queries and transactions. When enabled, the logger will output detailed information for each SQL query or transaction executed. This includes logging SQL statements, execution time, and number of affected rows.

Example:

db := database.New(...)
db.DebugMode()

Notes:

  • Debug mode should be used primarily for development and debugging purposes.
  • Enabling debug mode may impact performance due to increased logging overhead.

func (PostgreSQL) Error

func (l PostgreSQL) Error(ctx context.Context, msg string, data ...interface{})

Error logs an error level message with optional data.

func (PostgreSQL) Info

func (l PostgreSQL) Info(ctx context.Context, msg string, data ...interface{})

Info logs an info level message with optional data.

func (PostgreSQL) LogMode

func (l PostgreSQL) LogMode(level logger.LogLevel) logger.Interface

LogMode sets the logger's log level and returns a new logger instance with the updated settings.

func (PostgreSQL) ParamsFilter

func (l PostgreSQL) ParamsFilter(ctx context.Context, sql string, params ...interface{}) (string, []interface{})

ParamsFilter filters sensitive parameters from SQL statements if ParameterizedQueries is enabled.

func (*PostgreSQL) SetLogger

func (db *PostgreSQL) SetLogger(writer logger.Writer)

SetLogger sets a custom logger for the database.

func (*PostgreSQL) SetMaxConnectionPool

func (db *PostgreSQL) SetMaxConnectionPool(n int) error

SetMaxConnectionPool sets the maximum number of open connections to the database. It configures the PostgreSQL database connection to allow up to 'n' concurrent open connections.

Parameters:

n (int): Maximum number of open connections. Set to 0 or a negative value for unlimited connections.

Returns:

error: An error if setting the maximum open connections fails.

Example:

db := database.New(...)
err := db.SetMaxConnectionPool(20)
if err != nil {
    fmt.Println("Error setting max connection pool:", err)
}

func (*PostgreSQL) SetMinConnectionPool

func (db *PostgreSQL) SetMinConnectionPool(n int) error

SetMinConnectionPool sets the minimum number of idle connections to the database. It configures the PostgreSQL database connection to maintain at least 'n' idle connections when available.

Parameters:

n (int): Minimum number of idle connections. Set to 0 or a negative value to disable idle connections.

Returns:

error: An error if setting the minimum idle connections fails.

Example:

db := database.New(...)
err := db.SetMinConnectionPool(5)
if err != nil {
    fmt.Println("Error setting min connection pool:", err)
}

func (PostgreSQL) Trace

func (l PostgreSQL) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)

Trace logs detailed information about a database operation, including its duration and parameters.

func (PostgreSQL) Warn

func (l PostgreSQL) Warn(ctx context.Context, msg string, data ...interface{})

Warn logs a warning level message with optional data.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL