sql

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: May 8, 2024 License: MIT Imports: 10 Imported by: 1

README

SQL Module

ci go report codecov Deps PkgGoDev

SQL module based on database/sql.

Installation

go get github.com/ankorstore/yokai/sql

Documentation

This module provides a Driver, decorating database/sql compatible drivers, with a hooking mechanism.

Usage

The following database systems are supported:

To create a *sql.DB with the tracing and logging hooks:

package main

import (
	"database/sql"
	
	yokaisql "github.com/ankorstore/yokai/sql"
	"github.com/ankorstore/yokai/sql/hook/log"
	"github.com/ankorstore/yokai/sql/hook/trace"
)

func main() {
	// MySQL
	driver, _ := yokaisql.Register("mysql", trace.NewTraceHook(), log.NewLogHook())
	db, _ := sql.Open(driver, "user:password@tcp(localhost:3306)/db?parseTime=true")

	// Postgres
	driver, _ := yokaisql.Register("postgres", trace.NewTraceHook(), log.NewLogHook())
	db, _ := sql.Open(driver, "host=host port=5432 user=user password=password dbname=db sslmode=disable")

	// SQLite
	driver, _ := yokaisql.Register("sqlite", trace.NewTraceHook(), log.NewLogHook())
	db, _ := sql.Open(driver, ":memory:")
}

See database/sql documentation for more details.

Hooks

This module provides a hooking mechanism to add logic around the SQL operations.

Log hook

This module provides an LogHook, that you can use to automatically log the SQL operations:

package main

import (
	"database/sql"

	yokaisql "github.com/ankorstore/yokai/sql"
	"github.com/ankorstore/yokai/sql/hook/log"
	"github.com/rs/zerolog"
)

func main() {

	logHook := log.NewLogHook(
		log.WithLevel(zerolog.DebugLevel),        // SQL logs level, debug by default
		log.WithArguments(true),                  // SQL logs with SQL arguments, false by default
		log.WithExcludedOperations(               // SQL operations to exclude from logging, empty by default
			yokaisql.ConnectionPingOperation,
			yokaisql.ConnectionResetSessionOperation,
		),
	)

	driver, _ := yokaisql.Register("sqlite", logHook)
	db, _ := sql.Open(driver, ":memory:")
}
Trace hook

This module provides an TraceHook, that you can use to automatically trace the SQL operations:

package main

import (
	"database/sql"

	yokaisql "github.com/ankorstore/yokai/sql"
	"github.com/ankorstore/yokai/sql/hook/log"
	"github.com/ankorstore/yokai/sql/hook/trace"
	"github.com/rs/zerolog"
)

func main() {

	traceHook := trace.NewTraceHook(
		trace.WithArguments(true),                  // SQL traces with SQL arguments, false by default
		trace.WithExcludedOperations(               // SQL operations to exclude from tracing, empty by default
			yokaisql.ConnectionPingOperation,
			yokaisql.ConnectionResetSessionOperation,
		),
	)

	driver, _ := yokaisql.Register("sqlite", traceHook)
	db, _ := sql.Open(driver, ":memory:")
}
Custom hook

This module provides a Hook interface, that you can implement to extend the logic around SQL operations:

package main

import (
	"context"
	"database/sql"

	yokaisql "github.com/ankorstore/yokai/sql"
	"github.com/ankorstore/yokai/sql/hook/log"
	"github.com/ankorstore/yokai/sql/hook/trace"
	"github.com/rs/zerolog"
)

type CustomHook struct{}

func (h *CustomHook) Before(ctx context.Context, event *yokaisql.HookEvent) context.Context {
	// your custom logic before SQL operation
	
	return ctx
}

func (h *CustomHook) After(ctx context.Context, event *yokaisql.HookEvent) {
	// your custom logic after SQL operation
}

func main() {
	driver, _ := yokaisql.Register("sqlite", &CustomHook{})
	db, _ := sql.Open(driver, ":memory:")
}
Healthcheck

This module provides an SQLProbe, compatible with the healthcheck module:

package main

import (
	"context"

	yokaihc "github.com/ankorstore/yokai/healthcheck"
	yokaisql "github.com/ankorstore/yokai/sql"
	"github.com/ankorstore/yokai/sql/healthcheck"
)

func main() {
	driver, _ := yokaisql.Register("sqlite")
	db, _ := sql.Open(driver, ":memory:")

	checker, _ := yokaihc.NewDefaultCheckerFactory().Create(
		yokaihc.WithProbe(healthcheck.NewSQLProbe(db)),
	)

	checker.Check(context.Background(), yokaihc.Readiness)
}

This probe performs a ping to the configured database connection.

Documentation

Index

Constants

View Source
const DriverRegistrationPrefix = "yokai"

Variables

View Source
var (
	GlobalDriverRegistry DriverRegistry
	GlobalDriverFactory  DriverFactory
)

Functions

func ContainsOperation

func ContainsOperation(list []Operation, item Operation) bool

ContainsOperation returns true if a given Operation item is contained id a list of Operation.

func ConvertNamedValuesToValues

func ConvertNamedValuesToValues(namedValues []driver.NamedValue) []driver.Value

ConvertNamedValuesToValues converts a list of driver.NamedValue into a list of driver.Value.

func Register

func Register(name string, hooks ...Hook) (string, error)

Register registers a new Driver for a given name and an optional list of Hook.

Types

type Configuration

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

Configuration is the SQL components (driver, connector, connection, etc) configuration.

func NewConfiguration

func NewConfiguration(system System, hooks ...Hook) *Configuration

NewConfiguration returns a new Configuration.

func (*Configuration) Hooks

func (c *Configuration) Hooks() []Hook

Hooks returns the Configuration list of Hook.

func (*Configuration) System

func (c *Configuration) System() System

System returns the Configuration System.

type Connection

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

Connection is a SQL driver connection wrapping a driver.Conn.

func NewConnection

func NewConnection(base driver.Conn, configuration *Configuration) *Connection

NewConnection returns a new Connection.

func (*Connection) Begin

func (c *Connection) Begin() (driver.Tx, error)

Begin starts a transaction and returns a driver.Tx.

func (*Connection) BeginTx

func (c *Connection) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error)

BeginTx starts a transaction for a context and returns a driver.Tx.

func (*Connection) Close

func (c *Connection) Close() error

Close closes a connection.

func (*Connection) Exec

func (c *Connection) Exec(query string, args []driver.Value) (driver.Result, error)

Exec executes a query and returns a driver.Result.

func (*Connection) ExecContext

func (c *Connection) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error)

ExecContext executes a query for a context and returns a driver.Result.

func (*Connection) Ping

func (c *Connection) Ping(ctx context.Context) error

Ping pings a connection for context.

func (*Connection) Prepare

func (c *Connection) Prepare(query string) (driver.Stmt, error)

Prepare prepares a query and returns a driver.Stmt.

func (*Connection) PrepareContext

func (c *Connection) PrepareContext(ctx context.Context, query string) (driver.Stmt, error)

PrepareContext prepares a query for a context and returns a driver.Stmt.

func (*Connection) Query

func (c *Connection) Query(query string, args []driver.Value) (driver.Rows, error)

Query executes a query and returns a driver.Rows.

func (*Connection) QueryContext

func (c *Connection) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error)

QueryContext executes a query for a context and returns a driver.Rows.

func (*Connection) ResetSession

func (c *Connection) ResetSession(ctx context.Context) error

ResetSession resets a connection session for context.

type Connector

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

Connector is a SQL driver connector wrapping a driver.Connector.

func NewConnector

func NewConnector(dsn string, base driver.Connector, driver *Driver) *Connector

NewConnector returns a new Connector.

func (*Connector) Connect

func (c *Connector) Connect(ctx context.Context) (driver.Conn, error)

Connect returns a new driver.Conn.

func (*Connector) Driver

func (c *Connector) Driver() driver.Driver

Driver returns the Driver of the Connector.

type DefaultDriverFactory

type DefaultDriverFactory struct{}

DefaultDriverFactory is the default DriverFactory implementation.

func NewDefaultDriverFactory

func NewDefaultDriverFactory() *DefaultDriverFactory

NewDefaultDriverFactory returns a new DefaultDriverFactory.

func (*DefaultDriverFactory) Create

func (f *DefaultDriverFactory) Create(system System, hooks ...Hook) (*Driver, error)

Create creates a new Driver, for a provided System and an optional list of Hook.

type DefaultDriverRegistry

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

DefaultDriverRegistry is the default DriverRegistry implementation.

func NewDefaultDriverRegistry

func NewDefaultDriverRegistry() *DefaultDriverRegistry

NewDefaultDriverRegistry returns a new DefaultDriverRegistry.

func (*DefaultDriverRegistry) Add

func (r *DefaultDriverRegistry) Add(name string, driver *Driver) (err error)

Add adds and register a given Driver for a name.

func (*DefaultDriverRegistry) Get

func (r *DefaultDriverRegistry) Get(name string) (*Driver, error)

Get returns a registered driver for a given name.

func (*DefaultDriverRegistry) Has

func (r *DefaultDriverRegistry) Has(name string) bool

Has returns true is a driver is already registered for a given name.

type Driver

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

Driver is a SQL driver wrapping a driver.Driver.

func NewDriver

func NewDriver(base driver.Driver, configuration *Configuration) *Driver

NewDriver returns a new Driver.

func (*Driver) Base

func (d *Driver) Base() driver.Driver

Base returns the base driver.Driver of the Driver.

func (*Driver) Configuration

func (d *Driver) Configuration() *Configuration

Configuration returns the Configuration of the Driver.

func (*Driver) Open

func (d *Driver) Open(dsn string) (driver.Conn, error)

Open returns a new Connection.

func (*Driver) OpenConnector

func (d *Driver) OpenConnector(dsn string) (driver.Connector, error)

OpenConnector returns a new Connector.

type DriverFactory

type DriverFactory interface {
	Create(system System, hooks ...Hook) (*Driver, error)
}

DriverFactory is the interface for Driver factories.

type DriverRegistry

type DriverRegistry interface {
	Has(name string) bool
	Add(name string, driver *Driver) error
	Get(name string) (*Driver, error)
}

DriverRegistry is the interface for Driver registries.

type Hook

type Hook interface {
	Before(context.Context, *HookEvent) context.Context
	After(context.Context, *HookEvent)
}

Hook is the interface for database hooks.

type HookEvent

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

HookEvent is representing an event provided to a database Hook.

func NewHookEvent

func NewHookEvent(system System, operation Operation, query string, arguments interface{}) *HookEvent

NewHookEvent returns a new HookEvent.

func (*HookEvent) Arguments

func (e *HookEvent) Arguments() any

Arguments returns the HookEvent query arguments.

func (*HookEvent) Error

func (e *HookEvent) Error() error

Error returns the HookEvent error.

func (*HookEvent) LastInsertId

func (e *HookEvent) LastInsertId() int64

LastInsertId returns the HookEvent database last inserted id.

func (*HookEvent) Latency

func (e *HookEvent) Latency() (time.Duration, error)

Latency returns the HookEvent latency (duration between start and end times).

func (*HookEvent) Operation

func (e *HookEvent) Operation() Operation

Operation returns the HookEvent Operation.

func (*HookEvent) Query

func (e *HookEvent) Query() string

Query returns the HookEvent query.

func (*HookEvent) RowsAffected

func (e *HookEvent) RowsAffected() int64

RowsAffected returns the HookEvent database affected rows.

func (*HookEvent) SetError

func (e *HookEvent) SetError(err error) *HookEvent

SetError sets the HookEvent error.

func (*HookEvent) SetLastInsertId

func (e *HookEvent) SetLastInsertId(lastInsertId int64) *HookEvent

SetLastInsertId sets the HookEvent database last inserted id.

func (*HookEvent) SetRowsAffected

func (e *HookEvent) SetRowsAffected(rowsAffected int64) *HookEvent

SetRowsAffected sets the HookEvent database affected rows.

func (*HookEvent) Start

func (e *HookEvent) Start() *HookEvent

Start records the HookEvent start time.

func (*HookEvent) Stop

func (e *HookEvent) Stop() *HookEvent

Stop records the HookEvent stop time.

func (*HookEvent) System

func (e *HookEvent) System() System

System returns the HookEvent System.

type Operation

type Operation string

Operation is an enum for the supported database operations.

const (
	UnknownOperation                  Operation = "unknown"
	ConnectionBeginOperation          Operation = "connection:begin"
	ConnectionBeginTxOperation        Operation = "connection:begin-tx"
	ConnectionExecOperation           Operation = "connection:exec"
	ConnectionExecContextOperation    Operation = "connection:exec-context"
	ConnectionQueryOperation          Operation = "connection:query"
	ConnectionQueryContextOperation   Operation = "connection:query-context"
	ConnectionPrepareOperation        Operation = "connection:prepare"
	ConnectionPrepareContextOperation Operation = "connection:prepare-context"
	ConnectionPingOperation           Operation = "connection:ping"
	ConnectionResetSessionOperation   Operation = "connection:reset-session"
	ConnectionCloseOperation          Operation = "connection:close"
	StatementExecOperation            Operation = "statement:exec"
	StatementExecContextOperation     Operation = "statement:exec-context"
	StatementQueryOperation           Operation = "statement:query"
	StatementQueryContextOperation    Operation = "statement:query-context"
	TransactionCommitOperation        Operation = "transaction:commit"
	TransactionRollbackOperation      Operation = "transaction:rollback"
)

func FetchOperation

func FetchOperation(name string) Operation

FetchOperation returns an Operation for a given name.

func FetchOperations added in v1.1.0

func FetchOperations(names []string) []Operation

FetchOperations returns a list of Operation for a given list of names.

func (Operation) String

func (o Operation) String() string

String returns a string representation of the Operation.

type Statement

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

Statement is a SQL driver statement wrapping a driver.Stmt.

func NewStatement

func NewStatement(base driver.Stmt, ctx context.Context, query string, configuration *Configuration) *Statement

NewStatement returns a new Statement.

func (*Statement) Close

func (s *Statement) Close() error

Close closes the Statement.

func (*Statement) Exec

func (s *Statement) Exec(args []driver.Value) (driver.Result, error)

Exec executes a statement and returns a driver.Result.

func (*Statement) ExecContext

func (s *Statement) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error)

ExecContext executes a statement for a context and returns a driver.Result.

func (*Statement) NumInput

func (s *Statement) NumInput() int

NumInput returns the number of inputs of the Statement.

func (*Statement) Query

func (s *Statement) Query(args []driver.Value) (driver.Rows, error)

Query executes a statement and returns a driver.Rows.

func (*Statement) QueryContext

func (s *Statement) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error)

QueryContext executes a statement for a context and returns a driver.Rows.

type System

type System string

System is an enum for the supported database systems.

const (
	UnknownSystem  System = "unknown"
	SqliteSystem   System = "sqlite"
	MysqlSystem    System = "mysql"
	PostgresSystem System = "postgres"
)

func FetchSystem

func FetchSystem(name string) System

FetchSystem returns a System for a given name.

func (System) String

func (d System) String() string

String returns a string representation of the System.

type Transaction

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

Transaction is a SQL driver transaction wrapping a driver.Tx.

func NewTransaction

func NewTransaction(base driver.Tx, ctx context.Context, configuration *Configuration) *Transaction

NewTransaction returns a new Transaction.

func (*Transaction) Commit

func (t *Transaction) Commit() error

Commit commits the Transaction.

func (*Transaction) Rollback

func (t *Transaction) Rollback() error

Rollback rollbacks the Transaction.

Directories

Path Synopsis
hook
log

Jump to

Keyboard shortcuts

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