raptor

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2024 License: MIT Imports: 14 Imported by: 0

README

Raptor

Raptor is a lightweight SQLite3 wrapper for Go programming language. It provides an easy-to-use interface for working with SQLite3 databases.

Features

  • Simple and easy-to-use interface.
  • Safe and secure, uses parameterized queries to prevent SQL injection attacks.
  • Supports transactions with savepoints.
  • Allows custom logging of SQL queries.

Getting Started

To get started, install the package using go get.

go get github.com/maddiesch/go-raptor

Then, import the package in your code:

import "github.com/maddiesch/go-raptor"

You can then create a new connection to a SQLite3 database using the New function:

db, err := raptor.New("database.db")
if err != nil {
    // handle error
}
defer db.Close()

Usage

You can execute SQL queries on the database using the Exec and Query methods:

// Exec a query that doesn't return any rows
result, err := db.Exec(context.Background(), "INSERT INTO users (name, age) VALUES (?, ?)", "John Doe", 42)
if err != nil {
    // handle error
}

// Query rows from the database
rows, err := db.Query(context.Background(), "SELECT name, age FROM users WHERE age > ?", 30)
if err != nil {
    // handle error
}
defer rows.Close()

// Iterate over the rows
for rows.Next() {
    var name string
    var age int
    if err := rows.Scan(&name, &age); err != nil {
        // handle error
    }
    // do something with name and age
}
if err := rows.Err(); err != nil {
    // handle error
}

You can also execute a query that returns a single row using the QueryRow method:

// Query a single row from the database
row := db.QueryRow(context.Background(), "SELECT name, age FROM users WHERE id = ?", 1)

// Scan the values from the row
var name string
var age int
if err := row.Scan(&name, &age); err != nil {
    // handle error
}
// do something with name and age

Transactions

Raptor supports transactions with savepoints. You can execute a transaction using the Transact method:

err := db.Transact(context.Background(), func(tx raptor.DB) error {
    // Exec some queries
    if _, err := tx.Exec(context.Background(), "INSERT INTO users (name, age) VALUES (?, ?)", "John Doe", 42); err != nil {
        return err
    }
    if _, err := tx.Exec(context.Background(), "UPDATE users SET age = ? WHERE name = ?", 43, "John Doe"); err != nil {
        return err
    }
    return nil
})
if err != nil {
    // handle error
}

Inside the transaction, you can use the Exec, Query, and QueryRow methods as usual.

Documentation

Overview

Package raptor provides a simple and easy-to-use interface for working with SQLite3 databases.

Index

Constants

View Source
const (
	// DriverName is the name of the SQLite3 driver.
	DriverName = "sqlite"
)

Variables

View Source
var (
	ErrTransactionAlreadyStarted = errors.New("transaction already started")
	ErrTransactionNotRunning     = errors.New("transaction not running")
	ErrTxRollback                = errors.New("transaction rollback") // Can be returned from a transaction to rollback the transaction. Will not be returned to the caller
)
View Source
var (
	ErrRequirePointer = errors.New("raptor: unmarshal destination must be a pointer")
	ErrRequireStruct  = errors.New("raptor: unmarshal destination must be a struct")
)
View Source
var (
	ErrNoRows = sql.ErrNoRows
)

Functions

func CreateSlogArg added in v0.10.0

func CreateSlogArg(i int64, v any) slog.Attr

func GetRecordValue

func GetRecordValue[T any](record Record, key string) (val T, found bool)

func GetRecordValueLossy

func GetRecordValueLossy[T any](record Record, key string) (val T)

func Transact added in v0.10.0

func Transact(ctx context.Context, db TxBroker, fn func(DB) error) error

func TransactV added in v0.10.0

func TransactV[V any](ctx context.Context, db TxBroker, fn func(DB) (V, error)) (V, error)

func TransactV2 added in v0.10.0

func TransactV2[V1, V2 any](ctx context.Context, db TxBroker, fn func(DB) (V1, V2, error)) (V1, V2, error)

func UnmarshalRow

func UnmarshalRow(s Scanner, dest any) error

Types

type Conn

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

Conn represents a connection to a SQLite3 database.

func New

func New(source string) (*Conn, error)

New opens a new database connection

func (*Conn) Close

func (c *Conn) Close() error

Close the database connection and perform any necessary cleanup

Once close is called, new queries will be rejected. Close will block until all outstanding queries have completed.

func (*Conn) Exec

func (c *Conn) Exec(ctx context.Context, query string, args ...any) (Result, error)

Exec perform a query on the database. It will not return any rows. e.g. insert or delete

func (*Conn) ExecStatement added in v0.2.0

func (c *Conn) ExecStatement(ctx context.Context, statement generator.Generator) (Result, error)

func (*Conn) Ping

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

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

func (*Conn) Query

func (c *Conn) Query(ctx context.Context, query string, args ...any) (*Rows, error)

func (*Conn) QueryRow

func (c *Conn) QueryRow(ctx context.Context, query string, args ...any) *Row

func (*Conn) QueryRowStatement

func (c *Conn) QueryRowStatement(ctx context.Context, statement generator.Generator) *Row

func (*Conn) QueryStatement

func (c *Conn) QueryStatement(ctx context.Context, statement generator.Generator) (*Rows, error)

func (*Conn) SetLogger

func (c *Conn) SetLogger(l QueryLogger)

func (*Conn) SetQueryLogger added in v0.9.0

func (c *Conn) SetQueryLogger(l QueryLogger)

SetLogger assigns a logger instance to the connection.

func (*Conn) Transact

func (c *Conn) Transact(ctx context.Context, fn func(DB) error) error

type DB

type DB interface {
	Executor
	Querier
	TxBroker
}

DB defines a standard set of interfaces that allow CRUD operations on a database.

type Executor

type Executor interface {
	Exec(context.Context, string, ...any) (Result, error)
}

Executor defines an interface for executing queries that don't return rows.

type Pool added in v0.9.0

type Pool struct {
	pool.Pool[*Conn]
	// contains filtered or unexported fields
}

Pool implements a thread-safe pool of database connections.

It works as a single-writer multi-reader connection.

func NewPool added in v0.9.0

func NewPool(size int64, fn func(context.Context) (*Conn, error)) *Pool

Create a new pool with the given number of maximum connections.

func (*Pool) Exec added in v0.9.0

func (p *Pool) Exec(ctx context.Context, query string, args ...any) (Result, error)

func (*Pool) Query added in v0.9.0

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

func (*Pool) QueryRow added in v0.9.0

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

func (*Pool) Transact added in v0.9.0

func (p *Pool) Transact(ctx context.Context, fn func(DB) error) error

type Querier

type Querier interface {
	Query(context.Context, string, ...any) (*Rows, error)
	QueryRow(context.Context, string, ...any) *Row
}

Querier defines an interface for executing queries that return rows from the database.

type QueryLogger

type QueryLogger interface {
	LogQuery(context.Context, string, []any)
}

QueryLogger provides a standard interface for logging all SQL queries sent to Raptor

func NewNoopQueryLogger

func NewNoopQueryLogger() QueryLogger

NewNoopQueryLogger creates a new QueryLogger that doesn't log any queries.

func NewQueryLogger

func NewQueryLogger(w io.Writer) QueryLogger

NewQueryLogger creates a new QueryLogger that logs queries to an io.Writer.

func NewSLogFuncQueryLogger added in v0.8.0

func NewSLogFuncQueryLogger(fn SLogLoggerFunc) QueryLogger

type Record

type Record map[string]any

Record represents a Column/Value map for a row in the database.

func MarshalObject added in v0.4.0

func MarshalObject(obj any) (Record, error)

MarshalObject converts the given Struct into a Database Record map.

It used the `db` tag to map struct fields names to database column names.

func ScanAllRecord

func ScanAllRecord(r *Rows) ([]Record, error)

func ScanRecord

func ScanRecord(s Scanner) (Record, error)

func (Record) GetBool

func (r Record) GetBool(col string) bool

func (Record) GetInt

func (r Record) GetInt(col string) int64

func (Record) GetString

func (r Record) GetString(col string) string

func (Record) GetTime

func (r Record) GetTime(col string) time.Time

type RecordMarshaler

type RecordMarshaler interface {
	MarshalRecord() (Record, error)
}

type RecordUnmarshaler

type RecordUnmarshaler interface {
	UnmarshalRecord(Record) error
}

type Result

type Result interface {
	sql.Result
}

A Result summarizes an executed SQL command.

func ExecStatement added in v0.2.0

func ExecStatement(ctx context.Context, e Executor, stmt generator.Generator) (Result, error)

type Row

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

Row is the result of calling QueryRow to select a single row.

func QueryRowStatement added in v0.2.0

func QueryRowStatement(ctx context.Context, q Querier, stmt generator.Generator) *Row

func (*Row) Columns

func (r *Row) Columns() ([]string, error)

func (*Row) Err

func (r *Row) Err() error

func (*Row) Scan

func (r *Row) Scan(dest ...any) error

type Rows

type Rows struct {
	*sql.Rows
}

Rows is the result of a query. See sql.Rows for more information.

func QueryStatement added in v0.2.0

func QueryStatement(ctx context.Context, q Querier, stmt generator.Generator) (*Rows, error)

type SLogLoggerFunc added in v0.7.0

type SLogLoggerFunc func(context.Context, string, ...any)

type Scanner

type Scanner interface {
	Scan(...any) error
	Columns() ([]string, error)
}

type TxBroker

type TxBroker interface {
	Transact(context.Context, func(DB) error) error
}

TxBroker defines an interface for performing a transaction.

type TxRollbackError

type TxRollbackError struct {
	Underlying error
	Rollback   error
}

TxRollbackError is returned when a transaction is rolled back and the rollback also returns an error.

func (*TxRollbackError) Error

func (e *TxRollbackError) Error() string

Directories

Path Synopsis
internal
Package kv provides a simple key-value store backed by a Raptor SQLite database.
Package kv provides a simple key-value store backed by a Raptor SQLite database.

Jump to

Keyboard shortcuts

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