hey

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2023 License: MIT Imports: 7 Imported by: 1

README

What is HEY?

hey is an assistant tool similar to ORM to operate the database; its purpose is to allow you to perform addition, deletion, modification and query efficiently and quickly.

Advantages of HEY

hey does not limit you to use the database driver, you only need to provide the database connection pool instance *sql.DB

hey only supports the execution of a single SQL statement, if you need to execute SQL scripts in batches, please use (*sql.DB).Exec()

hey optional logging, you can use the CallTakeWarn() method to set the SQL execution time-consuming threshold, unit: milliseconds

hey uses ? as the placeholder of the SQL statement by default, if your database instance does not support it, please use the Prepare() method to preprocess the SQL statement

hey uses the tag-db value of the structure to match the query result field by default, if the tag does not match your business, you can use the Scanner() method to customize the matching rules

hey supports transactions, and allows nested calls to facilitate you to care more about business implementation

hey cleverly implements the conditional filtering of SQL statements, so you can easily use Filter to filter delete, update, query

hey When querying SQL, you can choose to use Scanner[reflection implementation] and rows.Scan() to customize the scan query results, performance and speed are up to you

Supports raw SQL execution by default, and raw SQL statements are valid in logs, transactions, Scanner, and SQL preprocessing

INSTALL

go get github.com/cd365/hey@v1.0.0

FOR EXAMPLE

package main

import (
	"database/sql"

	"github.com/cd365/hey"
)

func way() {
	var db *sql.DB

	way := hey.NewWay(db)
	// way.Prepare(hey.PreparePostgresql) // PostgreSQL
	// way.Logger(nil).CallTakeWarn(10) // logger
	// way.Scanner(func(rows *sql.Rows, result interface{}) error {
	// 	return hey.ScanSliceStruct(rows, result, "database")
	// }) // custom scanner

	/* account table */
	account := way.Table("account")

	/* insert one */
	account.Insert(func(tmp *hey.Insert) {
		tmp.Field("name", "email").Value(
			[]interface{}{
				"Jack",
				"jack@gmail.com",
			})
	})

	/* insert batch */
	account.Insert(func(tmp *hey.Insert) {
		tmp.Field("name", "email").Value(
			[]interface{}{
				"Alice",
				"alice@gmail.com",
			},
			[]interface{}{
				"Tom",
				"tom@gmail.com",
			},
			// ...
		)
	})

	/* delete */
	account.Delete(func(tmp *hey.Delete) {
		tmp.Where(hey.NewFilter().In("id", 1, 2, 3))
		// tmp.Force()
	})

	/* update */
	account.Update(func(tmp *hey.Update) {
		tmp.Where(hey.NewFilter().In("id", 1, 2, 3))
		// tmp.Force()
		tmp.Incr("times", 1)
		tmp.Set("name", "Jerry")
	})

	/* select count */
	account.Select().Where(hey.NewFilter().IsNotNull("id")).Count()

	type ScanStruct struct {
		Name  string `db:"name"`
		Email string `db:"email"`
	}
	result := make([]*ScanStruct, 0)
	query := account.Select().
		Field("name", "email").
		Where(
			hey.NewFilter().
				MoreThan("id", 0),
		).
		Desc("id").
		Limit(10).
		Offset(0)
	query.Scan(&result)

	query.Get(func(rows *sql.Rows) (err error) {
		name := new(string)
		email := new(string)
		if err = rows.Scan(&name, &email); err != nil {
			return
		}
		// todo ...
		return nil
	})

	/* transaction */
	way.Transaction(func(tx *hey.Way) (err error) {
		account := tx.Table("account")
		account.Insert(func(tmp *hey.Insert) { /* todo... */ })
		account.Delete(func(tmp *hey.Delete) { /* todo... */ })
		account.Update(func(tmp *hey.Update) { /* todo... */ })
		account.Select() /* todo... */
		return
	})
}

Documentation

Index

Constants

View Source
const (
	DefaultColumnName = "*" // default column name

	DefaultCountAliasName = "hey_rows_total" // default total rows alias name

	DefaultUnionResultTableAliasName = "hey_union_result_table_alias_name" // union query result table alias name
)
View Source
const (
	Placeholder = "?"
)

Variables

This section is empty.

Functions

func Alias

func Alias(prepare string, alias ...string) string

func FieldMerge

func FieldMerge(fields ...[]string) (result []string)

func ForRowsNextScan

func ForRowsNextScan(rows *sql.Rows, rowsScan func(rows *sql.Rows) (err error)) (err error)

func PreparePostgresql

func PreparePostgresql(prepare string) string

func RemoveDuplicate

func RemoveDuplicate(dynamic ...interface{}) (result []interface{})

RemoveDuplicate remove duplicate element

func ScanSliceStruct

func ScanSliceStruct(rows *sql.Rows, result interface{}, structTag string) (err error)

ScanSliceStruct scan queries result into slice *[]struct or *[]*struct

func StructAssign

func StructAssign(origin interface{}, latest interface{})

StructAssign struct attribute assignment, both the origin and latest parameters must be struct pointers

func StructAttributeIndex

func StructAttributeIndex(rt reflect.Type) map[string]int

func StructModify

func StructModify(origin interface{}, latest interface{})

StructModify struct attribute is not nil assignment, both the origin and latest parameters must be struct pointers

func StructTagIndex

func StructTagIndex(rt reflect.Type, tag string) map[string]int

func SubQuery

func SubQuery(prepare string) string

Types

type Delete

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

func NewDelete

func NewDelete(way *Way) *Delete

func (*Delete) Force

func (s *Delete) Force() *Delete

func (*Delete) Result

func (s *Delete) Result() (string, []interface{})

func (*Delete) Table

func (s *Delete) Table(table string) *Delete

func (*Delete) Tag

func (s *Delete) Tag(tag string) *Delete

func (*Delete) Where

func (s *Delete) Where(where Filter) *Delete

func (*Delete) WithContext

func (s *Delete) WithContext(ctx context.Context) *Delete

type Filter

type Filter interface {
	And(prepare string, args ...interface{}) Filter
	Or(prepare string, args ...interface{}) Filter
	Filter(filters ...Filter) Filter
	OrFilter(filters ...Filter) Filter
	Group(group func(filter Filter) Filter) Filter
	OrGroup(group func(filter Filter) Filter) Filter
	Equal(column string, value interface{}) Filter
	NotEqual(column string, value interface{}) Filter
	MoreThan(column string, value interface{}) Filter
	MoreThanEqual(column string, value interface{}) Filter
	LessThan(column string, value interface{}) Filter
	LessThanEqual(column string, value interface{}) Filter
	In(column string, values ...interface{}) Filter
	NotIn(column string, values ...interface{}) Filter
	Between(column string, start interface{}, end interface{}) Filter
	NotBetween(column string, start interface{}, end interface{}) Filter
	Like(column string, value interface{}) Filter
	NotLike(column string, value interface{}) Filter
	IsNull(column string) Filter
	IsNotNull(column string) Filter
	OrEqual(column string, value interface{}) Filter
	OrNotEqual(column string, value interface{}) Filter
	OrMoreThan(column string, value interface{}) Filter
	OrMoreThanEqual(column string, value interface{}) Filter
	OrLessThan(column string, value interface{}) Filter
	OrLessThanEqual(column string, value interface{}) Filter
	OrIn(column string, values ...interface{}) Filter
	OrNotIn(column string, values ...interface{}) Filter
	OrBetween(column string, start interface{}, end interface{}) Filter
	OrNotBetween(column string, start interface{}, end interface{}) Filter
	OrLike(column string, value interface{}) Filter
	OrNotLike(column string, value interface{}) Filter
	OrIsNull(column string) Filter
	OrIsNotNull(column string) Filter
	Result() (prepare string, args []interface{})
}

func NewFilter

func NewFilter() Filter

type Insert

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

func NewInsert

func NewInsert(way *Way) *Insert

func (*Insert) Field

func (s *Insert) Field(field ...string) *Insert

func (*Insert) ForMap

func (s *Insert) ForMap(fieldValue map[string]interface{}) *Insert

func (*Insert) ForSlice

func (s *Insert) ForSlice(field []string, value []interface{}) *Insert

func (*Insert) Result

func (s *Insert) Result() (string, []interface{})

func (*Insert) Table

func (s *Insert) Table(table string) *Insert

func (*Insert) Tag

func (s *Insert) Tag(tag string) *Insert

func (*Insert) Value

func (s *Insert) Value(value ...[]interface{}) *Insert

func (*Insert) ValuesFromQuery

func (s *Insert) ValuesFromQuery(prepare string, args ...interface{}) *Insert

func (*Insert) ValuesFromSelect

func (s *Insert) ValuesFromSelect(selector *Select) *Insert

func (*Insert) WithContext

func (s *Insert) WithContext(ctx context.Context) *Insert

type Join

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

func (*Join) Alias

func (s *Join) Alias() string

func (*Join) As

func (s *Join) As(as string) Joiner

func (*Join) Asa

func (s *Join) Asa() Joiner

func (*Join) Asb

func (s *Join) Asb() Joiner

func (*Join) Asc

func (s *Join) Asc() Joiner

func (*Join) Asd

func (s *Join) Asd() Joiner

func (*Join) Ase

func (s *Join) Ase() Joiner

func (*Join) Asf

func (s *Join) Asf() Joiner

func (*Join) Field

func (s *Join) Field(field string) string

func (*Join) Name

func (s *Join) Name() string

func (*Join) On

func (s *Join) On(joinOn string, joinOnFilter ...Filter) Joiner

func (*Join) OnEqual

func (s *Join) OnEqual(left string, right string, filter ...Filter) Joiner

func (*Join) Query

func (s *Join) Query(field ...string) Joiner

func (*Join) QueryFields

func (s *Join) QueryFields() []string

func (*Join) Result

func (s *Join) Result() (prepare string, args []interface{})

func (*Join) Table

func (s *Join) Table() string

type JoinType

type JoinType string
const (
	JoinMaster JoinType = "MASTER"
	JoinInner  JoinType = "INNER"
	JoinLeft   JoinType = "LEFT"
	JoinRight  JoinType = "RIGHT"
	JoinFull   JoinType = "FULL"
)

type Joiner

type Joiner interface {
	// As set current table name as alias-name
	As(as string) Joiner

	// Alias get current table name as alias-name
	Alias() string

	// Asa set current table name as <a>
	Asa() Joiner

	// Asb set current table name as <b>
	Asb() Joiner

	// Asc set current table name as <c>
	Asc() Joiner

	// Asd set current table name as <d>
	Asd() Joiner

	// Ase set current table name as <e>
	Ase() Joiner

	// Asf set current table name as <f>
	Asf() Joiner

	// Table get current table name
	Table() string

	// Name get the name used by the current table, aliases take precedence
	Name() string

	// Query set the connection query finally needs to query the field list of this table
	Query(field ...string) Joiner

	// QueryFields get the connection query finally needs to query the field list of this table
	QueryFields() []string

	// Field the table's field full name value
	Field(field string) string

	// On the criteria for joining the current table query
	On(on string, filter ...Filter) Joiner

	// OnEqual the criteria for joining the current table query, left = right
	OnEqual(left string, right string, filter ...Filter) Joiner

	// Result the current table joins the final sql script and parameters generated by the query
	Result() (prepare string, args []interface{})
}

func FullJoin

func FullJoin(table string, args ...interface{}) Joiner

func InnerJoin

func InnerJoin(table string, args ...interface{}) Joiner

func LeftJoin

func LeftJoin(table string, args ...interface{}) Joiner

func MasterJoin

func MasterJoin(table string, args ...interface{}) Joiner

func RightJoin

func RightJoin(table string, args ...interface{}) Joiner

type Logger

type Logger interface {
	Info(v ...interface{})
	Infof(format string, v ...interface{})
	Warn(v ...interface{})
	Warnf(format string, v ...interface{})
	Error(v ...interface{})
	Errorf(format string, v ...interface{})
}

type Order

type Order struct {
	Order []string
}

func NewOrder

func NewOrder() *Order

func (*Order) Asc

func (s *Order) Asc(columns ...string) *Order

func (*Order) Desc

func (s *Order) Desc(columns ...string) *Order

func (*Order) Result

func (s *Order) Result() string

type Select

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

func NewSelect

func NewSelect(way *Way) *Select

func (*Select) Alias

func (s *Select) Alias(alias string) *Select

func (*Select) Asc

func (s *Select) Asc(field ...string) *Select

func (*Select) Count

func (s *Select) Count() (result int64, err error)

func (*Select) Desc

func (s *Select) Desc(field ...string) *Select

func (*Select) Field

func (s *Select) Field(field ...string) *Select

func (*Select) FromSelect

func (s *Select) FromSelect(selector *Select, alias string) *Select

func (*Select) Get

func (s *Select) Get(forRowsNextScan func(rows *sql.Rows) (err error)) error

func (*Select) Group

func (s *Select) Group(group ...string) *Select

func (*Select) Having

func (s *Select) Having(having Filter) *Select

func (*Select) Join

func (s *Select) Join(join ...Joiner) *Select

func (*Select) Limit

func (s *Select) Limit(limit int64) *Select

func (*Select) Master

func (s *Select) Master(master Joiner) *Select

func (*Select) Offset

func (s *Select) Offset(offset int64) *Select

func (*Select) Order

func (s *Select) Order(order *Order) *Select

func (*Select) Result

func (s *Select) Result() (string, []interface{})

func (*Select) ResultForCount

func (s *Select) ResultForCount() (string, []interface{})

func (*Select) Scan

func (s *Select) Scan(result interface{}) error

func (*Select) Table

func (s *Select) Table(table string, args ...interface{}) *Select

func (*Select) Tag

func (s *Select) Tag(tag string) *Select

func (*Select) Union

func (s *Select) Union(c ...*Select) *Select

func (*Select) UnionAll

func (s *Select) UnionAll(c ...*Select) *Select

func (*Select) Where

func (s *Select) Where(where Filter) *Select

func (*Select) WithContext

func (s *Select) WithContext(ctx context.Context) *Select

type Table

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

func (*Table) Delete

func (s *Table) Delete(fn func(tmp *Delete)) (int64, error)

func (*Table) Insert

func (s *Table) Insert(fn func(tmp *Insert)) (int64, error)

func (*Table) Select

func (s *Table) Select() *Select

func (*Table) Update

func (s *Table) Update(fn func(tmp *Update)) (int64, error)

type TypeUnion

type TypeUnion string
const (
	UnknownUnion TypeUnion = ""
	Union        TypeUnion = "UNION"
	UnionAll     TypeUnion = "UNION ALL"
)

type Update

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

func NewUpdate

func NewUpdate(way *Way) *Update

func (*Update) Decr

func (s *Update) Decr(field string, value interface{}) *Update

func (*Update) Expr

func (s *Update) Expr(expr string, args ...interface{}) *Update

func (*Update) ForMap

func (s *Update) ForMap(fieldValue map[string]interface{}) *Update

func (*Update) ForSlice

func (s *Update) ForSlice(field []string, value []interface{}) *Update

func (*Update) Force

func (s *Update) Force() *Update

func (*Update) Incr

func (s *Update) Incr(field string, value interface{}) *Update

func (*Update) Result

func (s *Update) Result() (string, []interface{})

func (*Update) Set

func (s *Update) Set(field string, value interface{}) *Update

func (*Update) Table

func (s *Update) Table(table string) *Update

func (*Update) Tag

func (s *Update) Tag(tag string) *Update

func (*Update) Where

func (s *Update) Where(where Filter) *Update

func (*Update) WithContext

func (s *Update) WithContext(ctx context.Context) *Update

type Way

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

func NewWay

func NewWay(db *sql.DB) *Way

func (*Way) CallTakeWarn

func (s *Way) CallTakeWarn(milliseconds int64) *Way

func (*Way) DB

func (s *Way) DB() *sql.DB

func (*Way) Exec

func (s *Way) Exec(prepare string, args ...interface{}) (int64, error)

func (*Way) ExecContext

func (s *Way) ExecContext(ctx context.Context, prepare string, args ...interface{}) (rowsAffected int64, err error)

func (*Way) Logger

func (s *Way) Logger(logger Logger) *Way

func (*Way) Prepare

func (s *Way) Prepare(fn func(prepare string) (result string)) *Way

func (*Way) Query

func (s *Way) Query(handlingRows func(rows *sql.Rows) (err error), prepare string, args ...interface{}) error

func (*Way) QueryContext

func (s *Way) QueryContext(ctx context.Context, handlingRows func(rows *sql.Rows) (err error), prepare string, args ...interface{}) (err error)

func (*Way) Scan

func (s *Way) Scan(result interface{}, prepare string, args ...interface{}) error

func (*Way) ScanContext

func (s *Way) ScanContext(ctx context.Context, result interface{}, prepare string, args ...interface{}) error

func (*Way) Scanner

func (s *Way) Scanner(fn func(rows *sql.Rows, result interface{}) error) *Way

func (*Way) Table

func (s *Way) Table(table string) *Table

func (*Way) Transaction

func (s *Way) Transaction(fn func(tx *Way) (err error)) error

func (*Way) TransactionContext

func (s *Way) TransactionContext(ctx context.Context, opts *sql.TxOptions, fn func(tx *Way) (err error)) (err error)

func (*Way) TxNil

func (s *Way) TxNil() bool

Jump to

Keyboard shortcuts

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