prom

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2019 License: MIT Imports: 22 Imported by: 1

README

prom

Go Report Card GoDoc

Utility library to manage shared connection in Golang.

Documentation

History

2019-10-12 - v0.2.0
2019-09-14 - v0.1.3
2019-04-03 - v0.1.2
  • 'Prom' for database/sql:
    • Add timezone location attribute to SqlConnect struct.
    • Correctly parse date/time data from db using timezone location attribute.
2019-04-01 - v0.1.1
2019-03-27 - v0.1.0
  • Migrated Go modular design.
  • Add DbFlavor:
    • New method NewSqlConnectWithFlavor
  • SqlConnect.fetchOneRow fetches correct column's data type instead of []byte for MySQL. This makes results of SqlConnect.FetchRows and SqlConnect.FetchRowsCallback are correctly typed, too.
  • Update examples for MongoDB, MySQL and PostgreSQL.
  • Add examples for MSSQL and Oracle DB.
2019-03-19 - v0.0.4
2019-03-08 - v0.0.3.1
  • 'Prom' for the official Go driver for MongoDB: add 2 functions
    • DecodeSingleResultRaw(*mongo.SingleResult) (string, error)
    • DecodeResultCallbackRaw(context.Context, *mongo.Cursor, func(docNum int, doc string, err error))
  • Bug fixes & refactoring.
2019-03-05 - v0.0.3
2019-03-04 - v0.0.2
  • Function DecodeSingleResult and DecodeResultCallback are now attached to *MongoConnect
  • Change Mongo's timeout parameter from int64 to int
2019-02-28 - v0.0.1

License

MIT - see LICENSE.md.

Documentation

Overview

Package prom provides helpers to manage shared connections in Golang.

Documentation: see project's GitHub (https://godoc.org/github.com/btnguyen2k/prom)

Index

Constants

View Source
const (
	// AwsDynamodbNoIndex indicates that no index will be used
	AwsDynamodbNoIndex = ""
)
View Source
const (
	// Version of prom
	Version = "0.2.0"
)

Variables

This section is empty.

Functions

func AwsDynamodbEqualsBuilder added in v0.2.0

func AwsDynamodbEqualsBuilder(condition map[string]interface{}) *expression.ConditionBuilder

AwsDynamodbEqualsBuilder builds a expression.ConditionBuilder with condition attr1=value1 AND attr1=value1 AND...

Parameters:

  • condition: format {attribute-name:attribute-value}

func AwsDynamodbExistsAllBuilder added in v0.2.0

func AwsDynamodbExistsAllBuilder(attrs []string) *expression.ConditionBuilder

AwsDynamodbExistsAllBuilder builds a expression.ConditionBuilder where all attributes must exist.

func AwsDynamodbNotExistsAllBuilder added in v0.2.0

func AwsDynamodbNotExistsAllBuilder(attrs []string) *expression.ConditionBuilder

AwsDynamodbNotExistsAllBuilder builds a expression.ConditionBuilder where all attributes must not exist.

func AwsDynamodbToAttributeSet added in v0.2.0

func AwsDynamodbToAttributeSet(v interface{}) *dynamodb.AttributeValue

AwsDynamodbToAttributeSet converts a Go value to DynamoDB's set.

func AwsDynamodbToAttributeValue added in v0.2.0

func AwsDynamodbToAttributeValue(v interface{}) *dynamodb.AttributeValue

AwsDynamodbToAttributeValue converts a Go value to DynamoDB's attribute value.

func AwsIgnoreErrorIfMatched added in v0.2.0

func AwsIgnoreErrorIfMatched(err error, excludeCode string) error

AwsIgnoreErrorIfMatched returns nil if err is an awserr.Error and its code equals to excludeCode.

Types

type AwsDynamodbConnect added in v0.2.0

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

AwsDynamodbConnect holds a AWS DynamoDB client (https://github.com/aws/aws-sdk-go/tree/master/service/dynamodb) that can be shared within the application.

func NewAwsDynamodbConnect added in v0.2.0

func NewAwsDynamodbConnect(cfg *aws.Config, sess *session.Session, db *dynamodb.DynamoDB, defaultTimeoutMs int) (*AwsDynamodbConnect, error)

NewAwsDynamodbConnect constructs a new AwsDynamodbConnect instance.

Parameters:

  • cfg : aws.Config instance
  • sess : session.Session instance
  • db : dynamodb.DynamoDB instance
  • defaultTimeoutMs: default timeout for db operations, in milliseconds

Return: the AwsDynamodbConnect instance and error (if any). Note:

  • if db is nil, it will be built from session
  • if session is nil, it sill be built from config
  • at least one of {config, session, db} must not be nil

func (*AwsDynamodbConnect) AddValuesToAttributes added in v0.2.0

func (adc *AwsDynamodbConnect) AddValuesToAttributes(ctx aws.Context, table string, keyFilter map[string]interface{}, condition *expression.ConditionBuilder, attrsAndValues map[string]interface{}) (*dynamodb.UpdateItemOutput, error)

AddValuesToAttributes adds values to one or more attributes of an item.

Parameters:

  • ctx : (optional) used for request cancellation
  • table : name of the table
  • keyFilter : map of {primary-key-attribute-name:attribute-value}, must include all primary key's attributes
  • condition : (optional) a condition that must be satisfied before updating item
  • attrsAndValues: list of attributes and values to add

See https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html

Note: currently can not add value to a set using this function. To add value to a set, use AddValuesToSet. See: https://github.com/aws/aws-sdk-go/issues/1990

func (*AwsDynamodbConnect) AddValuesToSet added in v0.2.0

func (adc *AwsDynamodbConnect) AddValuesToSet(ctx aws.Context, table string, keyFilter map[string]interface{}, condition *expression.ConditionBuilder, attrsAndValues map[string]interface{}) (*dynamodb.UpdateItemOutput, error)

AddValuesToSet adds values to set attributes of an item.

Parameters:

  • ctx : (optional) used for request cancellation
  • table : name of the table
  • keyFilter : map of {primary-key-attribute-name:attribute-value}, must include all primary key's attributes
  • condition : (optional) a condition that must be satisfied before updating item
  • attrsAndValues: list of attributes and values to add

See https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html

func (*AwsDynamodbConnect) Close added in v0.2.0

func (adc *AwsDynamodbConnect) Close() error

Close frees all resources and closes all connection associated with this AwsDynamodbConnect.

func (*AwsDynamodbConnect) CreateGlobalSecondaryIndex added in v0.2.0

func (adc *AwsDynamodbConnect) CreateGlobalSecondaryIndex(ctx aws.Context, table, indexName string, rcu, wcu int64, attrDefs, keyAttrs []AwsDynamodbNameAndType) error

CreateGlobalSecondaryIndex creates a Global Secondary Index on a specified table.

Parameters:

  • ctx: (optional) used for request cancellation
  • table : name of the table
  • indexName: name of the index to be created
  • rcu : ReadCapacityUnits (0 means PAY_PER_REQUEST)
  • wcu : WriteCapacityUnits (0 means PAY_PER_REQUEST)
  • attrDefs : GSI attributes, where attribute-type is either "S", "N" or "B"
  • keyAttrs : GSI key schema, where key-type is either "HASH" or "RANGE"

Note: DynamoDB GSI is created asynchronously. Use GetGlobalSecondaryIndexStatus to check GSI's existence.

func (*AwsDynamodbConnect) CreateTable added in v0.2.0

func (adc *AwsDynamodbConnect) CreateTable(ctx aws.Context, table string, rcu, wcu int64, attrDefs, pkDefs []AwsDynamodbNameAndType) error

CreateTable create a new table without index.

Parameters:

  • ctx: (optional) used for request cancellation
  • table : name of the table to be created
  • rcu : ReadCapacityUnits (0 means PAY_PER_REQUEST)
  • wcu : WriteCapacityUnits (0 means PAY_PER_REQUEST)
  • attrDefs: table attributes, where attribute-type is either "S", "N" or "B"
  • pkDefs : primary key definitions, where key-type is either "HASH" or "RANGE"

Note: DynamoDB table is created asynchronously. Use GetTableStatus to check table's existence.

func (*AwsDynamodbConnect) DeleteGlobalSecondaryIndex added in v0.2.0

func (adc *AwsDynamodbConnect) DeleteGlobalSecondaryIndex(ctx aws.Context, table, indexName string) error

DeleteGlobalSecondaryIndex deletes a Global Secondary Index on a specified table.

Parameters:

  • ctx: (optional) used for request cancellation

Note: DynamoDB GSI is deleted asynchronously. Use GetGlobalSecondaryIndexStatus to check GSI's existence.

func (*AwsDynamodbConnect) DeleteItem added in v0.2.0

func (adc *AwsDynamodbConnect) DeleteItem(ctx aws.Context, table string, keyFilter map[string]interface{}, condition *expression.ConditionBuilder) (*dynamodb.DeleteItemOutput, error)

DeleteItem removes a single item from specified table.

Parameters:

  • ctx: (optional) used for request cancellation
  • table : name of the table
  • keyFilter: map of {primary-key-attribute-name:attribute-value}, must include all primary key's attributes
  • condition: (optional) a condition that must be satisfied before removing item

func (*AwsDynamodbConnect) DeleteTable added in v0.2.0

func (adc *AwsDynamodbConnect) DeleteTable(ctx aws.Context, table string) error

DeleteTable deletes an existing table.

Parameters:

  • ctx: (optional) used for request cancellation

Note: DynamoDB table is deleted asynchronously. Use GetTableStatus to check table's existence.

func (*AwsDynamodbConnect) DeleteValuesFromAttributes added in v0.2.0

func (adc *AwsDynamodbConnect) DeleteValuesFromAttributes(ctx aws.Context, table string, keyFilter map[string]interface{}, condition *expression.ConditionBuilder, attrsAndValues map[string]interface{}) (*dynamodb.UpdateItemOutput, error)

DeleteValuesFromAttributes deletes values from one or more set attributes of an item.

Parameters:

  • ctx : (optional) used for request cancellation
  • table : name of the table
  • keyFilter : map of {primary-key-attribute-name:attribute-value}, must include all primary key's attributes
  • condition : (optional) a condition that must be satisfied before updating item
  • attrsAndValues: list of attributes and values to delete

See https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html

func (*AwsDynamodbConnect) GetDb added in v0.2.0

func (adc *AwsDynamodbConnect) GetDb() *dynamodb.DynamoDB

GetDb returns the underlying dynamodb.DynamoDB instance.

func (*AwsDynamodbConnect) GetGlobalSecondaryIndexStatus added in v0.2.0

func (adc *AwsDynamodbConnect) GetGlobalSecondaryIndexStatus(ctx aws.Context, table, indexName string) (string, error)

GetGlobalSecondaryIndexStatus fetches and returns a table's GSI status.

Parameters:

  • ctx: (optional) used for request cancellation

Notes:

  • If index does not exist, this function returns "", nil

func (*AwsDynamodbConnect) GetItem added in v0.2.0

func (adc *AwsDynamodbConnect) GetItem(ctx aws.Context, table string, keyFilter map[string]interface{}) (AwsDynamodbItem, error)

GetItem fetches a single item from specified table.

Parameters:

  • ctx: (optional) used for request cancellation
  • table : name of the table
  • keyFilter: map of {primary-key-attribute-name:attribute-value}, must include all primary key's attributes

Notes:

  • If item does not exist, this function returns (nil, nil).
  • This function fetches all attributes of items.
  • ConsistentRead is not used.

func (*AwsDynamodbConnect) GetTableStatus added in v0.2.0

func (adc *AwsDynamodbConnect) GetTableStatus(ctx aws.Context, table string) (string, error)

GetTableStatus fetches and returns table status.

Parameters:

  • ctx: (optional) used for request cancellation

Notes:

  • If table does not exist, this function returns "", nil

func (*AwsDynamodbConnect) HasTable added in v0.2.0

func (adc *AwsDynamodbConnect) HasTable(ctx aws.Context, table string) (bool, error)

HasTable checks if a table exists.

Parameters:

  • ctx: (optional) used for request cancellation

func (*AwsDynamodbConnect) ListTables added in v0.2.0

func (adc *AwsDynamodbConnect) ListTables(ctx aws.Context) ([]string, error)

ListTables returns all visible tables.

Parameters:

  • ctx: (optional) used for request cancellation

func (*AwsDynamodbConnect) NewContext added in v0.2.0

func (adc *AwsDynamodbConnect) NewContext(timeoutMs ...int) (aws.Context, context.CancelFunc)

NewContext creates a new context with specified timeout in milliseconds. If there is no specified timeout, or timeout value is less than or equal to 0, the default timeout is used.

func (*AwsDynamodbConnect) PutItem added in v0.2.0

func (adc *AwsDynamodbConnect) PutItem(ctx aws.Context, table string, item interface{}, condition *expression.ConditionBuilder) (*dynamodb.PutItemOutput, error)

PutItem inserts a new item to table or replace an existing one.

Parameters:

  • ctx: (optional) used for request cancellation
  • table : name of the table
  • item : item to be inserted (a map or struct), will be converted to map[string]*dynamodb.AttributeValue via dynamodbattribute.MarshalMap(item)
  • condition: (optional) a condition that must be satisfied before writing item

func (*AwsDynamodbConnect) PutItemIfNotExist added in v0.2.0

func (adc *AwsDynamodbConnect) PutItemIfNotExist(ctx aws.Context, table string, item interface{}, pkAttrs []string) (*dynamodb.PutItemOutput, error)

PutItemIfNotExist inserts a new item to table only if it does not exist.

Parameters:

  • ctx: (optional) used for request cancellation
  • table : name of the table
  • item : item to be inserted (a map or struct), will be converted to map[string]*dynamodb.AttributeValue via dynamodbattribute.MarshalMap(item)
  • pkAttrs: primary key attribute names

func (*AwsDynamodbConnect) PutItemRaw added in v0.2.0

PutItemRaw inserts a new item to table or replace an existing one.

Parameters:

  • ctx : (optional) used for request cancellation
  • table : name of the table
  • item : item to be inserted
  • condition: (optional) a condition that must be satisfied before writing item

func (*AwsDynamodbConnect) PutItemRawIfNotExist added in v0.2.0

func (adc *AwsDynamodbConnect) PutItemRawIfNotExist(ctx aws.Context, table string, item map[string]*dynamodb.AttributeValue, pkAttrs []string) (*dynamodb.PutItemOutput, error)

PutItemRawIfNotExist inserts a new item to table only if it does not exist.

Parameters:

  • ctx : (optional) used for request cancellation
  • table : name of the table
  • item : item to be inserted
  • pkAttrs: primary key attribute names

func (*AwsDynamodbConnect) QueryItems added in v0.2.0

func (adc *AwsDynamodbConnect) QueryItems(ctx aws.Context, table string, keyFilter, nonKeyFilter *expression.ConditionBuilder, indexName string) ([]AwsDynamodbItem, error)

QueryItems fetches multiple items from specified table using "query" operation.

Parameters:

  • ctx : (optional) used for request cancellation
  • table : name of the table to be scanned
  • keyFilter : used to filter items on primary key attributes
  • nonKeyFilter : used to filter items on non-primary key attributes before returning result
  • indexName : if non-empty, use this secondary index to scan (local or global)

Notes:

  • This function may not fetch all item's attributes when using secondary index and not all attributes are projected to the index.
  • ConsistentRead is not used.

func (*AwsDynamodbConnect) QueryItemsWithCallback added in v0.2.0

func (adc *AwsDynamodbConnect) QueryItemsWithCallback(ctx aws.Context, table string, keyFilter, nonKeyFilter *expression.ConditionBuilder, indexName string, exclusiveStartKey map[string]*dynamodb.AttributeValue, callback AwsDynamodbItemCallback) error

QueryItemsWithCallback fetches multiple items from specified table using "query" operation.

Parameters:

  • ctx : (optional) used for request cancellation
  • table : name of the table to be queried
  • keyFilter : used to filter items on primary key attributes
  • nonKeyFilter : used to filter items on non-primary key attributes before returning result
  • indexName : if non-empty, use this secondary index to query (local or global)
  • exclusiveStartKey: (optional) skip items till this key (used for paging)
  • callback : callback function

Notes:

  • This function may not fetch all item's attributes when using secondary index and not all attributes are projected to the index.
  • ConsistentRead is not used.

func (*AwsDynamodbConnect) RemoveAttributes added in v0.2.0

func (adc *AwsDynamodbConnect) RemoveAttributes(ctx aws.Context, table string, keyFilter map[string]interface{}, condition *expression.ConditionBuilder, attrs []string) (*dynamodb.UpdateItemOutput, error)

RemoveAttributes removes one or more attributes from an item.

Parameters:

  • ctx : (optional) used for request cancellation
  • table : name of the table
  • keyFilter: map of {primary-key-attribute-name:attribute-value}, must include all primary key's attributes
  • condition: (optional) a condition that must be satisfied before updating item
  • attrs : list of attributes to remove

See https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html

func (*AwsDynamodbConnect) ScanItems added in v0.2.0

func (adc *AwsDynamodbConnect) ScanItems(ctx aws.Context, table string, filter *expression.ConditionBuilder, indexName string) ([]AwsDynamodbItem, error)

ScanItems fetches multiple items from specified table using "scan" operation.

Parameters:

  • ctx : (optional) used for request cancellation
  • table : name of the table to be scanned
  • filter : (optional) used to filter scanned items
  • indexName : if non-empty, use this secondary index to scan (local or global)

Notes:

  • This function may not fetch all item's attributes when using secondary index and not all attributes are projected to the index.
  • ConsistentRead is not used.

func (*AwsDynamodbConnect) ScanItemsWithCallback added in v0.2.0

func (adc *AwsDynamodbConnect) ScanItemsWithCallback(ctx aws.Context, table string, filter *expression.ConditionBuilder, indexName string, exclusiveStartKey map[string]*dynamodb.AttributeValue, callback AwsDynamodbItemCallback) error

ScanItemsWithCallback fetches multiple items from specified table using "scan" operation.

Parameters:

  • ctx : (optional) used for request cancellation
  • table : name of the table to be scanned
  • filter : (optional) used to filter scanned items
  • indexName : if non-empty, use this secondary index to scan (local or global)
  • exclusiveStartKey: (optional) skip items till this key (used for paging)
  • callback : callback function

Notes:

  • This function may not fetch all item's attributes when using secondary index and not all attributes are projected to the index.
  • ConsistentRead is not used.

func (*AwsDynamodbConnect) SetAttributes added in v0.2.0

func (adc *AwsDynamodbConnect) SetAttributes(ctx aws.Context, table string, keyFilter map[string]interface{}, condition *expression.ConditionBuilder, attrsAndValues map[string]interface{}) (*dynamodb.UpdateItemOutput, error)

SetAttributes sets one or more attributes of an item.

Parameters:

  • ctx : (optional) used for request cancellation
  • table : name of the table
  • keyFilter : map of {primary-key-attribute-name:attribute-value}, must include all primary key's attributes
  • condition : (optional) a condition that must be satisfied before updating item
  • attrsAndValues: list of attributes and values to set

See https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html

func (*AwsDynamodbConnect) UpdateItem added in v0.2.0

func (adc *AwsDynamodbConnect) UpdateItem(ctx aws.Context, table string,
	keyFilter map[string]interface{}, condition *expression.ConditionBuilder,
	attrsToRemove []string, attrsAndValuesToSet, attrsAndValuesToAdd, attrsAndValuesToDelete map[string]interface{}) (*dynamodb.UpdateItemOutput, error)

UpdateItem performs operation remove/set/add value/delete values from item's attributes.

Parameters:

  • ctx : (optional) used for request cancellation
  • table : name of the table
  • keyFilter : map of {primary-key-attribute-name:attribute-value}, must include all primary key's attributes
  • condition : (optional) a condition that must be satisfied before updating item
  • attrsToRemove : list of attributes to remove
  • attrsAndValuesToSet : list of attributes and values to set
  • attrsAndValuesToAdd : list of attributes and values to add
  • attrsAndValuesToDelete: list of attributes and values to delete

Notes: at least one of attrsToRemove, attrsAndValuesToSet, attrsAndValuesToAdd, attrsAndValuesToDelete must be provided

See https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html

type AwsDynamodbItem added in v0.2.0

type AwsDynamodbItem map[string]interface{}

AwsDynamodbItem defines a generic structure for DynamoDB item.

type AwsDynamodbItemCallback added in v0.2.0

type AwsDynamodbItemCallback func(item AwsDynamodbItem, lastEvaluatedKey map[string]*dynamodb.AttributeValue) (bool, error)

AwsDynamodbItemCallback defines callback interface for "scan"/"query" operation.

If callback function returns false or error, the scan/query process will stop (even if there are still more items).

type AwsDynamodbNameAndType added in v0.2.0

type AwsDynamodbNameAndType struct{ Name, Type string }

AwsDynamodbNameAndType defines a generic name & type pair.

type DbFlavor added in v0.1.0

type DbFlavor int

DbFlavor specifies the flavor or database server/vendor.

Available: since v0.1.0

const (
	FlavorDefault DbFlavor = iota
	FlavorMySql
	FlavorPgSql
	FlavorMsSql
	FlavorOracle
)

Predefined db flavors.

Available: since v0.1.0

type GoRedisConnect added in v0.0.3

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

GoRedisConnect holds a go-redis client (https://github.com/go-redis/redis) that can be shared within the application.

func NewGoRedisConnect added in v0.0.3

func NewGoRedisConnect(hostsAndPorts, password string, maxRetries int) *GoRedisConnect

NewGoRedisConnect constructs a new GoRedisConnect instance with supplied options.

Parameters:

  • hostsAndPorts : list of Redis servers (example: "host1:6379,host2;host3:6380")
  • password : password to authenticate against Redis server
  • maxRetries : max number of retries for failed operations

func (*GoRedisConnect) Close added in v0.2.0

func (r *GoRedisConnect) Close() error

Close closes all underlying Redis connections associated with this GoRedisConnect.

Available: since v0.2.0

func (*GoRedisConnect) GetClient added in v0.0.3

func (r *GoRedisConnect) GetClient(db int) *redis.Client

GetClient returns the redis.Client associated with the specified db number.

  • This function use the first entry of 'hostsAndPorts' as Redis server address.
  • This function returns the existing client, if any (i.e. no new redis.Client instance will be created).

func (*GoRedisConnect) GetClusterClient added in v0.0.3

func (r *GoRedisConnect) GetClusterClient() *redis.ClusterClient

GetClusterClient returns the redis.ClusterClient associated with the GoRedisConnect.

  • This function use 'hostsAndPorts' config as list of Redis server addresses.
  • This function returns the existing client, if any (i.e. no new redis.ClusterClient instance will be created).

func (*GoRedisConnect) GetFailoverClient added in v0.0.3

func (r *GoRedisConnect) GetFailoverClient(db int) *redis.Client

GetFailoverClient returns the failover redis.Client associated with the specified db number.

  • This function use 'hostsAndPorts' config as list of Redis Sentinel server addresses.
  • This function returns the existing client, if any (i.e. no new redis.Client instance will be created).

func (*GoRedisConnect) SetSentinelMasterName added in v0.0.3

func (r *GoRedisConnect) SetSentinelMasterName(masterName string) *GoRedisConnect

SetSentinelMasterName sets the sentinel master name, used by failover clients. The change will apply to newly created clients, existing one will NOT be effected! This function returns the current GoRedisConnect instance so that function calls can be chained.

func (*GoRedisConnect) SetSlaveReadOnly added in v0.0.3

func (r *GoRedisConnect) SetSlaveReadOnly(readOnly bool) *GoRedisConnect

SetSlaveReadOnly enables/disables read-only commands on slave nodes. The change will apply to newly created clients, existing one will NOT be effected! This function returns the current GoRedisConnect instance so that function calls can be chained.

type MongoConnect

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

MongoConnect holds a MongoDB client (https://github.com/mongodb/mongo-go-driver) that can be shared within the application.

func NewMongoConnect

func NewMongoConnect(url, db string, defaultTimeoutMs int) (*MongoConnect, error)

NewMongoConnect constructs a new MongoConnect instance.

Parameters:

  • url : connection url, including authentication credentials
  • db : name of database to connect to
  • defaultTimeoutMs: default timeout for db operations, in milliseconds

Return: the MongoConnect instance and error (if any). Note:

  • In case of connection error: this function returns the MongoConnect instance and the error.
  • Other error: this function returns (nil, error)

func (*MongoConnect) Close added in v0.2.0

func (m *MongoConnect) Close(ctx context.Context) error

Close closes all connections associated with the underlying MongoDB client.

Available: since v0.2.0

func (*MongoConnect) CreateCollection

func (m *MongoConnect) CreateCollection(collectionName string) (*mongo.SingleResult, error)

CreateCollection creates a collection specified by 'collectionName'

func (*MongoConnect) CreateIndexes

func (m *MongoConnect) CreateIndexes(collectionName string, indexes []interface{}) (*mongo.SingleResult, error)

CreateIndexes creates indexes on the specified collection.

Example:

collectionName := "my_table"
indexes := []interface{}{
	map[string]interface{}{
		"key": map[string]interface{}{
			"field_1": 1, // ascending index
		},
		"name":   "uidx_1",
		"unique": true,
	},
	map[string]interface{}{
		"key": map[string]interface{}{
			"field_2": -1, // descending index
		},
		"name": "idx_2",
	},
}
dbResult, err := m.CreateIndexes(collectionName, indexes)

func (*MongoConnect) DecodeResultCallback

func (m *MongoConnect) DecodeResultCallback(ctx context.Context, cursor *mongo.Cursor, callback func(docNum int, doc bson.M, err error) bool)

DecodeResultCallback loops through the cursor and, for each fetched document, passes it to the callback function. Note:

  • docNum is 1-based, and scoped to the cursor context. This function does not close the cursor!
  • If callback function returns 'false', the loop will break and DecodeResultCallback returns.

func (*MongoConnect) DecodeResultCallbackRaw added in v0.0.4

func (m *MongoConnect) DecodeResultCallbackRaw(ctx context.Context, cursor *mongo.Cursor, callback func(docNum int, doc []byte, err error) bool)

DecodeResultCallbackRaw loops through the cursor and, for each fetched document, passes it to the callback function. Note:

  • docNum is 1-based, and scoped to the cursor context. This function does not close the cursor!
  • If callback function returns 'false', the loop will break and DecodeResultCallbackRaw returns.

Available: since v0.0.3.1

func (*MongoConnect) DecodeSingleResult

func (m *MongoConnect) DecodeSingleResult(dbResult *mongo.SingleResult) (bson.M, error)

DecodeSingleResult transforms 'mongo.SingleResult' to 'bson.M'.

func (*MongoConnect) DecodeSingleResultRaw added in v0.0.4

func (m *MongoConnect) DecodeSingleResultRaw(dbResult *mongo.SingleResult) ([]byte, error)

DecodeSingleResultRaw transforms 'mongo.SingleResult' to raw JSON data.

Available: since v0.0.3.1

func (*MongoConnect) Disconnect deprecated added in v0.1.0

func (m *MongoConnect) Disconnect(ctx context.Context) error

Disconnect is alias of Close.

Deprecated: since v0.2.0, use Close instead.

func (*MongoConnect) GetCollection

func (m *MongoConnect) GetCollection(collectionName string, opts ...*options.CollectionOptions) *mongo.Collection

GetCollection returns the collection object specified by 'collectionName'.

func (*MongoConnect) GetDatabase

func (m *MongoConnect) GetDatabase(opts ...*options.DatabaseOptions) *mongo.Database

GetDatabase returns the database object attached to this MongoConnect.

func (*MongoConnect) GetMongoClient

func (m *MongoConnect) GetMongoClient() *mongo.Client

GetMongoClient returns the underlying MongoDB client instance.

func (*MongoConnect) HasCollection added in v0.0.3

func (m *MongoConnect) HasCollection(collectionName string, opts ...*options.ListCollectionsOptions) (bool, error)

HasCollection checks if a collection exists in the database.

func (*MongoConnect) HasDatabase added in v0.0.3

func (m *MongoConnect) HasDatabase(dbName string, opts ...*options.ListDatabasesOptions) (bool, error)

HasDatabase checks if a database exists on MongoDB server.

func (*MongoConnect) IsConnected

func (m *MongoConnect) IsConnected() bool

IsConnected returns true if the connection to MongoDB has established.

func (*MongoConnect) NewBackgroundContext deprecated

func (m *MongoConnect) NewBackgroundContext(timeoutMs ...int) (context.Context, context.CancelFunc)

NewBackgroundContext is alias of NewContext.

Deprecated: since v0.2.0, use NewContext instead.

func (*MongoConnect) NewContext added in v0.2.0

func (m *MongoConnect) NewContext(timeoutMs ...int) (context.Context, context.CancelFunc)

NewContext creates a new context with specified timeout in milliseconds. If there is no specified timeout, or timeout value is less than or equal to 0, the default timeout is used.

Available: since v0.2.0

func (*MongoConnect) Ping added in v0.0.3

func (m *MongoConnect) Ping(timeoutMs ...int) error

Ping tries to send a "ping" request to MongoDB server. If there is no specified timeout, or timeout value is less than or equal to 0, the default timeout is used.

type SqlConnect added in v0.0.4

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

SqlConnect holds a database/sql DB instance (https://golang.org/pkg/database/sql/#DB) that can be shared within the application.

func NewSqlConnect added in v0.0.4

func NewSqlConnect(driver, dsn string, defaultTimeoutMs int, poolOptions *SqlPoolOptions) (*SqlConnect, error)

NewSqlConnect constructs a new SqlConnect instance.

Parameters: see #NewSqlConnectWithFlavor.

func NewSqlConnectWithFlavor added in v0.1.0

func NewSqlConnectWithFlavor(driver, dsn string, defaultTimeoutMs int, poolOptions *SqlPoolOptions, flavor DbFlavor) (*SqlConnect, error)

NewSqlConnectWithFlavor constructs a new SqlConnect instance.

Parameters:

  • driver : database driver name
  • dsn : data source name (format [username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN])
  • defaultTimeoutMs: default timeout for db operations, in milliseconds
  • poolOptions : connection pool options. If nil, default value is used
  • flavor : database flavor associated with the SqlConnect instance.

Return: the SqlConnect instance and error (if any). Note:

  • In case of connection error: this function returns the SqlConnect instance and the error.
  • Other error: this function returns (nil, error)

Available: since v0.1.0

func (*SqlConnect) Close added in v0.0.4

func (sc *SqlConnect) Close() error

Close closes the underlying 'sql.DB' instance.

func (*SqlConnect) Conn added in v0.0.4

func (sc *SqlConnect) Conn(ctx context.Context) (*sql.Conn, error)

Conn returns a single connection by either opening a new connection or returning an existing connection from the connection pool. Conn will block until either a connection is returned or ctx is canceled/timed-out.

Every 'Conn' must be returned to the database pool after use by calling 'Conn.Close'.

func (*SqlConnect) FetchRow added in v0.0.4

func (sc *SqlConnect) FetchRow(row *sql.Row, numCols int) ([]interface{}, error)

FetchRow copies the columns from the matched row into a slice and return it. If more than one row matches the query, FetchRow uses only the first row and discards the rest. If no row matches the query, FetchRow returns (nil,nil).

func (*SqlConnect) FetchRows added in v0.0.4

func (sc *SqlConnect) FetchRows(rows *sql.Rows) ([]map[string]interface{}, error)

FetchRows loads rows from database and transform to a slice of 'map[string]interface{}' where each column's name & value is a map entry. If no row matches the query, FetchRow returns (<empty slice>,nil).

Note: FetchRows does NOT call 'rows.close()' when done!

func (*SqlConnect) FetchRowsCallback added in v0.0.4

func (sc *SqlConnect) FetchRowsCallback(rows *sql.Rows, callback func(row map[string]interface{}, err error) bool) error

FetchRowsCallback loads rows from database. For each row, FetchRowsCallback transforms it to 'map[string]interface{}', where each column's name & value is a map entry, and passes the map to the callback function. FetchRowsCallback stops the loop when there is no more row to load or 'callback' function returns 'false'.

Note: FetchRowsCallback does NOT call 'rows.close()' when done!

func (*SqlConnect) GetDB added in v0.0.4

func (sc *SqlConnect) GetDB() *sql.DB

GetDB returns the underlying 'sql.DB' instance.

func (*SqlConnect) GetDbFlavor added in v0.1.0

func (sc *SqlConnect) GetDbFlavor() DbFlavor

GetDbFlavor returns the current database flavor associated with this SqlConnect.

Available: since v0.1.0

func (*SqlConnect) GetLocation added in v0.1.2

func (sc *SqlConnect) GetLocation() *time.Location

GetLocation returns the timezone location associated with this SqlConnect.

Available: since v0.1.2

func (*SqlConnect) IsConnected added in v0.0.4

func (sc *SqlConnect) IsConnected() bool

IsConnected returns true if the connection to the database is alive.

func (*SqlConnect) NewBackgroundContext deprecated added in v0.0.4

func (sc *SqlConnect) NewBackgroundContext(timeoutMs ...int) (context.Context, context.CancelFunc)

NewBackgroundContext is alias of NewContext.

Deprecated: since v0.2.0, use NewContext instead.

func (*SqlConnect) NewContext added in v0.2.0

func (sc *SqlConnect) NewContext(timeoutMs ...int) (context.Context, context.CancelFunc)

NewContext creates a new context with specified timeout in milliseconds. If there is no specified timeout, or timeout value is less than or equal to 0, the default timeout is used.

Available: since v0.2.0

func (*SqlConnect) Ping added in v0.0.4

func (sc *SqlConnect) Ping(ctx context.Context) error

Ping verifies a connection to the database is still alive, establishing a connection if necessary.

func (*SqlConnect) SetDbFlavor added in v0.1.0

func (sc *SqlConnect) SetDbFlavor(flavor DbFlavor) *SqlConnect

SetDbFlavor associates a database flavor with this SqlConnect.

Available: since v0.1.0

func (*SqlConnect) SetLocation added in v0.1.2

func (sc *SqlConnect) SetLocation(loc *time.Location) *SqlConnect

SetLocation associates a timezone location with this SqlConnect, used when parsing date/time data. Default value is time.UTC.

Available: since v0.1.2

type SqlPoolOptions added in v0.0.4

type SqlPoolOptions struct {
	/*
		Maximum amount of time a connection may be reused, default is 1 hour,
		see https://golang.org/pkg/database/sql/#DB.SetConnMaxLifetime
	*/
	ConnMaxLifetime time.Duration

	/*
		Maximum number of idle connections in the pool, default is 1,
		see https://golang.org/pkg/database/sql/#DB.SetMaxIdleConns
	*/
	MaxIdleConns int

	/*
		Maximum number of open connections to the database, default is 2,
		see https://golang.org/pkg/database/sql/#DB.SetMaxOpenConns
	*/
	MaxOpenConns int
}

SqlPoolOptions configures database connection pooling options.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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