pgkebab

package module
v0.0.0-...-063ebdd Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2020 License: MIT Imports: 11 Imported by: 0

README

GitHub GitHub Go Report Card Go Version

PGKebab

GOLang PostgreSQL Helper Over PQ
Makes PostgreSQL handling as easy and simple as GOlang
Replace heavy ORMs and dense routines with simple SQL queries

PGKebab

Simple Sample
package main

import (
	"fmt"
	"github.com/miguelpragier/pgkebab"
	"log"
)

func main() {
	const (
		connectionTimeout                  = 10
		executiontionTimeout               = 10
		connectionMaxAttempts              = 5
		connectionMaxMinutesRetrying       = 5
		secondsBetweenReconnectionAttempts = 10
		debugLogPrint                      = true
	)

	var (
		cs         = pgkebab.ConnStringEnvVar("{YOURAPPCONNECTIONSTRING}")
		opts       = pgkebab.Options(cs, connectionTimeout, executiontionTimeout, connectionMaxAttempts, connectionMaxMinutesRetrying, secondsBetweenReconnectionAttempts, debugLogPrint)
		customerID = 1
	)

	db, errcnx := pgkebab.NewConnected(opts)

	if errcnx != nil {
		log.Fatal(errcnx)
	}

	if row, err := db.GetOne("SELECT name, status_id FROM customers WHERE id=$1", customerID); err != nil {
		log.Fatal(err)
	} else {
		fmt.Println("the customer", row.String("name"), "has status", row.Int64("status_id"))
	}

	if n, err := db.GetCount("customers"); err != nil {
		log.Fatal(err)
	} else {
		fmt.Println("table customer counts", n, "rows")
	}
}
Dependencies:

pq - Pure Go Postgres driver for database/sql


Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Pairs

func Pairs(params ...interface{}) map[string]interface{}

Pairs is a helper for creating query pairs The first pairs item SHOULD be string, or the function panics The function panics for "less than 2 items", or "odd quantity of items".

Types

type ConnectionString

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

ConnectionString has directives to obtain database connection string To create a new ConnectionString, use ConnStringDirect(), ConnStringEnvVar()

func ConnStringDirect

func ConnStringDirect(val string) *ConnectionString

ConnStringDirect sets connection string with given value

func ConnStringEnvVar

func ConnStringEnvVar(key string) *ConnectionString

ConnStringEnvVar configures the engine to obtain connection string from given environment variable

type DBLink struct {
	DBLinkOptions // connection options
	// contains filtered or unexported fields
}

DBLink is the basic interface between developer and database instance

func New

func New(opts *DBLinkOptions) (*DBLink, error)

New returns an instance of database, configured with options.

func NewConnected

func NewConnected(opts *DBLinkOptions) (*DBLink, error)

NewConnected returns an already connected instance of dbLink, ready for use

func (*DBLink) Bool

func (l *DBLink) Bool(sqlQuery string, args ...interface{}) bool

Bool returns the query result's single value as a boolean. in case of any error, it returns false

func (*DBLink) Connect

func (l *DBLink) Connect() error

Connect assures that database could be reached and used.

func (*DBLink) Database

func (l *DBLink) Database() *sql.DB

Database returns the raw sql driver database connection, aimed to let the programmer execute transactions and advanced operations

func (*DBLink) Delete

func (l *DBLink) Delete(table string, wherePairs map[string]interface{}) (int64, error)

Delete executes "delete" statements against specific table, considering the mandatory "where" criteria The routine tries to return affected rows count.

func (*DBLink) Disconnect

func (l *DBLink) Disconnect()

Disconnect closes the link with database or database pool

func (*DBLink) Exec

func (l *DBLink) Exec(sqlQuery string, args ...interface{}) (int64, error)

Exec sends the given sql query to database server. typically update, delete and insert, and return the number of affected rows

func (*DBLink) Exists

func (l *DBLink) Exists(sqlQuery string, args ...interface{}) (bool, error)

Exists returns true if the query returns non null resultset

func (*DBLink) GetBool

func (l *DBLink) GetBool(sqlQuery string, args ...interface{}) (bool, error)

GetBool returns the query result's single value as a boolean

func (*DBLink) GetCount

func (l *DBLink) GetCount(sqlQuery string, args ...interface{}) (int64, error)

GetCount returns the number of records produced by given query

func (*DBLink) GetFloat64

func (l *DBLink) GetFloat64(sqlQuery string, args ...interface{}) (float64, error)

GetFloat64 returns the query result's single value as a float64

func (*DBLink) GetInt

func (l *DBLink) GetInt(sqlQuery string, args ...interface{}) (int, error)

GetInt returns the query result's single value as an int64

func (*DBLink) GetInt64

func (l *DBLink) GetInt64(sqlQuery string, args ...interface{}) (int64, error)

GetInt64 returns the query result's single value as an int64

func (*DBLink) GetJSONMap

func (l *DBLink) GetJSONMap(sqlQuery string, args ...interface{}) (map[string]interface{}, error)

GetJSONMap returns the query result's single column value as map

func (*DBLink) GetJSONStruct

func (l *DBLink) GetJSONStruct(target interface{}, sqlQuery string, args ...interface{}) error

GetJSONStruct tries to scan query result's single column value into given struct

func (*DBLink) GetMany

func (l *DBLink) GetMany(sqlQuery string, args ...interface{}) (Resultset, error)

GetMany returns sql query result as an array of map[string]string

func (*DBLink) GetOne

func (l *DBLink) GetOne(sqlQuery string, args ...interface{}) (Row, error)

GetOne returns sql query result as a Row

func (*DBLink) GetString

func (l *DBLink) GetString(sqlQuery string, args ...interface{}) (string, error)

GetString returns the query result's single value as a string

func (*DBLink) GetTime

func (l *DBLink) GetTime(sqlQuery string, args ...interface{}) (time.Time, error)

GetTime returns the query result's single value as a time.Time

func (*DBLink) GetTimef

func (l *DBLink) GetTimef(format, sqlQuery string, args ...interface{}) (string, error)

GetTimef returns the query result's single value as a formatted time.Time, considering the given format string

func (*DBLink) Insert

func (l *DBLink) Insert(table string, pairs map[string]interface{}) error

Insert executes an "insert" sql query against given table

func (*DBLink) InsertID

func (l *DBLink) InsertID(table string, pairs map[string]interface{}, idFieldName ...string) (int64, error)

InsertID inserts a new record into given table and returns the last inserted id The 3rd param is the optional field name. If not given, the default value "id" will be used

func (*DBLink) InsertUUID

func (l *DBLink) InsertUUID(table string, pairs map[string]interface{}, idFieldName ...string) (string, error)

InsertUUID inserts a new record into given table and returns the last inserted uuid The 3rd param is the optional field name. If not given, the default value "id" will be used

func (*DBLink) IsEmptyErr

func (l *DBLink) IsEmptyErr(err error) bool

IsEmptyErr returns true if the given error is sql.ErrNoRows

func (*DBLink) MustGetBool

func (l *DBLink) MustGetBool(sqlQuery string, args ...interface{}) (bool, error)

MustGetBool returns the query result's single value as a boolean If sql.ErrNoRows occurs, it's returned. The other routines ( without "Must" preffix ) ignores sql.ErrNoRows

func (*DBLink) MustGetFloat64

func (l *DBLink) MustGetFloat64(sqlQuery string, args ...interface{}) (float64, error)

MustGetFloat64 returns the query result's single value as a float64 If sql.ErrNoRows occurs, it's returned. The other routines ( without "Must" preffix ) ignores sql.ErrNoRows

func (*DBLink) MustGetInt

func (l *DBLink) MustGetInt(sqlQuery string, args ...interface{}) (int, error)

MustGetInt returns the query result's single value as an int If sql.ErrNoRows occurs, it's returned. The other routines ( without "Must" preffix ) ignores sql.ErrNoRows

func (*DBLink) MustGetInt64

func (l *DBLink) MustGetInt64(sqlQuery string, args ...interface{}) (int64, error)

MustGetInt64 returns the query result's single value as an int64 If sql.ErrNoRows occurs, it's returned. The other routines ( without "Must" preffix ) ignores sql.ErrNoRows

func (*DBLink) MustGetJSONMap

func (l *DBLink) MustGetJSONMap(sqlQuery string, args ...interface{}) (map[string]interface{}, error)

MustGetJSONMap returns the query result's single column value as map If sql.ErrNoRows occurs, it's returned. The other routines ( without "Must" preffix ) ignores sql.ErrNoRows

func (*DBLink) MustGetJSONStruct

func (l *DBLink) MustGetJSONStruct(target interface{}, sqlQuery string, args ...interface{}) error

MustGetJSONStruct tries to scan query result's single column value into given struct If sql.ErrNoRows occurs, it's returned. The other routines ( without "Must" preffix ) ignores sql.ErrNoRows

func (*DBLink) MustGetMany

func (l *DBLink) MustGetMany(sqlQuery string, args ...interface{}) (Resultset, error)

MustGetMany returns sql query result as an array of map[string]string The difference to GetMany is that, if no record is found, it returns an error

func (*DBLink) MustGetString

func (l *DBLink) MustGetString(sqlQuery string, args ...interface{}) (string, error)

MustGetString returns the query result's single value as a string If sql.ErrNoRows occurs, it's returned. The other routines ( without "Must" preffix ) ignores sql.ErrNoRows

func (*DBLink) MustGetTime

func (l *DBLink) MustGetTime(sqlQuery string, args ...interface{}) (time.Time, error)

MustGetTime returns the query result's single value as a time.Time If sql.ErrNoRows occurs, it's returned. The other routines ( without "Must" preffix ) ignores sql.ErrNoRows

func (*DBLink) MustGetTimef

func (l *DBLink) MustGetTimef(format, sqlQuery string, args ...interface{}) (string, error)

MustGetTimef returns the query result's single value as a formatted time.Time, considering the given format string If sql.ErrNoRows occurs, it's returned. The other routines ( without "Must" preffix ) ignores sql.ErrNoRows

func (*DBLink) SetEmergencyCallback

func (l *DBLink) SetEmergencyCallback(ec func(error))

SetEmergencyCallback defines a routine to log emergency "no-connection" messages

func (*DBLink) Update

func (l *DBLink) Update(table string, updatePairs map[string]interface{}, wherePairs map[string]interface{}) (int64, error)

Update executes "update" sql queries against database At least one whereParameters is mandatory. Important: WHERE only accepts "AND" where criteria. If you need to send more complex operations/statements, use Execute()

type DBLinkOptions

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

DBLinkOptions contains directives for config database connection To create an instance, use Options() function

func Options

func Options(cs *ConnectionString, connTimeout, execTimeout, connAttemptsMax, connAttemptsMaxMinutes, secondsBetweenReconnectionAttempts uint, debugPrint bool) *DBLinkOptions

Options is a helper to initializate a new DBLinkOptions structure reconnectionAttemptsMax is the max number of (re)connection attempts. If zeroed, keeps trying indefinitely or until reconnectionAttemptsMaxMinutes is reached. reconnectionAttemptsMaxMinutes is the max allowed time to insist in (re)connect. If zeroed, keeps trying undefinetely or until reconnectionAttemptsMax is reached intervalBetweenReconnectionAttemptsSeconds is the sleepin' time lapse between (re)connection attempts debugPrint if true, prints debug/log messages to stdout with stdlib log.Printf() function

type Resultset

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

Resultset contains rows and result metadata

func (Resultset) Bottom

func (r Resultset) Bottom() bool

Bottom returns true if the cursor reached its final row

func (Resultset) Count

func (r Resultset) Count() int

Count returns the number of rows in this resultset

func (Resultset) JSON

func (r Resultset) JSON(errorIfEmpty bool) (string, error)

JSON returns a json resultset representation

func (Resultset) Map

func (r Resultset) Map() []map[string]interface{}

Map returns the resultset as a []map[string]interface{} If the resultset is empty, returns nil

func (*Resultset) Next

func (r *Resultset) Next() bool

Next returns true if there's a next item and position the internal cursonr on it

func (*Resultset) Rewind

func (r *Resultset) Rewind()

Rewind set the internal cursor at first row

func (*Resultset) Row

func (r *Resultset) Row() (Row, error)

Row returns the current row, set by the internal pointer/position.

func (*Resultset) Rows

func (r *Resultset) Rows() ([]Row, error)

Rows returns a row array from the current resultset

func (Resultset) Top

func (r Resultset) Top() bool

Top returns true if the cursor is set on first item

type Row

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

Row holds a single record

func (Row) Bool

func (r Row) Bool(key string) bool

Bool returns the specified field as boolean

func (Row) Columns

func (r Row) Columns() []string

Columns returns an string array filled with column names

func (Row) Float64

func (r Row) Float64(key string) float64

Float64 returns the specified field as float64 Check for conversion details: https://stackoverflow.com/questions/31946344/why-does-go-treat-a-postgresql-numeric-decimal-columns-as-uint8

func (Row) Int

func (r Row) Int(key string) int

Int returns the specified field as Int

func (Row) Int64

func (r Row) Int64(key string) int64

Int64 returns the specified field as Int64

func (Row) JSON

func (r Row) JSON() (string, error)

JSON returns the column content serialized as JSON string

func (Row) JSONMap

func (r Row) JSONMap(key string) (map[string]interface{}, bool)

JSONMap returns the column content desserialized and a bool indicating if the map has some content

func (Row) JSONStruct

func (r Row) JSONStruct(key string, target interface{}) error

JSONStruct returns the column content desserialized to given target struct

func (Row) Map

func (r Row) Map() map[string]interface{}

Map returns the current tuple as map[string]interface{}

func (Row) Ready

func (r Row) Ready() bool

Ready returns true if the tuple contains at least one filled column

func (Row) String

func (r Row) String(key string) string

String returns the specified field as string

func (Row) Time

func (r Row) Time(key string) time.Time

Time returns the specified field as time.Time

func (Row) Timef

func (r Row) Timef(key, format string) time.Time

Timef returns the specified field as time.Time it tries to interpret the date/time value according the given format

Jump to

Keyboard shortcuts

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