core

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

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

Go to latest
Published: Mar 8, 2020 License: BSD-2-Clause Imports: 13 Imported by: 39

README

Core is a lightweight wrapper of sql.DB.

Open

db, _ := core.Open(db, connstr)

SetMapper

db.SetMapper(SameMapper())

Scan usage

Scan
rows, _ := db.Query()
for rows.Next() {
    rows.Scan()
}
ScanMap
rows, _ := db.Query()
for rows.Next() {
    rows.ScanMap()
ScanSlice

You can use []string, [][]byte, []interface{}, []*string, []sql.NullString to ScanSclice. Notice, slice's length should be equal or less than select columns.

rows, _ := db.Query()
cols, _ := rows.Columns()
for rows.Next() {
    var s = make([]string, len(cols))
    rows.ScanSlice(&s)
}
rows, _ := db.Query()
cols, _ := rows.Columns()
for rows.Next() {
    var s = make([]*string, len(cols))
    rows.ScanSlice(&s)
}
ScanStruct
rows, _ := db.Query()
for rows.Next() {
    rows.ScanStructByName()
    rows.ScanStructByIndex()
}

Query usage

rows, err := db.Query("select * from table where name = ?", name)

user = User{
    Name:"lunny",
}
rows, err := db.QueryStruct("select * from table where name = ?Name",
            &user)

var user = map[string]interface{}{
    "name": "lunny",
}
rows, err = db.QueryMap("select * from table where name = ?name",
            &user)

QueryRow usage

row := db.QueryRow("select * from table where name = ?", name)

user = User{
    Name:"lunny",
}
row := db.QueryRowStruct("select * from table where name = ?Name",
            &user)

var user = map[string]interface{}{
    "name": "lunny",
}
row = db.QueryRowMap("select * from table where name = ?name",
            &user)

Exec usage

db.Exec("insert into user (`name`, title, age, alias, nick_name,created) values (?,?,?,?,?,?)", name, title, age, alias...)

user = User{
    Name:"lunny",
    Title:"test",
    Age: 18,
}
result, err = db.ExecStruct("insert into user (`name`, title, age, alias, nick_name,created) values (?Name,?Title,?Age,?Alias,?NickName,?Created)",
            &user)

var user = map[string]interface{}{
    "Name": "lunny",
    "Title": "test",
    "Age": 18,
}
result, err = db.ExecMap("insert into user (`name`, title, age, alias, nick_name,created) values (?Name,?Title,?Age,?Alias,?NickName,?Created)",
            &user)

Documentation

Index

Constants

View Source
const (
	// CacheExpired is default cache expired time
	CacheExpired = 60 * time.Minute
	// CacheMaxMemory is not use now
	CacheMaxMemory = 256
	// CacheGcInterval represents interval time to clear all expired nodes
	CacheGcInterval = 10 * time.Minute
	// CacheGcMaxRemoved represents max nodes removed when gc
	CacheGcMaxRemoved = 20
)
View Source
const (
	TWOSIDES = iota + 1
	ONLYTODB
	ONLYFROMDB
)
View Source
const (
	IndexType = iota + 1
	UniqueType
)

enumerate all index types

View Source
const (
	POSTGRES = "postgres"
	SQLITE   = "sqlite3"
	MYSQL    = "mysql"
	MSSQL    = "mssql"
	ORACLE   = "oracle"
)
View Source
const (
	UNKNOW_TYPE = iota
	TEXT_TYPE
	BLOB_TYPE
	TIME_TYPE
	NUMERIC_TYPE
)

Variables

View Source
var (
	ErrCacheMiss = errors.New("xorm/cache: key not found")
	ErrNotStored = errors.New("xorm/cache: not stored")
)

list all the errors

View Source
var (
	// ErrNoMapPointer represents error when no map pointer
	ErrNoMapPointer = errors.New("mp should be a map's pointer")
	// ErrNoStructPointer represents error when no struct pointer
	ErrNoStructPointer = errors.New("mp should be a struct's pointer")
)
View Source
var (
	Bit       = "BIT"
	TinyInt   = "TINYINT"
	SmallInt  = "SMALLINT"
	MediumInt = "MEDIUMINT"
	Int       = "INT"
	Integer   = "INTEGER"
	BigInt    = "BIGINT"

	Enum = "ENUM"
	Set  = "SET"

	Char             = "CHAR"
	Varchar          = "VARCHAR"
	NChar            = "NCHAR"
	NVarchar         = "NVARCHAR"
	TinyText         = "TINYTEXT"
	Text             = "TEXT"
	NText            = "NTEXT"
	Clob             = "CLOB"
	MediumText       = "MEDIUMTEXT"
	LongText         = "LONGTEXT"
	Uuid             = "UUID"
	UniqueIdentifier = "UNIQUEIDENTIFIER"
	SysName          = "SYSNAME"

	Date          = "DATE"
	DateTime      = "DATETIME"
	SmallDateTime = "SMALLDATETIME"
	Time          = "TIME"
	TimeStamp     = "TIMESTAMP"
	TimeStampz    = "TIMESTAMPZ"
	Year          = "YEAR"

	Decimal    = "DECIMAL"
	Numeric    = "NUMERIC"
	Money      = "MONEY"
	SmallMoney = "SMALLMONEY"

	Real   = "REAL"
	Float  = "FLOAT"
	Double = "DOUBLE"

	Binary     = "BINARY"
	VarBinary  = "VARBINARY"
	TinyBlob   = "TINYBLOB"
	Blob       = "BLOB"
	MediumBlob = "MEDIUMBLOB"
	LongBlob   = "LONGBLOB"
	Bytea      = "BYTEA"

	Bool    = "BOOL"
	Boolean = "BOOLEAN"

	Serial    = "SERIAL"
	BigSerial = "BIGSERIAL"

	Json  = "JSON"
	Jsonb = "JSONB"

	SqlTypes = map[string]int{
		Bit:       NUMERIC_TYPE,
		TinyInt:   NUMERIC_TYPE,
		SmallInt:  NUMERIC_TYPE,
		MediumInt: NUMERIC_TYPE,
		Int:       NUMERIC_TYPE,
		Integer:   NUMERIC_TYPE,
		BigInt:    NUMERIC_TYPE,

		Enum:  TEXT_TYPE,
		Set:   TEXT_TYPE,
		Json:  TEXT_TYPE,
		Jsonb: TEXT_TYPE,

		Char:       TEXT_TYPE,
		NChar:      TEXT_TYPE,
		Varchar:    TEXT_TYPE,
		NVarchar:   TEXT_TYPE,
		TinyText:   TEXT_TYPE,
		Text:       TEXT_TYPE,
		NText:      TEXT_TYPE,
		MediumText: TEXT_TYPE,
		LongText:   TEXT_TYPE,
		Uuid:       TEXT_TYPE,
		Clob:       TEXT_TYPE,
		SysName:    TEXT_TYPE,

		Date:          TIME_TYPE,
		DateTime:      TIME_TYPE,
		Time:          TIME_TYPE,
		TimeStamp:     TIME_TYPE,
		TimeStampz:    TIME_TYPE,
		SmallDateTime: TIME_TYPE,
		Year:          TIME_TYPE,

		Decimal:    NUMERIC_TYPE,
		Numeric:    NUMERIC_TYPE,
		Real:       NUMERIC_TYPE,
		Float:      NUMERIC_TYPE,
		Double:     NUMERIC_TYPE,
		Money:      NUMERIC_TYPE,
		SmallMoney: NUMERIC_TYPE,

		Binary:    BLOB_TYPE,
		VarBinary: BLOB_TYPE,

		TinyBlob:         BLOB_TYPE,
		Blob:             BLOB_TYPE,
		MediumBlob:       BLOB_TYPE,
		LongBlob:         BLOB_TYPE,
		Bytea:            BLOB_TYPE,
		UniqueIdentifier: BLOB_TYPE,

		Bool: NUMERIC_TYPE,

		Serial:    NUMERIC_TYPE,
		BigSerial: NUMERIC_TYPE,
	}
)
View Source
var (
	IntType   = reflect.TypeOf(c_INT_DEFAULT)
	Int8Type  = reflect.TypeOf(c_INT8_DEFAULT)
	Int16Type = reflect.TypeOf(c_INT16_DEFAULT)
	Int32Type = reflect.TypeOf(c_INT32_DEFAULT)
	Int64Type = reflect.TypeOf(c_INT64_DEFAULT)

	UintType   = reflect.TypeOf(c_UINT_DEFAULT)
	Uint8Type  = reflect.TypeOf(c_UINT8_DEFAULT)
	Uint16Type = reflect.TypeOf(c_UINT16_DEFAULT)
	Uint32Type = reflect.TypeOf(c_UINT32_DEFAULT)
	Uint64Type = reflect.TypeOf(c_UINT64_DEFAULT)

	Float32Type = reflect.TypeOf(c_FLOAT32_DEFAULT)
	Float64Type = reflect.TypeOf(c_FLOAT64_DEFAULT)

	Complex64Type  = reflect.TypeOf(c_COMPLEX64_DEFAULT)
	Complex128Type = reflect.TypeOf(c_COMPLEX128_DEFAULT)

	StringType = reflect.TypeOf(c_EMPTY_STRING)
	BoolType   = reflect.TypeOf(c_BOOL_DEFAULT)
	ByteType   = reflect.TypeOf(c_BYTE_DEFAULT)
	BytesType  = reflect.SliceOf(ByteType)

	TimeType = reflect.TypeOf(c_TIME_DEFAULT)
)
View Source
var (
	PtrIntType   = reflect.PtrTo(IntType)
	PtrInt8Type  = reflect.PtrTo(Int8Type)
	PtrInt16Type = reflect.PtrTo(Int16Type)
	PtrInt32Type = reflect.PtrTo(Int32Type)
	PtrInt64Type = reflect.PtrTo(Int64Type)

	PtrUintType   = reflect.PtrTo(UintType)
	PtrUint8Type  = reflect.PtrTo(Uint8Type)
	PtrUint16Type = reflect.PtrTo(Uint16Type)
	PtrUint32Type = reflect.PtrTo(Uint32Type)
	PtrUint64Type = reflect.PtrTo(Uint64Type)

	PtrFloat32Type = reflect.PtrTo(Float32Type)
	PtrFloat64Type = reflect.PtrTo(Float64Type)

	PtrComplex64Type  = reflect.PtrTo(Complex64Type)
	PtrComplex128Type = reflect.PtrTo(Complex128Type)

	PtrStringType = reflect.PtrTo(StringType)
	PtrBoolType   = reflect.PtrTo(BoolType)
	PtrByteType   = reflect.PtrTo(ByteType)

	PtrTimeType = reflect.PtrTo(TimeType)
)
View Source
var (
	// DefaultCacheSize sets the default cache size
	DefaultCacheSize = 200
)
View Source
var LintGonicMapper = GonicMapper{
	"API":   true,
	"ASCII": true,
	"CPU":   true,
	"CSS":   true,
	"DNS":   true,
	"EOF":   true,
	"GUID":  true,
	"HTML":  true,
	"HTTP":  true,
	"HTTPS": true,
	"ID":    true,
	"IP":    true,
	"JSON":  true,
	"LHS":   true,
	"QPS":   true,
	"RAM":   true,
	"RHS":   true,
	"RPC":   true,
	"SLA":   true,
	"SMTP":  true,
	"SSH":   true,
	"TLS":   true,
	"TTL":   true,
	"UI":    true,
	"UID":   true,
	"UUID":  true,
	"URI":   true,
	"URL":   true,
	"UTF8":  true,
	"VM":    true,
	"XML":   true,
	"XSRF":  true,
	"XSS":   true,
}

LintGonicMapper is A GonicMapper that contains a list of common initialisms taken from golang/lint

Functions

func GenSqlKey

func GenSqlKey(sql string, args interface{}) string

GenSqlKey generates cache key

func MapToSlice

func MapToSlice(query string, mp interface{}) (string, []interface{}, error)

func PutCacheSql

func PutCacheSql(m Cacher, ids []PK, tableName, sql string, args interface{}) error

PutCacheSql puts cacher SQL and PKs

func RegisterDialect

func RegisterDialect(dbName DbType, dialectFunc func() Dialect)

RegisterDialect register database dialect

func RegisterDriver

func RegisterDriver(driverName string, driver Driver)

func RegisteredDriverSize

func RegisteredDriverSize() int

func SQLType2Type

func SQLType2Type(st SQLType) reflect.Type

default sql type change to go types

func StructToSlice

func StructToSlice(query string, st interface{}) (string, []interface{}, error)

Types

type Base

type Base struct {
	*Uri
	// contains filtered or unexported fields
}

Base represents a basic dialect and all real dialects could embed this struct

func (*Base) AndStr

func (b *Base) AndStr() string

func (*Base) CreateIndexSql

func (db *Base) CreateIndexSql(tableName string, index *Index) string

func (*Base) CreateTableSql

func (b *Base) CreateTableSql(table *Table, tableName, storeEngine, charset string) string

func (*Base) DB

func (b *Base) DB() *DB

func (*Base) DBType

func (b *Base) DBType() DbType

func (*Base) DataSourceName

func (b *Base) DataSourceName() string

func (*Base) DriverName

func (b *Base) DriverName() string

func (*Base) DropIndexSql

func (db *Base) DropIndexSql(tableName string, index *Index) string

func (*Base) DropTableSql

func (db *Base) DropTableSql(tableName string) string

func (*Base) EqStr

func (b *Base) EqStr() string

func (*Base) ForUpdateSql

func (b *Base) ForUpdateSql(query string) string

func (*Base) FormatBytes

func (b *Base) FormatBytes(bs []byte) string

func (*Base) HasRecords

func (db *Base) HasRecords(query string, args ...interface{}) (bool, error)

func (*Base) Init

func (b *Base) Init(db *DB, dialect Dialect, uri *Uri, drivername, dataSourceName string) error

func (*Base) IsColumnExist

func (db *Base) IsColumnExist(tableName, colName string) (bool, error)

func (*Base) LogSQL

func (b *Base) LogSQL(sql string, args []interface{})

func (*Base) ModifyColumnSql

func (db *Base) ModifyColumnSql(tableName string, col *Column) string

func (*Base) OrStr

func (b *Base) OrStr() string

func (*Base) RollBackStr

func (db *Base) RollBackStr() string

func (*Base) SetLogger

func (b *Base) SetLogger(logger ILogger)

func (*Base) SetParams

func (b *Base) SetParams(params map[string]string)

func (*Base) ShowCreateNull

func (b *Base) ShowCreateNull() bool

func (*Base) SupportDropIfExists

func (db *Base) SupportDropIfExists() bool

func (*Base) URI

func (b *Base) URI() *Uri

type CacheMapper

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

func NewCacheMapper

func NewCacheMapper(mapper IMapper) *CacheMapper

func (*CacheMapper) Obj2Table

func (m *CacheMapper) Obj2Table(o string) string

func (*CacheMapper) Table2Obj

func (m *CacheMapper) Table2Obj(t string) string

type CacheStore

type CacheStore interface {
	// key is primary key or composite primary key
	// value is struct's pointer
	// key format : <tablename>-p-<pk1>-<pk2>...
	Put(key string, value interface{}) error
	Get(key string) (interface{}, error)
	Del(key string) error
}

CacheStore is a interface to store cache

type Cacher

type Cacher interface {
	GetIds(tableName, sql string) interface{}
	GetBean(tableName string, id string) interface{}
	PutIds(tableName, sql string, ids interface{})
	PutBean(tableName string, id string, obj interface{})
	DelIds(tableName, sql string)
	DelBean(tableName string, id string)
	ClearIds(tableName string)
	ClearBeans(tableName string)
}

Cacher is an interface to provide cache id format : u-<pk1>-<pk2>...

type Column

type Column struct {
	Name            string
	TableName       string
	FieldName       string
	SQLType         SQLType
	IsJSON          bool
	Length          int
	Length2         int
	Nullable        bool
	Default         string
	Indexes         map[string]int
	IsPrimaryKey    bool
	IsAutoIncrement bool
	MapType         int
	IsCreated       bool
	IsUpdated       bool
	IsDeleted       bool
	IsCascade       bool
	IsVersion       bool
	DefaultIsEmpty  bool // false means column has no default set, but not default value is empty
	EnumOptions     map[string]int
	SetOptions      map[string]int
	DisableTimeZone bool
	TimeZone        *time.Location // column specified time zone
	Comment         string
}

Column defines database column

func NewColumn

func NewColumn(name, fieldName string, sqlType SQLType, len1, len2 int, nullable bool) *Column

NewColumn creates a new column

func (*Column) String

func (col *Column) String(d Dialect) string

String generate column description string according dialect

func (*Column) StringNoPk

func (col *Column) StringNoPk(d Dialect) string

StringNoPk generate column description string according dialect without primary keys

func (*Column) ValueOf

func (col *Column) ValueOf(bean interface{}) (*reflect.Value, error)

ValueOf returns column's filed of struct's value

func (*Column) ValueOfV

func (col *Column) ValueOfV(dataStruct *reflect.Value) (*reflect.Value, error)

ValueOfV returns column's filed of struct's value accept reflevt value

type Conversion

type Conversion interface {
	FromDB([]byte) error
	ToDB() ([]byte, error)
}

Conversion is an interface. A type implements Conversion will according the custom method to fill into database and retrieve from database.

type DB

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

DB is a wrap of sql.DB with extra contents

func FromDB

func FromDB(db *sql.DB) *DB

FromDB creates a DB from a sql.DB

func Open

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

Open opens a database

func OpenDialect

func OpenDialect(dialect Dialect) (*DB, error)

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) ExecMap

func (db *DB) ExecMap(query string, mp interface{}) (sql.Result, error)

func (*DB) ExecMapContext

func (db *DB) ExecMapContext(ctx context.Context, query string, mp interface{}) (sql.Result, error)

ExecMapContext exec map with context.Context insert into (name) values (?) insert into (name) values (?name)

func (*DB) ExecStruct

func (db *DB) ExecStruct(query string, st interface{}) (sql.Result, error)

func (*DB) ExecStructContext

func (db *DB) ExecStructContext(ctx context.Context, query string, st interface{}) (sql.Result, error)

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(query string, args ...interface{}) (*Rows, error)

Query overwrites sql.DB.Query

func (*DB) QueryContext

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

QueryContext overwrites sql.DB.QueryContext

func (*DB) QueryMap

func (db *DB) QueryMap(query string, mp interface{}) (*Rows, error)

QueryMap executes query with parameters via map

func (*DB) QueryMapContext

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

QueryMapContext executes query with parameters via map and context

func (*DB) QueryRow

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

func (*DB) QueryRowContext

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

func (*DB) QueryRowMap

func (db *DB) QueryRowMap(query string, mp interface{}) *Row

func (*DB) QueryRowMapContext

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

func (*DB) QueryRowStruct

func (db *DB) QueryRowStruct(query string, st interface{}) *Row

func (*DB) QueryRowStructContext

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

func (*DB) QueryStruct

func (db *DB) QueryStruct(query string, st interface{}) (*Rows, error)

func (*DB) QueryStructContext

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

type DbType

type DbType string

type Dialect

type Dialect interface {
	SetLogger(logger ILogger)
	Init(*DB, *Uri, string, string) error
	URI() *Uri
	DB() *DB
	DBType() DbType
	SqlType(*Column) string
	FormatBytes(b []byte) string

	DriverName() string
	DataSourceName() string

	IsReserved(string) bool
	Quote(string) string

	AndStr() string
	OrStr() string
	EqStr() string
	RollBackStr() string
	AutoIncrStr() string

	SupportInsertMany() bool
	SupportEngine() bool
	SupportCharset() bool
	SupportDropIfExists() bool
	IndexOnTable() bool
	ShowCreateNull() bool

	IndexCheckSql(tableName, idxName string) (string, []interface{})
	TableCheckSql(tableName string) (string, []interface{})

	IsColumnExist(tableName string, colName string) (bool, error)

	CreateTableSql(table *Table, tableName, storeEngine, charset string) string
	DropTableSql(tableName string) string
	CreateIndexSql(tableName string, index *Index) string
	DropIndexSql(tableName string, index *Index) string

	ModifyColumnSql(tableName string, col *Column) string

	ForUpdateSql(query string) string

	GetColumns(tableName string) ([]string, map[string]*Column, error)
	GetTables() ([]*Table, error)
	GetIndexes(tableName string) (map[string]*Index, error)

	Filters() []Filter
	SetParams(params map[string]string)
}

a dialect is a driver's wrapper

func QueryDialect

func QueryDialect(dbName DbType) Dialect

QueryDialect query if registered database dialect

type Driver

type Driver interface {
	Parse(string, string) (*Uri, error)
}

func QueryDriver

func QueryDriver(driverName string) Driver

type EmptyScanner

type EmptyScanner struct {
}

func (EmptyScanner) Scan

func (EmptyScanner) Scan(src interface{}) error

type Filter

type Filter interface {
	Do(sql string, dialect Dialect, table *Table) string
}

Filter is an interface to filter SQL

type GonicMapper

type GonicMapper map[string]bool

GonicMapper implements IMapper. It will consider initialisms when mapping names. E.g. id -> ID, user -> User and to table names: UserID -> user_id, MyUID -> my_uid

func (GonicMapper) Obj2Table

func (mapper GonicMapper) Obj2Table(name string) string

func (GonicMapper) Table2Obj

func (mapper GonicMapper) Table2Obj(name string) string

type ILogger

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

	Level() LogLevel
	SetLevel(l LogLevel)

	ShowSQL(show ...bool)
	IsShowSQL() bool
}

ILogger is a logger interface

type IMapper

type IMapper interface {
	Obj2Table(string) string
	Table2Obj(string) string
}

IMapper represents a name convertation between struct's fields name and table's column name

type IdFilter

type IdFilter struct {
}

IdFilter filter SQL replace (id) to primary key column name

func (*IdFilter) Do

func (i *IdFilter) Do(sql string, dialect Dialect, table *Table) string

type Index

type Index struct {
	IsRegular bool
	Name      string
	Type      int
	Cols      []string
}

Index represents a database index

func NewIndex

func NewIndex(name string, indexType int) *Index

NewIndex new an index object

func (*Index) AddColumn

func (index *Index) AddColumn(cols ...string)

AddColumn add columns which will be composite index

func (*Index) Equal

func (index *Index) Equal(dst *Index) bool

func (*Index) XName

func (index *Index) XName(tableName string) string

type LogLevel

type LogLevel int

LogLevel defines a log level

const (
	// !nashtsai! following level also match syslog.Priority value
	LOG_DEBUG LogLevel = iota
	LOG_INFO
	LOG_WARNING
	LOG_ERR
	LOG_OFF
	LOG_UNKNOWN
)

enumerate all LogLevels

type NullTime

type NullTime time.Time

func (*NullTime) Scan

func (ns *NullTime) Scan(value interface{}) error

func (NullTime) Value

func (ns NullTime) Value() (driver.Value, error)

Value implements the driver Valuer interface.

type PK

type PK []interface{}

func GetCacheSql

func GetCacheSql(m Cacher, tableName, sql string, args interface{}) ([]PK, error)

GetCacheSql returns cacher PKs via SQL

func NewPK

func NewPK(pks ...interface{}) *PK

func (*PK) FromString

func (p *PK) FromString(content string) error

func (*PK) ToString

func (p *PK) ToString() (string, error)

type PrefixMapper

type PrefixMapper struct {
	Mapper IMapper
	Prefix string
}

PrefixMapper provides prefix table name support

func NewPrefixMapper

func NewPrefixMapper(mapper IMapper, prefix string) PrefixMapper

func (PrefixMapper) Obj2Table

func (mapper PrefixMapper) Obj2Table(name string) string

func (PrefixMapper) Table2Obj

func (mapper PrefixMapper) Table2Obj(name string) string

type QuoteFilter

type QuoteFilter struct {
}

QuoteFilter filter SQL replace ` to database's own quote character

func (*QuoteFilter) Do

func (s *QuoteFilter) Do(sql string, dialect Dialect, table *Table) string

type Quoter

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

func NewQuoter

func NewQuoter(dialect Dialect) *Quoter

func (*Quoter) Quote

func (q *Quoter) Quote(content string) string

type Row

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

func ErrorRow

func ErrorRow(err error) *Row

ErrorRow return an error row

func NewRow

func NewRow(rows *Rows, err error) *Row

NewRow from rows

func (*Row) Columns

func (row *Row) Columns() ([]string, error)

func (*Row) Scan

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

func (*Row) ScanMap

func (row *Row) ScanMap(dest interface{}) error

scan data to a map's pointer

func (*Row) ScanSlice

func (row *Row) ScanSlice(dest interface{}) error

scan data to a slice's pointer, slice's length should equal to columns' number

func (*Row) ScanStructByIndex

func (row *Row) ScanStructByIndex(dest interface{}) error

func (*Row) ScanStructByName

func (row *Row) ScanStructByName(dest interface{}) error

func (*Row) ToMapString

func (row *Row) ToMapString() (map[string]string, error)

type Rows

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

func (*Rows) ScanMap

func (rs *Rows) ScanMap(dest interface{}) error

scan data to a map's pointer

func (*Rows) ScanSlice

func (rs *Rows) ScanSlice(dest interface{}) error

scan data to a slice's pointer, slice's length should equal to columns' number

func (*Rows) ScanStructByIndex

func (rs *Rows) ScanStructByIndex(dest ...interface{}) error

scan data to a struct's pointer according field index

func (*Rows) ScanStructByName

func (rs *Rows) ScanStructByName(dest interface{}) error

scan data to a struct's pointer according field name

func (*Rows) ToMapString

func (rs *Rows) ToMapString() ([]map[string]string, error)

type SQLType

type SQLType struct {
	Name           string
	DefaultLength  int
	DefaultLength2 int
}

xorm SQL types

func Type2SQLType

func Type2SQLType(t reflect.Type) (st SQLType)

Type2SQLType generate SQLType acorrding Go's type

func (*SQLType) IsBlob

func (s *SQLType) IsBlob() bool

func (*SQLType) IsJson

func (s *SQLType) IsJson() bool

func (*SQLType) IsNumeric

func (s *SQLType) IsNumeric() bool

func (*SQLType) IsText

func (s *SQLType) IsText() bool

func (*SQLType) IsTime

func (s *SQLType) IsTime() bool

func (*SQLType) IsType

func (s *SQLType) IsType(st int) bool

type SameMapper

type SameMapper struct {
}

SameMapper implements IMapper and provides same name between struct and database table

func (SameMapper) Obj2Table

func (m SameMapper) Obj2Table(o string) string

func (SameMapper) Table2Obj

func (m SameMapper) Table2Obj(t string) string

type SeqFilter

type SeqFilter struct {
	Prefix string
	Start  int
}

SeqFilter filter SQL replace ?, ? ... to $1, $2 ...

func (*SeqFilter) Do

func (s *SeqFilter) Do(sql string, dialect Dialect, table *Table) string

type SnakeMapper

type SnakeMapper struct {
}

SnakeMapper implements IMapper and provides name transaltion between struct and database table

func (SnakeMapper) Obj2Table

func (mapper SnakeMapper) Obj2Table(name string) string

func (SnakeMapper) Table2Obj

func (mapper SnakeMapper) Table2Obj(name string) string

type Stmt

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

Stmt reprents a stmt objects

func (*Stmt) ExecMap

func (s *Stmt) ExecMap(mp interface{}) (sql.Result, error)

func (*Stmt) ExecMapContext

func (s *Stmt) ExecMapContext(ctx context.Context, mp interface{}) (sql.Result, error)

func (*Stmt) ExecStruct

func (s *Stmt) ExecStruct(st interface{}) (sql.Result, error)

func (*Stmt) ExecStructContext

func (s *Stmt) ExecStructContext(ctx context.Context, st interface{}) (sql.Result, error)

func (*Stmt) Query

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

func (*Stmt) QueryContext

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

func (*Stmt) QueryMap

func (s *Stmt) QueryMap(mp interface{}) (*Rows, error)

func (*Stmt) QueryMapContext

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

func (*Stmt) QueryRow

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

func (*Stmt) QueryRowContext

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

func (*Stmt) QueryRowMap

func (s *Stmt) QueryRowMap(mp interface{}) *Row

func (*Stmt) QueryRowMapContext

func (s *Stmt) QueryRowMapContext(ctx context.Context, mp interface{}) *Row

func (*Stmt) QueryRowStruct

func (s *Stmt) QueryRowStruct(st interface{}) *Row

func (*Stmt) QueryRowStructContext

func (s *Stmt) QueryRowStructContext(ctx context.Context, st interface{}) *Row

func (*Stmt) QueryStruct

func (s *Stmt) QueryStruct(st interface{}) (*Rows, error)

func (*Stmt) QueryStructContext

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

type SuffixMapper

type SuffixMapper struct {
	Mapper IMapper
	Suffix string
}

SuffixMapper provides suffix table name support

func NewSuffixMapper

func NewSuffixMapper(mapper IMapper, suffix string) SuffixMapper

func (SuffixMapper) Obj2Table

func (mapper SuffixMapper) Obj2Table(name string) string

func (SuffixMapper) Table2Obj

func (mapper SuffixMapper) Table2Obj(name string) string

type Table

type Table struct {
	Name string
	Type reflect.Type

	Indexes       map[string]*Index
	PrimaryKeys   []string
	AutoIncrement string
	Created       map[string]bool
	Updated       string
	Deleted       string
	Version       string
	Cacher        Cacher
	StoreEngine   string
	Charset       string
	Comment       string
	// contains filtered or unexported fields
}

Table represents a database table

func NewEmptyTable

func NewEmptyTable() *Table

func NewTable

func NewTable(name string, t reflect.Type) *Table

NewTable creates a new Table object

func (*Table) AddColumn

func (table *Table) AddColumn(col *Column)

AddColumn adds a column to table

func (*Table) AddIndex

func (table *Table) AddIndex(index *Index)

AddIndex adds an index or an unique to table

func (*Table) AutoIncrColumn

func (table *Table) AutoIncrColumn() *Column

func (*Table) ColumnType

func (table *Table) ColumnType(name string) reflect.Type

func (*Table) Columns

func (table *Table) Columns() []*Column

func (*Table) ColumnsSeq

func (table *Table) ColumnsSeq() []string

func (*Table) DeletedColumn

func (table *Table) DeletedColumn() *Column

func (*Table) GetColumn

func (table *Table) GetColumn(name string) *Column

func (*Table) GetColumnIdx

func (table *Table) GetColumnIdx(name string, idx int) *Column

func (*Table) PKColumns

func (table *Table) PKColumns() []*Column

PKColumns reprents all primary key columns

func (*Table) UpdatedColumn

func (table *Table) UpdatedColumn() *Column

func (*Table) VersionColumn

func (table *Table) VersionColumn() *Column

type Tx

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

func (*Tx) ExecMap

func (tx *Tx) ExecMap(query string, mp interface{}) (sql.Result, error)

func (*Tx) ExecMapContext

func (tx *Tx) ExecMapContext(ctx context.Context, query string, mp interface{}) (sql.Result, error)

func (*Tx) ExecStruct

func (tx *Tx) ExecStruct(query string, st interface{}) (sql.Result, error)

func (*Tx) ExecStructContext

func (tx *Tx) ExecStructContext(ctx context.Context, query string, st interface{}) (sql.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(query string, args ...interface{}) (*Rows, error)

func (*Tx) QueryContext

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

func (*Tx) QueryMap

func (tx *Tx) QueryMap(query string, mp interface{}) (*Rows, error)

func (*Tx) QueryMapContext

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

func (*Tx) QueryRow

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

func (*Tx) QueryRowContext

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

func (*Tx) QueryRowMap

func (tx *Tx) QueryRowMap(query string, mp interface{}) *Row

func (*Tx) QueryRowMapContext

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

func (*Tx) QueryRowStruct

func (tx *Tx) QueryRowStruct(query string, st interface{}) *Row

func (*Tx) QueryRowStructContext

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

func (*Tx) QueryStruct

func (tx *Tx) QueryStruct(query string, st interface{}) (*Rows, error)

func (*Tx) QueryStructContext

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

func (*Tx) Stmt

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

func (*Tx) StmtContext

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

type Uri

type Uri struct {
	DbType  DbType
	Proto   string
	Host    string
	Port    string
	DbName  string
	User    string
	Passwd  string
	Charset string
	Laddr   string
	Raddr   string
	Timeout time.Duration
	Schema  string
}

Jump to

Keyboard shortcuts

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