postgres

package
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: May 14, 2026 License: GPL-3.0 Imports: 12 Imported by: 0

README

db/postgres

Import path: github.com/InsideGallery/core/db/postgres

Package postgres provides Postgres configuration, sqlx client ownership helpers, and a core-owned SQL operation boundary. New code should prefer Database or DatabaseClient when callers do not need direct access to sqlx.DB.

Main APIs

  • ConnectionConfig configures host, port, user, password, database, application name, and pool settings.
  • GetConnectionConfigFromEnv() reads POSTGRES_* environment variables.
  • DatabaseOptions is a core-owned constructor input that accepts time.Duration for connection lifetime.
  • NewDatabase, NewDatabaseFromOptions, DefaultDatabase, and WrapDatabase create DatabaseClient values.
  • Database is the core-owned interface for ping, exec, query, query-row, and close operations.
  • Statement supplies SQL text and arguments.
  • CommandResult reports rows affected by commands.
  • NewClient, ClientStore, Set, Get, and Default provide legacy sqlx-shaped access.

Usage

package example

import (
	"context"
	"time"

	"github.com/InsideGallery/core/db/postgres"
)

func insertEvent(ctx context.Context) (err error) {
	database, err := postgres.NewDatabaseFromOptions(postgres.DatabaseOptions{
		Host:            "localhost",
		Port:            "5432",
		User:            "app",
		Password:        "secret",
		Database:        "events",
		ApplicationName: "worker",
		MaxOpenConns:    10,
		ConnMaxLifetime: time.Minute,
	})
	if err != nil {
		return err
	}
	defer func() {
		if closeErr := database.Close(); err == nil {
			err = closeErr
		}
	}()

	_, err = database.Exec(ctx, postgres.Statement{
		Query: "insert into events (name) values ($1)",
		Args:  []any{"created"},
	})

	return err
}

Configuration And Operations

Environment variables include POSTGRES_HOST, POSTGRES_PORT, POSTGRES_USER, POSTGRES_PASSWORD, POSTGRES_DB, POSTGRES_APPLICATIONNAME, POSTGRES_MAXOPENCONNS, and POSTGRES_CONNMAXLIFETIME. ConnectionConfig.GetDSN() builds a pgx DSN with sslmode=disable and optional fallback_application_name. NewClient opens a handle and configures the pool; callers should use Ping when they need to verify connectivity and must close rows and clients they create.

Documentation

Overview

Package postgres provides Postgres connection and database helpers.

New code should use explicit construction and core-owned SQL operation types:

import "github.com/InsideGallery/core/db/postgres"

db, err := postgres.NewDatabaseFromOptions(postgres.DatabaseOptions{
	Host: "localhost",
	Database: "app",
})

Prefer Database, DatabaseClient, Statement, DatabaseOptions, and CommandResult when consumer code should not depend directly on sqlx.

Compatibility: NewClient, Set, Get, and Default remain available for existing sqlx-shaped callers. Prefer NewDatabase, NewDatabaseFromOptions, DefaultDatabase, or NewClientStore with explicit lifecycle ownership in new code.

Index

Constants

View Source
const EnvPrefix = "POSTGRES"

EnvPrefix environment prefix for mongodb config

Variables

View Source
var ErrConnectionIsNotSet = errors.New("connection is not set")

Functions

func Default deprecated

func Default() (*sqlx.DB, error)

Default returns the legacy sqlx Postgres client.

Deprecated: use DefaultDatabase for new code.

func Get deprecated

func Get() (*sqlx.DB, error)

Get returns the legacy sqlx Postgres client.

Deprecated: use DefaultDatabase for new code.

func NewClient added in v1.1.0

func NewClient(config *ConnectionConfig) (*sqlx.DB, error)

NewClient creates a legacy sqlx Postgres client from explicit config.

func Set deprecated

func Set(r *sqlx.DB)

Set stores the legacy sqlx Postgres client.

Deprecated: use NewDatabase, DefaultDatabase, and DatabaseClient for new code.

Types

type ClientStore added in v1.1.0

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

ClientStore owns a Postgres sqlx client for explicit application composition.

func NewClientStore added in v1.1.0

func NewClientStore(client *sqlx.DB) *ClientStore

NewClientStore creates a Postgres client store with an optional existing client.

func (*ClientStore) Close added in v1.1.0

func (s *ClientStore) Close() error

Close closes the stored Postgres client and clears this store.

func (*ClientStore) Get added in v1.1.0

func (s *ClientStore) Get() (*sqlx.DB, error)

Get returns the Postgres client from this store.

func (*ClientStore) GetOrCreate added in v1.1.0

func (s *ClientStore) GetOrCreate(config *ConnectionConfig) (*sqlx.DB, error)

GetOrCreate returns or creates a Postgres client from explicit config.

func (*ClientStore) Set added in v1.1.0

func (s *ClientStore) Set(client *sqlx.DB)

Set stores a Postgres client in this store.

type CommandResult added in v1.1.0

type CommandResult struct {
	RowsAffected int64
}

CommandResult is the core-owned result for SQL commands.

type ConnectionConfig

type ConnectionConfig struct {
	Host            string `env:"_HOST" envDefault:"localhost"`
	Port            string `env:"_PORT" envDefault:"5432"`
	User            string `env:"_USER" envDefault:"default"`
	Password        string `env:"_PASSWORD" envDefault:"default"`
	DB              string `env:"_DB" envDefault:"default"`
	ApplicationName string `env:"_APPLICATIONNAME" envDefault:""`
	MaxOpenConns    int    `env:"_MAXOPENCONNS" envDefault:"500"`
	ConnMaxLifetime int64  `env:"_CONNMAXLIFETIME" envDefault:"-1"`
}

ConnectionConfig contains required data for gremlin

func GetConnectionConfigFromEnv

func GetConnectionConfigFromEnv() (*ConnectionConfig, error)

GetConnectionConfigFromEnv return aerospike configs bases on environment variables

func (*ConnectionConfig) GetDSN

func (c *ConnectionConfig) GetDSN() string

type Database added in v1.1.0

type Database interface {
	Ping(ctx context.Context) error
	Exec(ctx context.Context, statement Statement) (CommandResult, error)
	Query(ctx context.Context, statement Statement) (*sql.Rows, error)
	QueryRow(ctx context.Context, statement Statement) *sql.Row
	Close() error
}

Database is the core-owned Postgres contract for new consumers.

type DatabaseClient added in v1.1.0

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

DatabaseClient wraps sqlx behind core-owned operation inputs and results.

func DefaultDatabase added in v1.1.0

func DefaultDatabase() (*DatabaseClient, error)

DefaultDatabase returns the default Postgres client behind the core-owned DatabaseClient API.

func NewDatabase added in v1.1.0

func NewDatabase(config *ConnectionConfig) (*DatabaseClient, error)

NewDatabase creates a Postgres database client from core-owned config.

func NewDatabaseFromOptions added in v1.1.0

func NewDatabaseFromOptions(options DatabaseOptions) (*DatabaseClient, error)

NewDatabaseFromOptions creates a Postgres database client from core-owned construction options.

func WrapDatabase added in v1.1.0

func WrapDatabase(db *sqlx.DB) *DatabaseClient

WrapDatabase adapts an existing sqlx DB to DatabaseClient.

func (*DatabaseClient) Close added in v1.1.0

func (d *DatabaseClient) Close() error

Close closes the database client.

func (*DatabaseClient) Exec added in v1.1.0

func (d *DatabaseClient) Exec(ctx context.Context, statement Statement) (CommandResult, error)

Exec runs a command with core-owned options.

func (*DatabaseClient) Ping added in v1.1.0

func (d *DatabaseClient) Ping(ctx context.Context) error

Ping verifies connectivity.

func (*DatabaseClient) Query added in v1.1.0

func (d *DatabaseClient) Query(ctx context.Context, statement Statement) (*sql.Rows, error)

Query runs a query with core-owned options.

func (*DatabaseClient) QueryRow added in v1.1.0

func (d *DatabaseClient) QueryRow(ctx context.Context, statement Statement) *sql.Row

QueryRow runs a single-row query with core-owned options.

func (*DatabaseClient) SQLDB added in v1.1.0

func (d *DatabaseClient) SQLDB() *sql.DB

SQLDB returns the standard-library database handle.

type DatabaseOptions added in v1.1.0

type DatabaseOptions struct {
	Host            string
	Port            string
	User            string
	Password        string
	Database        string
	ApplicationName string
	MaxOpenConns    int
	ConnMaxLifetime time.Duration
}

DatabaseOptions is the core-owned input for constructing a Postgres database client.

type Statement added in v1.1.0

type Statement struct {
	Query string
	Args  []any
}

Statement is the core-owned input for SQL operations.

Jump to

Keyboard shortcuts

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