sqlw

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2024 License: MIT Imports: 10 Imported by: 9

README

sqlw - raw and simple wrapped std sql

Doc Go Report Card MIT licensed

Install

go get github.com/lesismal/sqlw

Usage

Define Model

Noted:

  1. The db tags of the struct are used to map struct fields to sql table fields in our insert/update/select operations.
  2. If you want to use some tools to auto-generate structs or sql tables but the tools use different struct tag names, you can set the tag when sqlw.Open, or modify it using db.SetTag().
type Model struct {
	Id int64  `db:"id"`
	I  int64  `db:"i"`
	S  string `db:"s"`
}
Open DB
import (
    _ "github.com/go-sql-driver/mysql"
    "github.com/lesismal/sqlw"
)

// "db" is Model struct tag name, if you want to use some tools to auto-generate structs or sql tables, 
// you can set the tag name according to your tools.
db, err := sqlw.Open("mysql", SqlConnStr, "db")
if err != nil {
    // handle err
}
Transaction
tx, err := db.Begin()
if err != nil {
    // handle err
}
defer tx.Rollback()

// curd logic

err = tx.Commit()
if err != nil {
    // handle err
}
Prepare/Stmt
stmt, err := db.Prepare(`your sql`)
if err != nil {
    // handle err
}

// curd logic using stmt
Insert One Records
model := Model{
    I: 1,
    S: "str_1",
}

result, err := db.Insert("insert into sqlw_test.sqlw_test", &model)
// result, err := db.Insert("insert into sqlw_test.sqlw_test(i,s)", &model) // insert the specified fields
if err != nil {
    log.Panic(err)
}
log.Println("sql:", result.Sql())
Insert Multi Records
var models []*Model
for i:=0; i<3; i++{
    models = append(models, &Model{
        I: i,
        S: fmt.Sprintf("str_%v", i),
    })
}

result, err := db.Insert("insert into sqlw_test.sqlw_test", models)
// result, err := db.Insert("insert into sqlw_test.sqlw_test(i,s)", models) // insert the specified fields
if err != nil {
    log.Panic(err)
}
log.Println("sql:", result.Sql())
Delete
deleteId := 1
result, err := db.Delete("delete from sqlw_test.sqlw_test where id=?", deleteId)
if err != nil {
    log.Panic(err)
}
log.Println("sql:", result.Sql())
Update
m := Model{
    I: 10,
    S: "str_10",
}

updateId := 1
result, err := db.Update("update sqlw_test.sqlw_test set i=?, s=? where id=?", &m, updateId)
if err != nil {
    log.Panic(err)
}
log.Println("sql:", result.Sql())
Select One Record
var model Model
selectId := 1
result, err := db.Select(&model, "select * from sqlw_test.sqlw_test where id=?", selectId)
// result, err := db.Select(&model, "select (i,s) from sqlw_test.sqlw_test where id=?", selectId) // select the specified fields
if err != nil {
    log.Panic(err)
}
log.Println("model:", model)
log.Println("sql:", result.Sql())
Select Multi Records
var models []*Model // type []Model is also fine
result, err = db.Select(&models, "select * from sqlw_test.sqlw_test")
// result, err = db.Select(&models, "select (i,s) from sqlw_test.sqlw_test") // select the specified fields
if err != nil {
    log.Panic(err)
}
for i, v := range models {
    log.Printf("models[%v]: %v", i, v)
}
log.Println("sql:", result.Sql())
Get RawSql

All Query/QueryRow/Exec/Insert/Delete/Update/Select related funcs of sqlw.DB/Tx/Stmt return (sqlw.Result, error). The sqlw.Result would always be a non-nil value to help users getting the raw sql, we can use sqlw.Result.Sql() to print it out.

For example:

result, err := db.Insert(`insert into t(a,b) values(?,?)`, 1, 2)
if err != nil {
    // handle err
}
fmt.Println("sql:", result.Sql())

Output:

sql: insert into t(a,b) values(?,?), [1, 2]
For More Examples

Please refer to: sqlw_examples

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound = errors.New("not found")
)

Functions

This section is empty.

Types

type DB

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

func Open

func Open(driverName, dataSourceName string, tag string) (*DB, error)

func OpenContext

func OpenContext(ctx context.Context, driverName, dataSourceName string, tag string) (*DB, error)

func Wrap

func Wrap(db *sql.DB, driverName, tag string) *DB

func WrapContext

func WrapContext(ctx context.Context, db *sql.DB, driverName, tag string) *DB

func (*DB) Begin

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

func (*DB) BeginTx

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

func (*DB) Close

func (db *DB) Close() error

func (*DB) Context

func (db *DB) Context() context.Context

func (*DB) Delete

func (db *DB) Delete(query string, args ...interface{}) (Result, error)

func (*DB) DeleteContext

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

func (*DB) Exec

func (db *DB) Exec(query string, args ...interface{}) (Result, error)

func (*DB) ExecContext

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

func (*DB) Insert

func (db *DB) Insert(sqlHead string, args ...interface{}) (Result, error)

func (*DB) InsertContext

func (db *DB) InsertContext(ctx context.Context, sqlHead string, args ...interface{}) (Result, error)

func (*DB) Mapping

func (db *DB) Mapping() *sync.Map

func (*DB) Placeholder

func (db *DB) Placeholder() string

func (*DB) PlaceholderBuilder

func (db *DB) PlaceholderBuilder() func(int) string

func (*DB) Prepare

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

func (*DB) PrepareContext

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

func (*DB) Query

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

func (*DB) QueryContext

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

func (*DB) QueryRow

func (db *DB) QueryRow(dst interface{}, query string, args ...interface{}) (Result, error)

func (*DB) QueryRowContext

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

func (*DB) Quote added in v1.1.1

func (db *DB) Quote() string

func (*DB) RawScan

func (db *DB) RawScan() bool

func (*DB) Select

func (db *DB) Select(dst interface{}, query string, args ...interface{}) (Result, error)

func (*DB) SelectContext

func (db *DB) SelectContext(ctx context.Context, dst interface{}, query string, args ...interface{}) (Result, error)

func (*DB) SetContext

func (db *DB) SetContext(ctx context.Context)

func (*DB) SetFieldParser

func (db *DB) SetFieldParser(f FieldParser)

func (*DB) SetPlaceholder

func (db *DB) SetPlaceholder(placeholder string)

func (*DB) SetPlaceholderBuilder

func (db *DB) SetPlaceholderBuilder(placeholderBuilder func(int) string)

func (*DB) SetQuote added in v1.1.1

func (db *DB) SetQuote(quote string)

func (*DB) SetRawScan

func (db *DB) SetRawScan(rawScan bool)

func (*DB) SetTag

func (db *DB) SetTag(tag string)

func (*DB) Tag

func (db *DB) Tag() string

func (*DB) Update

func (db *DB) Update(sqlHead string, args ...interface{}) (Result, error)

func (*DB) UpdateContext

func (db *DB) UpdateContext(ctx context.Context, sqlHead string, args ...interface{}) (Result, error)

type Field

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

sql.Scanner

func (*Field) Bool

func (field *Field) Bool() bool

func (*Field) Bytes

func (field *Field) Bytes() []byte

func (*Field) Float64

func (field *Field) Float64() float64

func (*Field) Int64

func (field *Field) Int64() int64

func (*Field) Scan

func (field *Field) Scan(v interface{}) error

func (*Field) String

func (field *Field) String() string

func (*Field) Time

func (field *Field) Time() time.Time

func (*Field) ToValue

func (field *Field) ToValue(dstVal reflect.Value)

func (*Field) Uint64

func (field *Field) Uint64() uint64

type FieldParser

type FieldParser func(field *reflect.StructField) string

type MappingInfo

type MappingInfo struct {
	SqlHead      string
	FieldNames   []string
	FieldIndexes map[string]int
}

type Result

type Result = *sqlResult

type Selector

type Selector interface {
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	Query(query string, args ...interface{}) (*sql.Rows, error)
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
}

type Stmt

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

func NewStmt

func NewStmt(db *DB, stmt *sql.Stmt, query string) *Stmt

func (*Stmt) Delete

func (stmt *Stmt) Delete(args ...interface{}) (Result, error)

func (*Stmt) DeleteContext

func (stmt *Stmt) DeleteContext(ctx context.Context, args ...interface{}) (Result, error)

func (*Stmt) Exec

func (stmt *Stmt) Exec(args ...interface{}) (Result, error)

func (*Stmt) ExecContext

func (stmt *Stmt) ExecContext(ctx context.Context, args ...interface{}) (Result, error)

func (*Stmt) Insert

func (stmt *Stmt) Insert(args ...interface{}) (Result, error)

func (*Stmt) InsertContext

func (stmt *Stmt) InsertContext(ctx context.Context, args ...interface{}) (Result, error)

func (*Stmt) Query

func (stmt *Stmt) Query(dst interface{}, args ...interface{}) (Result, error)

func (*Stmt) QueryContext

func (stmt *Stmt) QueryContext(ctx context.Context, dst interface{}, args ...interface{}) (Result, error)

func (*Stmt) QueryRow

func (stmt *Stmt) QueryRow(dst interface{}, args ...interface{}) (Result, error)

func (*Stmt) QueryRowContext

func (stmt *Stmt) QueryRowContext(ctx context.Context, dst interface{}, args ...interface{}) (Result, error)

func (*Stmt) Select

func (stmt *Stmt) Select(dst interface{}, args ...interface{}) (Result, error)

func (*Stmt) SelectContext

func (stmt *Stmt) SelectContext(ctx context.Context, dst interface{}, args ...interface{}) (Result, error)

func (*Stmt) Sql

func (stmt *Stmt) Sql(ctx context.Context, dst interface{}, args ...interface{}) string

func (*Stmt) Update

func (stmt *Stmt) Update(args ...interface{}) (Result, error)

func (*Stmt) UpdateContext

func (stmt *Stmt) UpdateContext(ctx context.Context, args ...interface{}) (Result, error)

type Tx

type Tx struct {
	*DB
	*sql.Tx
}

func (*Tx) Delete

func (tx *Tx) Delete(query string, args ...interface{}) (Result, error)

func (*Tx) DeleteContext

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

func (*Tx) Exec

func (tx *Tx) Exec(query string, args ...interface{}) (Result, error)

func (*Tx) ExecContext

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

func (*Tx) Insert

func (tx *Tx) Insert(sqlHead string, args ...interface{}) (Result, error)

func (*Tx) InsertContext

func (tx *Tx) InsertContext(ctx context.Context, sqlHead string, args ...interface{}) (Result, error)

func (*Tx) Prepare

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

func (*Tx) PrepareContext

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

func (*Tx) Query

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

func (*Tx) QueryContext

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

func (*Tx) QueryRow

func (tx *Tx) QueryRow(dst interface{}, query string, args ...interface{}) (Result, error)

func (*Tx) QueryRowContext

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

func (*Tx) Select

func (tx *Tx) Select(dst interface{}, query string, args ...interface{}) (Result, error)

func (*Tx) SelectContext

func (tx *Tx) SelectContext(ctx context.Context, dst interface{}, query string, args ...interface{}) (Result, error)

func (*Tx) Stmt

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

func (*Tx) StmtContext

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

func (*Tx) Update

func (tx *Tx) Update(sqlHead string, args ...interface{}) (Result, error)

func (*Tx) UpdateContext

func (tx *Tx) UpdateContext(ctx context.Context, sqlHead string, args ...interface{}) (Result, error)

Jump to

Keyboard shortcuts

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