pginit

package module
v1.1.5 Latest Latest
Warning

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

Go to latest
Published: May 31, 2023 License: MIT Imports: 13 Imported by: 1

README

pginit

import "github.com/induzo/gocom/database/pginit"

This package allows you to init a connection pool to postgres database via pgx below are default value in pginit:

default MaxConns = 25

default MaxIdleConns = 25

default MaxLifeTime = 5 minute

default LogLevel = Warn

Index

func ConnPoolHealthCheck

func ConnPoolHealthCheck(pool *pgxpool.Pool) func(ctx context.Context) error

ConnPoolHealthCheck returns a health check function for pgxpool.Pool that can be used in health endpoint.

Example

Using standard net/http package. We can also simply pass healthCheck as a CheckFn in gocom/http/health/v2.

package main

import (
	"context"
	"log"
	"net/http"
	"time"

	"github.com/induzo/gocom/database/pginit"
)

func main() {
	pgi, err := pginit.New(&pginit.Config{
		Host:         "localhost",
		Port:         "5432",
		User:         "postgres",
		Password:     "postgres",
		Database:     "datawarehouse",
		MaxConns:     10,
		MaxIdleConns: 10,
		MaxLifeTime:  1 * time.Minute,
	})
	if err != nil {
		log.Fatalf("init pgi config: %v", err)
	}

	ctx := context.Background()

	pool, err := pgi.ConnPool(ctx)
	if err != nil {
		log.Fatalf("init pgi config: %v", err)
	}

	defer pool.Close()

	healthCheck := pginit.ConnPoolHealthCheck(pool)

	mux := http.NewServeMux()

	mux.HandleFunc("/sys/health", func(rw http.ResponseWriter, req *http.Request) {
		if err := healthCheck(ctx); err != nil {
			rw.WriteHeader(http.StatusServiceUnavailable)
		}
	})
}

func StdConnHealthCheck

func StdConnHealthCheck(conn *sql.DB) func(ctx context.Context) error

StdConnHealthCheck returns a health check function for sql.DB that can be used in health endpoint.

type Config

Config allow you to set database credential to connect to database

type Config struct {
    User         string
    Password     string
    Host         string
    Port         string
    Database     string
    MaxConns     int32
    MaxIdleConns int32
    MaxLifeTime  time.Duration
}

type Option

Option configures PGInit behaviour.

type Option func(*PGInit)
func WithDecimalType
func WithDecimalType() Option

WithDecimalType set pgx decimal type to shopspring/decimal.

func WithLogger
func WithLogger(logger *slog.Logger, _ string) Option

WithLogger Add logger to pgx. if the request context contains request id, can pass in the request id context key to reqIDKeyFromCtx and logger will log with the request id.

func WithUUIDType
func WithUUIDType() Option

WithUUIDType set pgx uuid type to gofrs/uuid.

type PGInit

PGInit provides capabilities for connect to postgres with pgx.pool.

type PGInit struct {
    // contains filtered or unexported fields
}
func New
func New(conf *Config, opts ...Option) (*PGInit, error)

New initializes a PGInit using the provided Config and options. If opts is not provided it will initializes PGInit with default configuration.

func (*PGInit) ConnPool
func (pgi *PGInit) ConnPool(ctx context.Context) (*pgxpool.Pool, error)

ConnPool initiates connection to database and return a pgxpool.Pool.

Example

package main

import (
	"context"
	"log"
	"time"

	"github.com/induzo/gocom/database/pginit"
)

func main() {
	pgi, err := pginit.New(&pginit.Config{
		Host:         "localhost",
		Port:         "5432",
		User:         "postgres",
		Password:     "postgres",
		Database:     "datawarehouse",
		MaxConns:     10,
		MaxIdleConns: 10,
		MaxLifeTime:  1 * time.Minute,
	})
	if err != nil {
		log.Fatalf("init pgi config: %v", err)
	}

	ctx := context.Background()

	pool, err := pgi.ConnPool(ctx)
	if err != nil {
		log.Fatalf("init pgi config: %v", err)
	}

	defer pool.Close()

	if err := pool.Ping(ctx); err != nil {
		log.Fatalf("ping: %v", err)
	}
}

Example (Withlogger)

package main

import (
	"context"
	"io"
	"log"
	"time"

	"golang.org/x/exp/slog"

	"github.com/induzo/gocom/database/pginit"
)

func main() {
	textHandler := slog.NewTextHandler(io.Discard, nil)
	logger := slog.New(textHandler)

	pgi, err := pginit.New(
		&pginit.Config{
			Host:         "localhost",
			Port:         "5432",
			User:         "postgres",
			Password:     "postgres",
			Database:     "datawarehouse",
			MaxConns:     10,
			MaxIdleConns: 10,
			MaxLifeTime:  1 * time.Minute,
		},
		pginit.WithLogger(logger, "request-id"),
		pginit.WithDecimalType(),
		pginit.WithUUIDType(),
	)
	if err != nil {
		log.Fatalf("init pgi config: %v", err)
	}

	ctx := context.Background()

	pool, err := pgi.ConnPool(ctx)
	if err != nil {
		log.Fatalf("init pgi config: %v", err)
	}

	defer pool.Close()

	if err := pool.Ping(ctx); err != nil {
		log.Fatalf("ping: %v", err)
	}
}

Generated by gomarkdoc

Documentation

Overview

This package allows you to init a connection pool to postgres database via pgx below are default value in pginit:

default MaxConns = 25

default MaxIdleConns = 25

default MaxLifeTime = 5 minute

default LogLevel = Warn

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConnPoolHealthCheck

func ConnPoolHealthCheck(pool *pgxpool.Pool) func(ctx context.Context) error

ConnPoolHealthCheck returns a health check function for pgxpool.Pool that can be used in health endpoint.

Example

Using standard net/http package. We can also simply pass healthCheck as a CheckFn in gocom/http/health/v2.

package main

import (
	"context"
	"log"
	"net/http"
	"time"

	"github.com/induzo/gocom/database/pginit"
)

func main() {
	pgi, err := pginit.New(&pginit.Config{
		Host:         "localhost",
		Port:         "5432",
		User:         "postgres",
		Password:     "postgres",
		Database:     "datawarehouse",
		MaxConns:     10,
		MaxIdleConns: 10,
		MaxLifeTime:  1 * time.Minute,
	})
	if err != nil {
		log.Fatalf("init pgi config: %v", err)
	}

	ctx := context.Background()

	pool, err := pgi.ConnPool(ctx)
	if err != nil {
		log.Fatalf("init pgi config: %v", err)
	}

	defer pool.Close()

	healthCheck := pginit.ConnPoolHealthCheck(pool)

	mux := http.NewServeMux()

	mux.HandleFunc("/sys/health", func(rw http.ResponseWriter, req *http.Request) {
		if err := healthCheck(ctx); err != nil {
			rw.WriteHeader(http.StatusServiceUnavailable)
		}
	})
}
Output:

func StdConnHealthCheck

func StdConnHealthCheck(conn *sql.DB) func(ctx context.Context) error

StdConnHealthCheck returns a health check function for sql.DB that can be used in health endpoint.

Types

type Config

type Config struct {
	User         string
	Password     string
	Host         string
	Port         string
	Database     string
	MaxConns     int32
	MaxIdleConns int32
	MaxLifeTime  time.Duration
}

Config allow you to set database credential to connect to database

type Option

type Option func(*PGInit)

Option configures PGInit behaviour.

func WithDecimalType

func WithDecimalType() Option

WithDecimalType set pgx decimal type to shopspring/decimal.

func WithLogger

func WithLogger(logger *slog.Logger, _ string) Option

WithLogger Add logger to pgx. if the request context contains request id, can pass in the request id context key to reqIDKeyFromCtx and logger will log with the request id.

func WithUUIDType

func WithUUIDType() Option

WithUUIDType set pgx uuid type to gofrs/uuid.

type PGInit

type PGInit struct {
	// contains filtered or unexported fields
}

PGInit provides capabilities for connect to postgres with pgx.pool.

func New

func New(conf *Config, opts ...Option) (*PGInit, error)

New initializes a PGInit using the provided Config and options. If opts is not provided it will initializes PGInit with default configuration.

func (*PGInit) ConnPool

func (pgi *PGInit) ConnPool(ctx context.Context) (*pgxpool.Pool, error)

ConnPool initiates connection to database and return a pgxpool.Pool.

Example
package main

import (
	"context"
	"log"
	"time"

	"github.com/induzo/gocom/database/pginit"
)

func main() {
	pgi, err := pginit.New(&pginit.Config{
		Host:         "localhost",
		Port:         "5432",
		User:         "postgres",
		Password:     "postgres",
		Database:     "datawarehouse",
		MaxConns:     10,
		MaxIdleConns: 10,
		MaxLifeTime:  1 * time.Minute,
	})
	if err != nil {
		log.Fatalf("init pgi config: %v", err)
	}

	ctx := context.Background()

	pool, err := pgi.ConnPool(ctx)
	if err != nil {
		log.Fatalf("init pgi config: %v", err)
	}

	defer pool.Close()

	if err := pool.Ping(ctx); err != nil {
		log.Fatalf("ping: %v", err)
	}
}
Output:

Example (Withlogger)
package main

import (
	"context"
	"io"
	"log"
	"time"

	"golang.org/x/exp/slog"

	"github.com/induzo/gocom/database/pginit"
)

func main() {
	textHandler := slog.NewTextHandler(io.Discard, nil)
	logger := slog.New(textHandler)

	pgi, err := pginit.New(
		&pginit.Config{
			Host:         "localhost",
			Port:         "5432",
			User:         "postgres",
			Password:     "postgres",
			Database:     "datawarehouse",
			MaxConns:     10,
			MaxIdleConns: 10,
			MaxLifeTime:  1 * time.Minute,
		},
		pginit.WithLogger(logger, "request-id"),
		pginit.WithDecimalType(),
		pginit.WithUUIDType(),
	)
	if err != nil {
		log.Fatalf("init pgi config: %v", err)
	}

	ctx := context.Background()

	pool, err := pgi.ConnPool(ctx)
	if err != nil {
		log.Fatalf("init pgi config: %v", err)
	}

	defer pool.Close()

	if err := pool.Ping(ctx); err != nil {
		log.Fatalf("ping: %v", err)
	}
}
Output:

Jump to

Keyboard shortcuts

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