database

package
v1.3.8 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2022 License: MIT Imports: 28 Imported by: 1

Documentation

Index

Constants

View Source
const (
	// Select indicates a SELECT statement triggered the error
	Select SQLQueryType = "SELECT"
	// Insert indicates an INSERT statement triggered the error
	Insert = "INSERT"
	// Delete indicates a DELETE statement triggered the error
	Delete = "DELETE"
	// Update indicates an UPDATE statement triggered the error
	Update = "UPDATE"
)
View Source
const (
	// TableExistenceQueryFormat returns a single row and column indicating that the table
	// exists and when it was created. Takes format vars 'table_schema' and 'table_name'
	// NOTE: 'as' clause MUST be there or MySQL will return TABLE_NAME for the column name and
	//  mapping will fail
	// NOTE: Do not use 'create_time' for existence check on tables as it can be NULL
	//  for partitioned tables and is always null in aurora
	TableExistenceQueryFormat = `SELECT TABLE_NAME as "table_name" ` +
		`FROM information_schema.tables` +
		`	WHERE table_schema = '%s'` +
		`	AND table_name = '%s' LIMIT 1;`

	// DefaultMaxTries documentation hur
	DefaultMaxTries = 10
)
View Source
const MaxLimit = 100

MaxLimit for records returned in an unbounded List request

Variables

This section is empty.

Functions

func AcquireDatabaseLock added in v1.2.0

func AcquireDatabaseLock(db *Database, name string, timeout time.Duration) (bool, errors.TracerError)

AcquireDatabaseLock with the specified name and timeout. Returns boolean indicating whether the lock was acquired or error on failure to execute. See: https://dev.mysql.com/doc/refman/5.7/en/locking-functions.html

func Bootstrap

func Bootstrap(db *Database, lines []string, logger log.Logger)

Bootstrap runs sql commands to import baseline data into the database

func CommitOrRollback

func CommitOrRollback(tx *sqlx.Tx, err error) errors.TracerError

CommitOrRollback will rollback on an errors.TracerError otherwise commit

func DatabaseToApiError added in v1.3.1

func DatabaseToApiError(primary qb.Table, dbError error) error

DatabaseToApiError handles conversion from a database error to a GRPC friendly error with code.

func EqualLogError added in v1.3.2

func EqualLogError(assert assertion, theError error, errString string, msgAndArgs ...interface{}) bool

EqualLogError asserts that a function returned an error (i.e. not `nil`) and that it is equal to the provided error, ignoring line number in the log prefix and any database error ids.

func IsNotFoundError added in v1.2.0

func IsNotFoundError(err error) bool

IsNotFoundError returns a boolean indicating that the passed error (can be nil) is of type *database.NotFoundError

func Migrate

func Migrate(migrations map[string]string, dbURL string)

Migrate ensures that the database is up to date Panics on error since this is an unrecoverable, fatal issue

func NewDataTooLongError

func NewDataTooLongError(action SQLQueryType, stmt string, err error, logger log.Logger) errors.TracerError

NewDataTooLongError logs the error and returns an instantiated DataTooLongError

func NewDatabaseConnectionError

func NewDatabaseConnectionError(err error) errors.TracerError

NewDatabaseConnectionError instantiates a DatabaseConnectionError with a stack trace

func NewDuplicateRecordError

func NewDuplicateRecordError(action SQLQueryType, stmt string, err error, logger log.Logger) errors.TracerError

NewDuplicateRecordError is returned when a records is created/updated with a duplicate primary key

func NewExecutionError

func NewExecutionError(action SQLQueryType, stmt string, err error, logger log.Logger) errors.TracerError

NewExecutionError logs the error and returns an ExecutionError

func NewInvalidForeignKeyError

func NewInvalidForeignKeyError(action SQLQueryType, stmt string, err error, logger log.Logger) errors.TracerError

NewInvalidForeignKeyError logs the error and returns an instantiated InvalidForeignKeyError

func NewNotAPointerError

func NewNotAPointerError() errors.TracerError

NewNotAPointerError instantiates a NotAPointerError with a stack trace

func NewNotFoundError

func NewNotFoundError() errors.TracerError

NewNotFoundError returns a NotFoundError with a stack trace

func NewSystemError

func NewSystemError(action SQLQueryType, stmt string, err error, logger log.Logger) errors.TracerError

NewSystemError logs the error and returns an ExecutionError

func NewUniqueConstraintError

func NewUniqueConstraintError(action SQLQueryType, stmt string, err error, logger log.Logger) errors.TracerError

NewUniqueConstraintError is returned when a record is created/updated with a duplicate primary key

func NewValidationError

func NewValidationError(msg string, subs ...interface{}) errors.TracerError

NewValidationError returns a ValidationError with a stack trace

func ReleaseDatabaseLock added in v1.2.0

func ReleaseDatabaseLock(db *Database, name string) errors.TracerError

ReleaseDatabaseLock with the specified name See: https://dev.mysql.com/doc/refman/5.7/en/locking-functions.html

func Reset

func Reset(migrations map[string]string, dbURL string)

Reset runs all rollback migrations for the database Panics on error since this is an unrecoverable, fatal issue This will essentially nuke your database. Only really useful for test scenario cleanup.

func TableExists added in v1.2.0

func TableExists(db *Database, schema, name string) (bool, error)

TableExists for the passed schema and table name on the passed database

func TranslateError

func TranslateError(err error, action SQLQueryType, stmt string, logger log.Logger) errors.TracerError

TranslateError converts a mysql or other obtuse errors into discrete explicit errors

Types

type Bootstrapper

type Bootstrapper interface {
	// ReadYaml reads a yaml file and exit on error
	ReadYaml(filename string, target interface{})
	// WriteYaml writes yaml to a file and exit on error
	WriteYaml(filename string, output interface{})
	// WriteSQL writes the sql version of a yaml file
	WriteSQL(filename string, output []string)
	// WriteConstants writes the constants for the data
	WriteConstants(filename string, output map[string]map[string]string)
	// Insert a record into the database
	Insert(record Record) error
	// UpsertQuery generates SQL to insert / update a record
	UpsertQuery(record Record) string
	// DB returns a *Database instances
	DB() *Database
	// TX returns the database transaction
	TX() *sqlx.Tx
	// FailOnError will rollback transaction and exit if an error is received
	FailOnError(err error)
}

Bootstrapper handles reading/writing yaml and sql files for data bootstrapping

func NewBootstrapper

func NewBootstrapper(db *Database) Bootstrapper

NewBootstrapper returns the primary implementation of the Bootstrapper interface

type Config

type Config interface {
	// DatabaseDialect of SQL
	DatabaseDialect() string
	// DatabaseConnection string for addressing the database
	DatabaseConnection() string
	// NumberOfRetries for the connection before failing
	NumberOfRetries() int
	// WaitBetweenRetries before trying again
	WaitBetweenRetries() time.Duration
}

Config defines the interface for a config to establish a database connection

type ConnectionError

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

ConnectionError is returned when unable to connect to database

func (*ConnectionError) Error

func (err *ConnectionError) Error() string

func (*ConnectionError) Trace

func (err *ConnectionError) Trace() []string

Trace returns the stack trace for the error

type DataTooLongError

type DataTooLongError struct {
	SQLExecutionError
}

DataTooLongError is returned when a mysql error #1406 occurs

type Database

type Database struct {
	*sqlx.DB
	Logger log.Logger
}

Database defines a connection to a database

func Initialize

func Initialize(config Config) *Database

Initialize establishes the database connection

func (*Database) Create

func (db *Database) Create(obj Record) errors.TracerError

Create initializes a Record and inserts it into the Database

func (*Database) CreateTx

func (db *Database) CreateTx(obj Record, tx *sqlx.Tx) errors.TracerError

CreateTx initializes a Record and inserts it into the Database

func (*Database) Delete

func (db *Database) Delete(obj Record) errors.TracerError

Delete removes a row from the database

func (*Database) DeleteTx

func (db *Database) DeleteTx(obj Record, tx *sqlx.Tx) errors.TracerError

DeleteTx removes a row from the database using a transaction

func (*Database) DeleteWhere

func (db *Database) DeleteWhere(obj Record, where *qb.ConditionExpression) errors.TracerError

DeleteWhere removes a row(s) from the database based on a supplied where clause

func (*Database) DeleteWhereTx

func (db *Database) DeleteWhereTx(obj Record, tx *sqlx.Tx, condition *qb.ConditionExpression) errors.TracerError

DeleteWhereTx removes row(s) from the database based on a supplied where clause in a transaction

func (*Database) List

func (db *Database) List(def Record, obj interface{}, options *ListOptions) errors.TracerError

List populates obj with a list of Records from the database

func (*Database) ListWhere

func (db *Database) ListWhere(meta Record, target interface{}, condition *qb.ConditionExpression, options *ListOptions) errors.TracerError

ListWhere populates obj with a list of Records from the database

func (*Database) ListWhereTx

func (db *Database) ListWhereTx(tx *sqlx.Tx, meta Record, target interface{}, condition *qb.ConditionExpression,
	options *ListOptions) errors.TracerError

ListWhereTx populates target with a list of Records from the database using the transaction

func (*Database) Read

func (db *Database) Read(obj Record, pk PrimaryKeyValue) errors.TracerError

Read populates a Record from the database

func (*Database) ReadOneWhere

func (db *Database) ReadOneWhere(obj Record, condition *qb.ConditionExpression) errors.TracerError

ReadOneWhere populates a Record from a custom where clause

func (*Database) ReadOneWhereTx

func (db *Database) ReadOneWhereTx(obj Record, tx *sqlx.Tx, condition *qb.ConditionExpression) errors.TracerError

ReadOneWhereTx populates a Record from a custom where clause using a transaction

func (*Database) ReadTx

func (db *Database) ReadTx(obj Record, pk PrimaryKeyValue, tx *sqlx.Tx) errors.TracerError

ReadTx populates a Record from the database using a transaction

func (*Database) Select

func (db *Database) Select(target interface{}, query *qb.SelectQuery) errors.TracerError

Select executes a given select query and populates the target

func (*Database) SelectList added in v1.2.4

func (db *Database) SelectList(target interface{}, query *qb.SelectQuery,
	options *ListOptions) errors.TracerError

SelectList of Records into target based upon the passed query

func (*Database) SelectListTx added in v1.2.4

func (db *Database) SelectListTx(tx *sqlx.Tx, target interface{}, query *qb.SelectQuery,
	options *ListOptions) errors.TracerError

SelectListTx of Records into target in a transaction based upon the passed query

func (*Database) SelectTx

func (db *Database) SelectTx(tx *sqlx.Tx, target interface{}, query *qb.SelectQuery) errors.TracerError

SelectTx executes a given select query and populates the target

func (*Database) Update

func (db *Database) Update(obj Record) errors.TracerError

Update replaces an entry in the database for the Record

func (*Database) UpdateTx

func (db *Database) UpdateTx(obj Record, tx *sqlx.Tx) errors.TracerError

UpdateTx replaces an entry in the database for the Record using a transaction

func (*Database) UpsertTx

func (db *Database) UpsertTx(obj Record, tx *sqlx.Tx) errors.TracerError

UpsertTx a new entry into the database for the Record

type DefaultRecord

type DefaultRecord struct{}

DefaultRecord implements the Key() as "id"

func (*DefaultRecord) Key

func (record *DefaultRecord) Key() string

Key returns "ID" as the default Primary Key

type DuplicateRecordError

type DuplicateRecordError struct {
	SQLExecutionError
}

DuplicateRecordError is returned when a mysql error #1062 occurs for a PrimaryKey

type InstanceConfig added in v1.1.3

type InstanceConfig struct {
	// Dialect of this instance
	Dialect string
	// Connection string for this instance
	Connection string
	// ConnectRetries is the number of times to retry connecting
	ConnectRetries int
	// ConnectRetryWait is the time to wait between connection retries
	ConnectRetryWait time.Duration
	// DeltaLockMaxTries is used as the maximum retries when attempting to get a Lock during Delta execution
	DeltaLockMaxTries int
	// DeltaLockMinimumCycle is used as the minimum cycle duration when attempting to get a Lock during Delta execution
	DeltaLockMinimumCycle time.Duration
	// DeltaLockMaxCycle is used as the maximum wait time between executions when attempting to get a Lock during Delta execution
	DeltaLockMaxCycle time.Duration
}

InstanceConfig is a simple struct that satisfies the Config interface

func (*InstanceConfig) DatabaseConnection added in v1.1.3

func (config *InstanceConfig) DatabaseConnection() string

DatabaseConnection string

func (*InstanceConfig) DatabaseDialect added in v1.1.3

func (config *InstanceConfig) DatabaseDialect() string

DatabaseDialect indicates the type of SQL this database uses

func (*InstanceConfig) MaxWaitBetweenDeltaLockRetries added in v1.3.0

func (config *InstanceConfig) MaxWaitBetweenDeltaLockRetries() time.Duration

WaitBetweenRetries when trying to connect to the database

func (*InstanceConfig) MinimumWaitBetweenDeltaLockRetries added in v1.3.0

func (config *InstanceConfig) MinimumWaitBetweenDeltaLockRetries() time.Duration

MinimumWaitBetweenDeltaLockRetries when trying to connect to the database

func (*InstanceConfig) NumberOfDeltaLockTries added in v1.3.0

func (config *InstanceConfig) NumberOfDeltaLockTries() int

NumberOfDeltaLockTries on a connection to the database before failing

func (*InstanceConfig) NumberOfRetries added in v1.1.4

func (config *InstanceConfig) NumberOfRetries() int

NumberOfRetries on a connection to the database before failing

func (*InstanceConfig) WaitBetweenRetries added in v1.1.5

func (config *InstanceConfig) WaitBetweenRetries() time.Duration

WaitBetweenRetries when trying to connect to the database

type InvalidForeignKeyError

type InvalidForeignKeyError struct {
	SQLExecutionError
}

InvalidForeignKeyError is returned when a mysql error #1452 occurs

type ListOptions

type ListOptions struct {
	Limit  uint
	Offset uint
}

ListOptions provide limit and filtering capabilities for the List function

func NewListOptions

func NewListOptions(limit uint, offset uint) *ListOptions

NewListOptions generates a ListOptions

type Model

type Model struct {
	Name         string
	PrimaryKey   string
	ReadColumns  []string
	WriteColumns []string
}

Model represents the basic table information from a DB Record

type NotAPointerError

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

NotAPointerError indicates that a record object isn't a pointer

func (*NotAPointerError) Error

func (err *NotAPointerError) Error() string

func (*NotAPointerError) Trace

func (err *NotAPointerError) Trace() []string

Trace returns the stack trace for the error

type NotFoundError

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

NotFoundError is returned when a query against the database fails

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

Error prints a NotFoundError

func (*NotFoundError) Trace

func (e *NotFoundError) Trace() []string

Trace returns the stack trace for the error

type PrimaryKeyValue

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

PrimaryKeyValue limits keys to string or int

func NewPrimaryKey

func NewPrimaryKey(value interface{}) (pk PrimaryKeyValue)

NewPrimaryKey returns a populated PrimaryKeyValue

func (PrimaryKeyValue) Value

func (pk PrimaryKeyValue) Value() interface{}

Value returns the string or integer value for a Record

type Record

type Record interface {
	// Initialize sets any expected values on a Record during Create
	Initialize()
	// PrimaryKey returns the value of the primary key of the Record
	PrimaryKey() PrimaryKeyValue
	// Key returns the name of the primary key of the Record
	Key() string
	// Meta returns the meta object for this Record
	Meta() qb.Table
}

Record defines a database enabled record

type SQLExecutionError

type SQLExecutionError struct {
	Action      SQLQueryType
	ReferenceID string

	Stmt   string
	ErrMsg string
	// contains filtered or unexported fields
}

SQLExecutionError is returned when a query against the database fails

func (*SQLExecutionError) Error

func (e *SQLExecutionError) Error() string

Error prints a ExecutionError

func (*SQLExecutionError) Trace

func (e *SQLExecutionError) Trace() []string

Trace returns the stack trace for the error

type SQLQueryType

type SQLQueryType string

SQLQueryType indicates the type of query being executed that caused and error

type SQLSystemError

type SQLSystemError struct {
	SQLExecutionError
}

SQLSystemError is returned when a database action fails

type StatusResult added in v1.2.0

type StatusResult struct {
	// Status as returned by a function call usually
	Status int `db:"STATUS"`
}

StatusResult is for capturing output from a function call on the database, you must use an 'AS STATUS' clause in your query in order for mapping to work correctly.

type TableNameResult added in v1.2.2

type TableNameResult struct {
	// TableName of the table
	TableName string `db:"table_name"`
}

TableNameResult is for holding the result row from the existence query

type UniqueConstraintError

type UniqueConstraintError struct {
	SQLExecutionError
}

UniqueConstraintError is returned when a mysql error #1062 occurs for a Unique constraint

type ValidationError

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

ValidationError is returned when a query against the database fails

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error prints a ValidationError

func (*ValidationError) Trace

func (e *ValidationError) Trace() []string

Trace returns the stack trace for the error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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