orm

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2022 License: BSD-3-Clause Imports: 19 Imported by: 8

README

orm

Quick Start

  • Open orm
db, err := orm.Open(driverName, dataSourceName)
  • Define table struct to database
type User struct {
    Name   string
    Age    int
    Passwd *string
}
  • Exec runs a SQL string, it returns error
err := db.ExecNumErr("delete from user where name=?", "test")
  • Insert one record to database
err := db.Insert(&user)
// insert into user () values ()

err := db.Insert(&user, orm.WithTable("system_user"))
// insert into system_user () values ()
  • Query query one record from database
err := db.Query("select * from user limit 1").Row(&user)
  • check if one record or affected exist with query/exec
import "github.com/yubo/golib/api/errors"

if errors.IsNotFound(err) {
	// do something
}
  • Rows query multiple records from database
var users []User
err := db.Query("select * from user where age > ?", 10).Rows(&users)
  • Rows query multiple records from database with Count
var users []User
var total int64
err := db.Query("select * from user where age > ?", 10).Count(&total).Rows(&users)
// select * from user where age > 10
// select count(*) from user where age > 10
  • Update update one record
type User struct {
    Name   string `sql:",where"`
    Age    int
    Passwd *string
}

affected, err := db.Update(&user)
// if user.Passwd == nil
// update user set age=? where name = ?
// else
// update user set age=?, passwd=? where name = ?

affected, err := db.Update(&user, orm.WithTable("system_user"))
// update system_user set ... where name = ?
  • Transation
tx, err := db.Begin()
if err != nil {
	return err
}

// do something...

if err := tx.Insert(&user); err != nil {
	tx.Rollback()
	return err
}

return tx.Commit()

Documentation

Index

Constants

View Source
const (
	DefaultMaxRows = 1000
)

Variables

View Source
var (
	DefaultStringSize = 255
	DEBUG             = false
)

Functions

func AddSqlArgs added in v0.0.2

func AddSqlArgs(sql string, args []interface{},
	intoSql *string, intoArgs *[]interface{})

func GenDeleteSql added in v0.0.2

func GenDeleteSql(table string, selector queries.Selector) (string, []interface{}, error)

func GenGetSql added in v0.0.2

func GenGetSql(table string, cols []string, selector queries.Selector) (string, []interface{}, error)

func GenInsertSql

func GenInsertSql(table string, sample interface{}, db Driver) (string, []interface{}, error)

func GenListSql added in v0.0.2

func GenListSql(table string, cols []string, selector queries.Selector, orderby []string, offset, limit *int64) (string, string, []interface{}, error)

func GenUpdateSql

func GenUpdateSql(table string, sample interface{}, db Driver) (string, []interface{}, error)

func Ints2sql

func Ints2sql(array []int64) string

{1,2,3} => "(1,2,3)"

func IsNil added in v0.0.2

func IsNil(rv reflect.Value) bool

func NewCurTime added in v0.0.2

func NewCurTime(t TimeType, cur time.Time) interface{}

func Register added in v0.0.2

func Register(name string, d DBFactory)

func SetClock added in v0.0.2

func SetClock(clock clock.Clock)

func Strings2sql

func Strings2sql(array []string) string

{"1","2","3"} => "('1', '2', '3')"

func WithInterface added in v0.0.2

func WithInterface(ctx context.Context, orm Interface) context.Context

Types

type DB

type DB interface {
	SqlDB() *sql.DB
	Close() error
	Begin() (Tx, error)
	BeginTx(ctx context.Context, ops *sql.TxOptions) (Tx, error)
	ExecRows(bytes []byte) error // like mysql < a.sql

	Interface
}

func Open

func Open(driverName, dataSourceName string, opts ...DBOption) (DB, error)

type DBFactory added in v0.0.2

type DBFactory func(db Execer) Driver

type DBOption added in v0.0.2

type DBOption func(*DBOptions)

func WithConnMaxIdletime

func WithConnMaxIdletime(d time.Duration) DBOption

func WithConnMaxLifetime

func WithConnMaxLifetime(d time.Duration) DBOption

func WithContext

func WithContext(ctx context.Context) DBOption

func WithDirver

func WithDirver(driver string) DBOption

func WithDsn

func WithDsn(dsn string) DBOption

func WithIgnoreNotFound

func WithIgnoreNotFound() DBOption

func WithMaxIdleCount

func WithMaxIdleCount(n int) DBOption

func WithMaxOpenConns

func WithMaxOpenConns(n int) DBOption

func WithMaxRows

func WithMaxRows(n int) DBOption

func WithoutPing

func WithoutPing() DBOption

type DBOptions added in v0.0.2

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

func (*DBOptions) Validate added in v0.0.2

func (p *DBOptions) Validate() error

type DataType added in v0.0.2

type DataType string
const (
	Bool   DataType = "bool"
	Int    DataType = "int"
	Uint   DataType = "uint"
	Float  DataType = "float"
	String DataType = "string"
	Time   DataType = "time"
	Bytes  DataType = "bytes"
)

type Driver added in v0.0.2

type Driver interface {
	// refer: https://gorm.io/docs/migration.html
	AutoMigrate(sample interface{}, opts ...Option) error

	//  parse datatype
	ParseField(opts *StructField)

	// Database
	CurrentDatabase() string
	FullDataTypeOf(field *StructField) string

	// Tables
	CreateTable(o *Options) error
	DropTable(o *Options) error
	HasTable(tableName string) bool
	GetTables() (tableList []string, err error)

	// Columns
	AddColumn(field string, o *Options) error
	DropColumn(field string, o *Options) error
	AlterColumn(field string, o *Options) error
	MigrateColumn(expect, actual *StructField, o *Options) error
	HasColumn(field string, o *Options) bool
	ColumnTypes(o *Options) ([]StructField, error)

	// Indexes
	CreateIndex(name string, o *Options) error
	DropIndex(name string, o *Options) error
	HasIndex(name string, o *Options) bool
}

type Execer added in v0.0.2

type Execer interface {
	Exec(query string, args ...interface{}) (sql.Result, error)
	ExecLastId(sql string, args ...interface{}) (int64, error)
	ExecNum(sql string, args ...interface{}) (int64, error)
	ExecNumErr(s string, args ...interface{}) error
	Query(query string, args ...interface{}) *Rows
	WithRawDB(raw RawDB) Interface
	RawDB() RawDB
}

type Interface added in v0.0.2

type Interface interface {
	Driver
	Execer
	Store
}

func InterfaceFrom added in v0.0.2

func InterfaceFrom(ctx context.Context) (Interface, bool)

func NewBaseInterface added in v0.0.2

func NewBaseInterface(driver Driver, db RawDB, opts *DBOptions) Interface

type Option

type Option func(*Options)

func WithCols

func WithCols(cols ...string) Option

func WithIgnoreNotFoundErr added in v0.0.2

func WithIgnoreNotFoundErr() Option

func WithLimit

func WithLimit(offset, limit int64) Option

func WithOrderby added in v0.0.2

func WithOrderby(orderby ...string) Option

func WithSample

func WithSample(sample interface{}) Option

func WithSelector added in v0.0.2

func WithSelector(selector string) Option

func WithTable

func WithTable(table string) Option

func WithTotal added in v0.0.2

func WithTotal(total *int64) Option

type Options

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

func NewOptions added in v0.0.2

func NewOptions(opts ...Option) (*Options, error)

func (*Options) Error added in v0.0.2

func (o *Options) Error(err error) error

func (*Options) GenDeleteSql added in v0.0.2

func (p *Options) GenDeleteSql() (string, []interface{}, error)

TODO: generate selector from sample.fields, like GenUpdateSql

func (*Options) GenGetSql added in v0.0.2

func (p *Options) GenGetSql() (string, []interface{}, error)

func (*Options) GenInsertSql added in v0.0.2

func (p *Options) GenInsertSql(db Driver) (string, []interface{}, error)

func (*Options) GenListSql added in v0.0.2

func (p *Options) GenListSql() (query, countQuery string, args []interface{}, err error)

func (*Options) GenUpdateSql added in v0.0.2

func (p *Options) GenUpdateSql(db Driver) (string, []interface{}, error)

func (*Options) Sample added in v0.0.2

func (o *Options) Sample() interface{}

func (*Options) Table added in v0.0.2

func (p *Options) Table() string

type RawDB added in v0.0.2

type RawDB interface {
	Exec(query string, args ...interface{}) (sql.Result, error)
	Query(query string, args ...interface{}) (*sql.Rows, error)
}

type Rows

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

func (*Rows) Iterator

func (p *Rows) Iterator() (RowsIter, error)

func (*Rows) Row

func (p *Rows) Row(dst ...interface{}) error

Row(*int, *int, ...) Row(*struct{}) Row(**struct{})

func (*Rows) Rows

func (p *Rows) Rows(dst interface{}) error

Rows([]struct{}) Rows([]*struct{}) Rows(*[]struct{}) Rows(*[]*struct{}) Rows([]string) Rows([]*string) Rows ignore notfound err msg

type RowsIter

type RowsIter interface {
	Close() error
	Next() bool
	Row(dest ...interface{}) error
}

type Set added in v0.0.2

type Set map[string]string

Set is a map of field:value. It implements Fields.

func ParseFields added in v0.0.2

func ParseFields(s string) Set

func (Set) Get added in v0.0.2

func (ls Set) Get(field string) string

Get returns the value in the map for the provided field.

func (Set) Has added in v0.0.2

func (ls Set) Has(field string) bool

Has returns whether the provided field exists in the map.

func (Set) String added in v0.0.2

func (ls Set) String() string

String returns all fields listed as a human readable string. Conveniently, exactly the format that ParseSelector takes.

type Store added in v0.0.2

type Store interface {
	Insert(sample interface{}, opts ...Option) error
	InsertLastId(sample interface{}, opts ...Option) (int64, error)
	Get(into interface{}, opts ...Option) error
	List(into interface{}, opts ...Option) error
	Update(sample interface{}, opts ...Option) error
	Delete(sample interface{}, opts ...Option) error
}

type StructField added in v0.0.2

type StructField struct {
	Set
	Type  reflect.Type
	Index []int

	FieldName string
	Name      string
	Where     bool
	Skip      bool
	Inline    bool

	// from tag
	DataType              DataType
	AutoCreatetime        TimeType // auto_createtime
	AutoUpdatetime        TimeType // auto_updatetime
	PrimaryKey            bool
	AutoIncrement         bool
	AutoIncrementNum      int64
	HasDefaultValue       bool
	DefaultValue          string
	DefaultValueInterface interface{}
	Size                  *int64
	Precision             *int64
	Scale                 *int64
	NotNull               *bool
	Unique                *bool
	Comment               *string

	// index
	IndexComment string
	IndexClass   string
	IndexOption  string
	IndexKey     bool
	IndexName    string

	DriverDataType string
	Class          string
}

func GetField added in v0.0.2

func GetField(sample interface{}, field string, driver Driver) *StructField

func (StructField) String added in v0.0.2

func (p StructField) String() string

type StructFields added in v0.0.2

type StructFields struct {
	Fields []*StructField
	// contains filtered or unexported fields
}

func GetFields added in v0.0.2

func GetFields(sample interface{}, driver Driver) StructFields

func (StructFields) String added in v0.0.2

func (p StructFields) String() (ret string)

type TimeType added in v0.0.2

type TimeType int64
const (
	UnixTime        TimeType = 1
	UnixSecond      TimeType = 2
	UnixMillisecond TimeType = 3
	UnixNanosecond  TimeType = 4
)

type Tx

type Tx interface {
	Tx() *sql.Tx
	Rollback() error
	Commit() error

	Interface
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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