sqle

package module
v0.0.0-...-a1608fc Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2024 License: Apache-2.0 Imports: 11 Imported by: 0

README

sqle GoDoc Build Status

The sqle package is an extension of the standard database/sql package.

Features

  • fully implements the database/sql interface;
  • it is fast, sometimes very fast (has a minimum overhead);
  • Scan method can take composite types as arguments, such as pointers to structures (including nested ones), maps and slices;
  • Columns and ColumnTypes methods cache the returned result.

Prerequisites

This package requires Go 1.8 or later.

Installation

go get -u github.com/lazada/sqle

Usage

There are two ways of using this package:

  1. by replacing standard database/sql package with this package in your imports;
  2. by wrapping specific standard database/sql objects using the Wrap function.

Examples

Additional examples of usage are available in rows_test.go, row_test.go and wrap_test.go.

Working with structures

As it was:

import "database/sql"

type User struct {
    Id      int32
    Name    string
    Email   string
    Created time.Time
    Updated time.Time
}

db, err := sql.Open(`sqlite3`, `testdata/testdata.db`)
if err != nil {
    log.Fatalln(err)
}
user := new(User)

err = db.QueryRowContext(ctx, `SELECT * FROM users WHERE id = ?`, userId).
    Scan(&user.Id, &user.Name, &user.Email, &user.Created, &user.Updated)
if err != nil {
    log.Fatalln(err)
}

It is now:

import sql "github.com/lazada/sqle"

type User struct {
	Id      int32     `sql:"id"`
	Name    string    `sql:"name"`
	Email   string    `sql:"email"`
	Created time.Time `sql:"created"`
	Updated time.Time `sql:"updated"`
}

db, err := sql.Open(`sqlite3`, `testdata/testdata.db`)
if err != nil {
    log.Fatalln(err)
}
user := new(User)

err = db.QueryRowContext(ctx, `SELECT * FROM users WHERE id = ?`, userId).Scan(user)
if err != nil {
    log.Fatalln(err)
}
Working with maps

As it was (simplified example):

import "database/sql"

db, err := sql.Open(`sqlite3`, `testdata/testdata.db`)
if err != nil {
    log.Fatalln(err)
}
var (
    userId                   int32
    userName, userEmail      string
    userCreated, userUpdated time.Time
)
err = db.QueryRowContext(ctx, `SELECT * FROM users WHERE id = ?`, userId).
    Scan(&userId, &userName, &userEmail, &userCreated, &userUpdated)
if err != nil {
    log.Fatalln(err)
}
user := map[string]interface{}{
    `id`:      userId,
    `name`:    userName,
    `email`:   userEmail,
    `created`: userCreated,
    `updated`: userUpdated,
}

It is now:

import sql "github.com/lazada/sqle"

db, err := sql.Open(`sqlite3`, `testdata/testdata.db`)
if err != nil {
    log.Fatalln(err)
}
user := make(map[string]interface{})

err = db.QueryRowContext(ctx, `SELECT * FROM users WHERE id = ?`, userId).Scan(user)
if err != nil {
    log.Fatalln(err)
}

Documentation

Overview

`sqle` package is an extension of the standard `database/sql` package

Features

  1. fully implements the `database/sql` interface.
  2. it is fast, sometimes very fast (has a minimum overhead).
  3. `Scan` method can take composite types as arguments, such as structures (including nested ones), maps and slices.
  4. `Columns` and `ColumnTypes` methods cache the returned result.

Installation

go get -u github.com/lazada/sqle

Usage import sql "github.com/lazada/sqle"

 type User struct {
		Id      int32     `sql:"id"`
		Name    string    `sql:"name"`
		Email   string    `sql:"email"`
		Created time.Time `sql:"created"`
		Updated time.Time `sql:"updated"`
 }

 db, err := sql.Open(`sqlite3`, `testdata/testdata.db`)
 if err != nil {
	  log.Fatalln(err)
 }
 user := new(User)

 db.QueryRowContext(ctx, `SELECT * FROM users WHERE id = ?`, userId).Scan(user)

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrSrcNotPtr   = errors.New(`sqle: source is not a pointer`)
	ErrSrcNotPtrTo = errors.New(`sqle: source is not a pointer to a structure`)
	ErrNilCtor     = errors.New(`sqle: constructor is nil`)
	ErrCtorRetNil  = errors.New(`sqle: constructor returned nil pointer`)
)
View Source
var (
	ErrMiss = errors.New(`miss`)
)

Functions

func InStrictMode

func InStrictMode(opt *dbOptions) error

InStrictMode places the DB into strict mode.

func Wrap

func Wrap(object interface{}, options ...DBOption) (_ interface{}, err error)

Wrap converts objects from the standard `database/sql` to the coresponding `sqle` objects.

Types

type Aliases

type Aliases interface {
	Aliases() []string
	Numerable
}

type CachedConvention

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

func NewCachedConvention

func NewCachedConvention(conv NamingConvention) *CachedConvention

func (*CachedConvention) Name

func (c *CachedConvention) Name(name string) string

func (*CachedConvention) Reset

func (c *CachedConvention) Reset() error

type CamelConvention

type CamelConvention struct{}

func (*CamelConvention) Name

func (n *CamelConvention) Name(name string) string

func (*CamelConvention) Reset

func (n *CamelConvention) Reset() error

type Conn

type Conn struct {
	*sql.Conn
	// contains filtered or unexported fields
}

Conn represents a single database session rather a pool of database sessions. Prefer running queries from DB unless there is a specific need for a continuous single database session.

A Conn must call Close to return the connection to the database pool and may do so concurrently with a running query.

After a call to Close, all operations on the connection fail with sql.ErrConnDone.

func (*Conn) BeginTx

func (c *Conn) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)

BeginTx starts a transaction.

The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled.

The provided sql.TxOptions is optional and may be nil if defaults should be used. If a non-default isolation level is used that the driver doesn't support, an error will be returned.

func (*Conn) PrepareContext

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

PrepareContext creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement. The caller must call the statement's Close method when the statement is no longer needed.

The provided context is used for the preparation of the statement, not for the execution of the statement.

func (*Conn) QueryContext

func (c *Conn) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)

QueryContext executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

func (*Conn) QueryRowContext

func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row

QueryRowContext executes a query that is expected to return at most one row. QueryRowContext always returns a non-nil value. Errors are deferred until Row's Scan method is called. If the query selects no rows, the *Row's Scan will return sql.ErrNoRows. Otherwise, the *Row's Scan scans the first selected row and discards the rest.

type DB

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

DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines.

The sql package creates and frees connections automatically; it also maintains a free pool of idle connections. If the database has a concept of per-connection state, such state can only be reliably observed within a transaction. Once DB.Begin is called, the returned Tx is bound to a single connection. Once Commit or Rollback is called on the transaction, that transaction's connection is returned to DB's idle connection pool. The pool size can be controlled with SetMaxIdleConns.

func Open

func Open(driver, dsn string, options ...DBOption) (*DB, error)

Open opens a database specified by its database driver name and a driver-specific data source name, usually consisting of at least a database name and connection information.

Most users will open a database via a driver-specific connection helper function that returns a *DB. No database drivers are included in the Go standard library. See https://golang.org/s/sqldrivers for a list of third-party drivers.

Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call Ping.

The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

func (*DB) Begin

func (db *DB) Begin() (*Tx, error)

Begin starts a transaction. The default isolation level is dependent on the driver.

func (*DB) BeginTx

func (db *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)

BeginTx starts a transaction.

The provided context is used until the transaction is committed or rolled back. If the context is canceled, the sql package will roll back the transaction. Tx.Commit will return an error if the context provided to BeginTx is canceled.

The provided TxOptions is optional and may be nil if defaults should be used. If a non-default isolation level is used that the driver doesn't support, an error will be returned.

func (*DB) Conn

func (db *DB) Conn(ctx context.Context) (*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. Queries run on the same Conn will be run in the same database session.

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

func (*DB) Prepare

func (db *DB) Prepare(query string) (*Stmt, error)

Prepare creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement. The caller must call the statement's Close method when the statement is no longer needed.

func (*DB) PrepareContext

func (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error)

PrepareContext creates a prepared statement for later queries or executions. Multiple queries or executions may be run concurrently from the returned statement. The caller must call the statement's Close method when the statement is no longer needed.

The provided context is used for the preparation of the statement, not for the execution of the statement.

func (*DB) Query

func (db *DB) Query(query string, args ...interface{}) (*Rows, error)

Query executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

func (*DB) QueryContext

func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)

QueryContext executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

func (*DB) QueryRow

func (db *DB) QueryRow(query string, args ...interface{}) *Row

QueryRow executes a query that is expected to return at most one row. QueryRow always returns a non-nil value. Errors are deferred until Row's Scan method is called.

func (*DB) QueryRowContext

func (db *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row

QueryRowContext executes a query that is expected to return at most one row. QueryRowContext always returns a non-nil value. Errors are deferred until Row's Scan method is called.

type DBOption

type DBOption func(*dbOptions) error

func WithMapper

func WithMapper(mapper *Mapper) DBOption

WithMapper

type LowerConvention

type LowerConvention struct{}

func (*LowerConvention) Name

func (n *LowerConvention) Name(name string) string

func (*LowerConvention) Reset

func (n *LowerConvention) Reset() error

type Mapper

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

func NewMapper

func NewMapper(tag string, conv NamingConvention) *Mapper

func (*Mapper) Aliases

func (m *Mapper) Aliases(src interface{}) ([]string, error)

func (*Mapper) Pointers

func (m *Mapper) Pointers(src interface{}, dest []interface{}, aliases []string) ([]interface{}, int, error)

func (*Mapper) Tag

func (m *Mapper) Tag() string

type NamingConvention

type NamingConvention interface {
	Name(string) string
	Reset() error
}

type NoopConvention

type NoopConvention struct{}

func (*NoopConvention) Name

func (n *NoopConvention) Name(name string) string

func (*NoopConvention) Reset

func (n *NoopConvention) Reset() error

type Numerable

type Numerable interface {
	Num() int
}

type Pointers

type Pointers interface {
	Pointers([]interface{}, []string) ([]interface{}, int)
	Numerable
}

type Row

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

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

func (*Row) Scan

func (r *Row) Scan(dest ...interface{}) (err error)

Scan copies the columns from the matched row into the values pointed at by dest. See the documentation on Rows.Scan for details. If more than one row matches the query, Scan uses the first row and discards the rest. If no row matches the query, Scan returns sql.ErrNoRows.

type Rows

type Rows struct {
	*sql.Rows
	// contains filtered or unexported fields
}

Rows is the result of a query. Its cursor starts before the first row of the result set.

func (*Rows) ColumnTypes

func (r *Rows) ColumnTypes() ([]*sql.ColumnType, error)

ColumnTypes returns column information such as column type, length, and nullable. Some information may not be available from some drivers.

func (*Rows) Columns

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

Columns returns the column names. Columns returns an error if the rows are closed, or if the rows are from QueryRow and there was a deferred error.

func (*Rows) Scan

func (r *Rows) Scan(dest ...interface{}) (err error)

Scan copies the columns in the current row into the values pointed at by dest.

type SnakeConvention

type SnakeConvention struct{}

func (*SnakeConvention) Name

func (n *SnakeConvention) Name(name string) string

func (*SnakeConvention) Reset

func (n *SnakeConvention) Reset() error

type Stmt

type Stmt struct {
	*sql.Stmt
	// contains filtered or unexported fields
}

Stmt is a prepared statement. A Stmt is safe for concurrent use by multiple goroutines.

func (*Stmt) Query

func (s *Stmt) Query(args ...interface{}) (*Rows, error)

Query executes a prepared query statement with given arguments and returns the query results as *Rows.

func (*Stmt) QueryContext

func (s *Stmt) QueryContext(ctx context.Context, args ...interface{}) (*Rows, error)

QueryContext executes a prepared query statement with given arguments and returns the query results as *Rows.

func (*Stmt) QueryRow

func (s *Stmt) QueryRow(args ...interface{}) *Row

QueryRow executes a prepared query statement with the given arguments. If an error occurs during the execution of the statement, that error will be returned by a call to Scan on the returned *Row, which is always non-nil. If the query selects no rows, the *Row's Scan will return sql.ErrNoRows. Otherwise, the *Row's Scan scans the first selected row and discards the rest.

func (*Stmt) QueryRowContext

func (s *Stmt) QueryRowContext(ctx context.Context, args ...interface{}) *Row

QueryRowContext executes a prepared query statement with the given arguments. If an error occurs during the execution of the statement, that error will be returned by a call to Scan on the returned *Row, which is always non-nil. If the query selects no rows, the *Row's Scan will return sql.ErrNoRows. Otherwise, the *Row's Scan scans the first selected row and discards the rest.

type Tx

type Tx struct {
	*sql.Tx
	// contains filtered or unexported fields
}

Tx is an in-progress database transaction.

A transaction must end with a call to Commit or Rollback.

After a call to Commit or Rollback, all operations on the transaction fail with ErrTxDone.

The statements prepared for a transaction by calling the transaction's Prepare or Stmt methods are closed by the call to Commit or Rollback.

func (*Tx) Prepare

func (tx *Tx) Prepare(query string) (*Stmt, error)

Prepare creates a prepared statement for use within a transaction.

The returned statement operates within the transaction and can no longer be used once the transaction has been committed or rolled back.

To use an existing prepared statement on this transaction, see Tx.Stmt.

func (*Tx) PrepareContext

func (tx *Tx) PrepareContext(ctx context.Context, query string) (*Stmt, error)

Prepare creates a prepared statement for use within a transaction.

The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back.

To use an existing prepared statement on this transaction, see Tx.Stmt.

The provided context will be used for the preparation of the context, not for the execution of the returned statement. The returned statement will run in the transaction context.

func (*Tx) Query

func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error)

Query executes a query that returns rows, typically a SELECT.

func (*Tx) QueryContext

func (tx *Tx) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error)

QueryContext executes a query that returns rows, typically a SELECT.

func (*Tx) QueryRow

func (tx *Tx) QueryRow(query string, args ...interface{}) *Row

QueryRow executes a query that is expected to return at most one row. QueryRow always returns a non-nil value. Errors are deferred until Row's Scan method is called.

func (*Tx) QueryRowContext

func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row

QueryRowContext executes a query that is expected to return at most one row. QueryRowContext always returns a non-nil value. Errors are deferred until Row's Scan method is called.

func (*Tx) Stmt

func (tx *Tx) Stmt(stmt *sql.Stmt) *Stmt

Stmt returns a transaction-specific prepared statement from an existing statement. The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back.

func (*Tx) StmtContext

func (tx *Tx) StmtContext(ctx context.Context, stmt *sql.Stmt) *Stmt

StmtContext returns a transaction-specific prepared statement from an existing statement. The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back.

type UpperConvention

type UpperConvention struct{}

func (*UpperConvention) Name

func (n *UpperConvention) Name(name string) string

func (*UpperConvention) Reset

func (n *UpperConvention) Reset() error

type Values

type Values interface {
	Values([]interface{}, []string) ([]interface{}, int)
	Numerable
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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