mapper

package module
v1.6.2 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2022 License: Apache-2.0 Imports: 3 Imported by: 1

README

Mapper

Golang Database Statement Mapper for managing multiple prepared statements.

Mapper is a Go package that allows for mapping multiple prepared SQL statements with name "keys". This can be used to manage resources and close all statements when your program closes.

Using Mapper is easy.

Taken from "examples/example.go"

package main

import (
    "database/sql"
    "fmt"

    "github.com/PurpleSec/mapper"

    _ "github.com/mattn/go-sqlite3"
)

func main() {
    db, err := sql.Open("sqlite3", ":memory:")
    if err != nil {
        panic(err)
    }

    m := &mapper.Map{Database: db}
    defer m.Close()

    err = m.Add(
        "create_table",
            `CREATE TABLE IF NOT EXISTS Testing1 (
            TestID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
            TestName VARCHAR(64) NOT NULL UNIQUE
        )`,
    )
    if err != nil {
        panic(err)
    }

    if _, err := m.Exec("create_table"); err != nil {
        panic(err)
    }

    err = m.Extend(
        map[string]string{
            "insert": "INSERT INTO Testing1(TestName) VALUES(?)",
            "select": "SELECT TestName FROM Testing1 WHERE TestID = ?",
        },
    )
    if err != nil {
        panic(err)
    }

    r, err := m.Exec("insert", "Hello World :D!")
    if err != nil {
        panic(err)
    }

    a, err := r.RowsAffected()
    if err != nil {
        panic(err)
    }
    fmt.Printf("Rows Affected: %d\n", a)

    q, err := m.Query("select", 1)
    if err != nil {
        panic(err)
    }

    var s string
    q.Next()
    if err := q.Scan(&s); err != nil {
        panic(err)
    }

    fmt.Printf("got %q\n", s)
    q.Close()
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidDB = &errval{s: "database cannot be nil"}

ErrInvalidDB is an error returned when the Database property of the Map is nil.

Functions

This section is empty.

Types

type Map

type Map struct {
	Database *sql.DB
	// contains filtered or unexported fields
}

Map is a struct that is used to track and manage multiple database *Stmt structs. Each statement can be mapped to a name that can be used again to recall or execute the statement.

This struct is safe for multiple co-current goroutine usage.

func New

func New(db *sql.DB) *Map

New is a shorthand function for "&Map{database: db}". Returns a new Map instance backed by the supplied database.

func (*Map) Add

func (m *Map) Add(name, query string) error

Add will prepare and add the specified query to the Map with the provided name.

This will only add the mapping if the 'Prepare' function is successful. Otherwise the prepare error will be returned.

This function does not allow for adding a mapping when one already exists. If a mapping with an overlapping name is attempted, an error will be returned before attempting to prepare the query.

func (*Map) AddContext

func (m *Map) AddContext(x context.Context, name, query string) error

AddContext will prepare and add the specified query to the Map with the provided name.

This will only add the mapping if the 'Prepare' function is successful. Otherwise the prepare error will be returned.

This function does not allow for adding a mapping when one already exists. If a mapping with an overlapping name is attempted, an error will be returned before attempting to prepare the query.

This function specifies a Context that can be used to interrupt and cancel the prepare calls.

func (*Map) Batch

func (m *Map) Batch(queries []string) error

Batch is a function that can be used to perform execute statements in a specific order.

This function will execute all the statements in the provided string array and will stop and return any errors that occur.

The passed query results will not be returned or parsed.

func (*Map) BatchContext

func (m *Map) BatchContext(x context.Context, queries []string) error

BatchContext is a function that can be used to perform execute statements in a specific order. This function will execute all the statements in the provided string array and will stop and return any errors that occur.

The passed query results will not be returned or parsed.

This function specifies a Context that can be used to interrupt and cancel the execute calls.

func (*Map) Close

func (m *Map) Close() error

Close will attempt to close all the contained database statements. This will bail on any errors that occur.

Multiple calls to close can be used to make sure that all statements are closed successfully. Note: this will also attempt to close the connected database if all statement closures are successful.

func (*Map) Contains

func (m *Map) Contains(name string) bool

Contains returns True if the name provided has an associated statement.

func (*Map) Exec

func (m *Map) Exec(name string, args ...interface{}) (sql.Result, error)

Exec will attempt to get the statement with the provided name and then attempt to call the 'Exec' function on the statement.

This provides the results of the Exec function.

func (*Map) ExecContext

func (m *Map) ExecContext(x context.Context, name string, args ...interface{}) (sql.Result, error)

ExecContext will attempt to get the statement with the provided name and then attempt to call the 'Exec' function on the statement.

This provides the results of the Exec function.

This function specifies a Context that can be used to interrupt and cancel the Exec function.

func (*Map) Extend

func (m *Map) Extend(data map[string]string) error

Extend will prepare and add all the specified queries in the provided map to the Map.

This will only add each mapping if the 'Prepare' function is successful. Otherwise the prepare error will be returned.

This function does not allow for adding a mapping when one already exists. If a mapping with an overlapping name is attempted, an error will be returned before attempting to prepare the query.

func (*Map) ExtendContext

func (m *Map) ExtendContext(x context.Context, data map[string]string) error

ExtendContext will prepare and add all the specified queries in the provided map to the Map.

This will only add each mapping if the 'Prepare' function is successful. Otherwise the prepare error will be returned.

This function does not allow for adding a mapping when one already exists. If a mapping with an overlapping name is attempted, an error will be returned before attempting to prepare the query.

This function specifies a Context that can be used to interrupt and cancel the prepare calls.

func (*Map) Get

func (m *Map) Get(name string) (*sql.Stmt, bool)

Get will attempt to return the statement that is associated with the provided name.

This function will return the statement and True if the mapping exists. Otherwise, the statement will be nil and the boolean will be False.

func (*Map) Len

func (m *Map) Len() int

Len returns the size of the internal mapping.

func (*Map) Query

func (m *Map) Query(name string, args ...interface{}) (*sql.Rows, error)

Query will attempt to get the statement with the provided name and then attempt to call the 'Query' function on the statement.

This provides the results of the Query function.

func (*Map) QueryContext

func (m *Map) QueryContext(x context.Context, name string, args ...interface{}) (*sql.Rows, error)

QueryContext will attempt to get the statement with the provided name and then attempt to call the 'Query' function on the statement.

This provides the results of the Query function.

This function specifies a Context that can be used to interrupt and cancel the Query function.

func (*Map) QueryRow

func (m *Map) QueryRow(name string, args ...interface{}) (*sql.Row, bool)

QueryRow will attempt to get the statement with the provided name and then attempt to call the 'QueryRow' function on the statement.

This function differs from the original 'QueryRow' statement as this provides a boolean to indicate if the provided named statement was found.

If the returned boolean is True, the result is not-nil and safe to use.

func (*Map) QueryRowContext

func (m *Map) QueryRowContext(x context.Context, name string, args ...interface{}) (*sql.Row, bool)

QueryRowContext will attempt to get the statement with the provided name and then attempt to call the 'QueryRow' function on the statement.

This function differs from the original 'QueryRow' statement as this provides a boolean to indicate if the provided named statement was found.

If the returned boolean is True, the result is not-nil and safe to use.

This function specifies a Context that can be used to interrupt and cancel the Query function.

func (*Map) Remove

func (m *Map) Remove(name string) bool

Remove will attempt to remove the statement with the provided name.

This function will return True if the mapping was found and removed. Otherwise the function will return false.

This will also close the removed statement.

Jump to

Keyboard shortcuts

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