picodata

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2026 License: BSD-2-Clause Imports: 11 Imported by: 3

README

picodata-go - Picodata driver based on pgx

picodata-go is a pure Golang driver for Picodata.
With power of pgx/pgxpool library, peer discovery and embedded load balancing it provides seamless experience of using distributed databases.

Key features:

  1. Instance discovery
  2. Load balancing with public API
  3. Automatic topology managing

Example of usage

package main

import (
	"context"
	"fmt"
	"os"

	picogo "github.com/picodata/picodata-go"
	logger "github.com/picodata/picodata-go/logger"
	strats "github.com/picodata/picodata-go/strategies"
)

func main() {
	// export PICODATA_CONNECTION_URL=postgres://username:password@host:port
	pool, err := picogo.New(context.Background(), os.Getenv("PICODATA_CONNECTION_URL"), picogo.WithBalanceStrategy(strats.NewRoundRobinStrategy()), picogo.WithLogLevel(logger.LevelError))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
		os.Exit(1)
	}
	defer pool.Close()
	/*
	 CREATE TABLE items (id INTEGER NOT NULL,name TEXT NOT NULL,stock INTEGER,PRIMARY KEY (id)) USING memtx DISTRIBUTED BY (id) OPTION (TIMEOUT = 3.0);
	 INSERT INTO items VALUES
	 (1, 'bricks', 1123),
	 (2, 'panels', 998),
	 (3, 'piles', 177);
	*/
	var (
		id    int
		name  string
		stock int
	)
	err = pool.QueryRow(context.Background(), "select * from items where id=$1", 2).Scan(&id, &name, &stock)
	if err != nil {
		fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err)
		os.Exit(1)
	}

	fmt.Println(id, name, stock)
}

picodata-go Pool class follows and provides the same API as pgx/v5/pgxpool. Also, Pool's New() and NewWithConfig() methods receive optional arguments - functional options, that can modify default settings. You can check them out in pool_opts.go file:

func WithBalanceStrategy(strategy strategies.BalanceStrategy) PoolOption {
	...
}

func WithLogger(customLogger logger.Logger) PoolOption {
	...
}

func WithLogLevel(level logger.LogLevel) PoolOption {
	...
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParseConfig

func ParseConfig(connString string) (*pgxpool.Config, error)

ParseConfig builds a *pgxpool.Config from connString.

Example URL
postgres://admin:T0psecret@localhost:5432?sslmode=disable&pool_max_conns=10

Types

type Pool

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

Pool allows for connection reuse. It operates with slice of *pgxpool.Pool, each Picodata instance have its own pool object.

func New

func New(ctx context.Context, connString string, opts ...PoolOption) (*Pool, error)

New creates a new Pool. See ParseConfig for information on connString format.

func NewWithConfig

func NewWithConfig(ctx context.Context, config *pgxpool.Config, opts ...PoolOption) (*Pool, error)

NewWithConfig creates a new Pool. config must have been created by ParseConfig.

func (*Pool) Close

func (p *Pool) Close()

Close closes all connections in the pool and rejects future Acquire calls. Blocks until all connections are returned to pool and closed.

It is safe to close a pool multiple times.

func (*Pool) Config

func (p *Pool) Config() *pgxpool.Config

Config returns a copy of config that was used to initialize this pool.

func (*Pool) Exec

func (p *Pool) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error)

Exec acquires a connection from the Pool and executes the given SQL. SQL can be either a prepared statement name or an SQL string. Arguments should be referenced positionally from the SQL string as $1, $2, etc. The acquired connection is returned to the pool when the Exec function returns.

func (*Pool) Ping

func (p *Pool) Ping(ctx context.Context) error

Ping acquires a connection from the Pool and executes a simple SQL statement against it. If the sql returns without error, the database Ping is considered successful, otherwise, the error is returned.

func (*Pool) Query

func (p *Pool) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)

Query acquires a connection and executes a query that returns pgx.Rows. Arguments should be referenced positionally from the SQL string as $1, $2, etc. See pgx.Rows documentation to close the returned Rows and return the acquired connection to the Pool.

If there is an error, the returned pgx.Rows will be returned in an error state. If preferred, ignore the error returned from Query and handle errors using the returned pgx.Rows.

For extra control over how the query is executed, the types QuerySimpleProtocol, QueryResultFormats, and QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely needed. See the documentation for those types for details.

func (*Pool) QueryRow

func (p *Pool) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row

QueryRow acquires a connection and executes a query that is expected to return at most one row (pgx.Row). Errors are deferred until pgx.Row's Scan method is called. If the query selects no rows, pgx.Row's Scan will return ErrNoRows. Otherwise, pgx.Row's Scan scans the first selected row and discards the rest. The acquired connection is returned to the Pool when pgx.Row's Scan method is called.

Arguments should be referenced positionally from the SQL string as $1, $2, etc.

For extra control over how the query is executed, the types QuerySimpleProtocol, QueryResultFormats, and QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely needed. See the documentation for those types for details.

func (*Pool) Reset

func (p *Pool) Reset()

Reset closes all connections, but leaves the pool open. It is intended for use when an error is detected that would disrupt all connections (such as a network interruption or a server state change).

It is safe to reset a pool while connections are checked out. Those connections will be closed when they are returned to the pool.

func (*Pool) SendBatch

func (p *Pool) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults

SendBatch acquires a connection from the pool and sends a batch of SQL commands for execution using that connection.

It returns a pgx.BatchResults interface, which provides access to the results of each command in the batch.

If acquiring a connection from the pool fails, SendBatch returns a pgx.BatchResults that will return the acquisition error on any result method.

The caller must ensure that the returned BatchResults is closed via Close() to release the connection back to the pool.

Example usage

batch := &pgx.Batch{}
batch.Queue("INSERT INTO users (name) VALUES($1)", "alice")
batch.Queue("SELECT COUNT(*) FROM users")
results := pool.SendBatch(ctx, batch)
defer results.Close()
tag, err := results.Exec()
if err != nil{...}
err := results.QueryRow().Scan(&count)
if err != nil{...}

type PoolOption

type PoolOption func(*poolOpts) error

func WithBalanceStrategy

func WithBalanceStrategy(strategy strategies.BalanceStrategy) PoolOption

WithBalanceStrategy defines logic of pool balancing across connections

func WithDisableTopologyManaging added in v1.1.0

func WithDisableTopologyManaging() PoolOption

WithDisableTopologyManaging disables backfround poller that actualizes topology

func WithLogLevel

func WithLogLevel(level logger.LogLevel) PoolOption

WithLogLevel set a logger level for pool internal logger

func WithLogger

func WithLogger(customLogger logger.Logger) PoolOption

WithLogger sets a custom pool internal logger to print information

func WithMaxConnPerInstance added in v1.1.0

func WithMaxConnPerInstance(maxConns int32) PoolOption

func WithServiceConnString added in v1.1.0

func WithServiceConnString(addr string) PoolOption

WithServiceConnString takes postgresql connection string for the service instance where cluster metainfo will be taken

Directories

Path Synopsis
examples
crud command

Jump to

Keyboard shortcuts

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