gdb

package
v1.12.2 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2020 License: MIT Imports: 32 Imported by: 165

Documentation

Overview

Package gdb provides ORM features for popular relationship databases.

Index

Constants

View Source
const (
	ORM_TAG_FOR_STRUCT  = "orm"
	ORM_TAG_FOR_UNIQUE  = "unique"
	ORM_TAG_FOR_PRIMARY = "primary"
)
View Source
const (
	OPTION_OMITEMPTY = 1 << iota
	OPTION_ALLOWEMPTY
)
View Source
const (
	DEFAULT_GROUP_NAME = "default" // Default group name.
)

Variables

View Source
var (
	// ErrNoRows is alias of sql.ErrNoRows.
	ErrNoRows = sql.ErrNoRows
)

Functions

func AddConfigNode

func AddConfigNode(group string, node ConfigNode)

AddConfigNode adds one node configuration to configuration of given group.

func AddDefaultConfigGroup

func AddDefaultConfigGroup(nodes ConfigGroup)

AddDefaultConfigGroup adds multiple node configurations to configuration of default group.

func AddDefaultConfigNode

func AddDefaultConfigNode(node ConfigNode)

AddDefaultConfigNode adds one node configuration to configuration of default group.

func DataToMapDeep added in v1.11.6

func DataToMapDeep(obj interface{}) map[string]interface{}

DataToMapDeep converts struct object to map type recursively.

func FormatSqlWithArgs added in v1.12.0

func FormatSqlWithArgs(sql string, args []interface{}) string

FormatSqlWithArgs binds the arguments to the sql string and returns a complete sql string, just for debugging.

func GetDefaultGroup

func GetDefaultGroup() string

GetDefaultGroup returns the { name of default configuration.

func GetInsertOperationByOption added in v1.11.6

func GetInsertOperationByOption(option int) string

GetInsertOperationByOption returns proper insert option with given parameter <option>.

func GetPrimaryKey added in v1.10.1

func GetPrimaryKey(pointer interface{}) string

GetPrimaryKey retrieves and returns primary key field name from given struct.

func GetPrimaryKeyCondition added in v1.10.1

func GetPrimaryKeyCondition(primary string, where ...interface{}) (newWhereCondition []interface{})

GetPrimaryKeyCondition returns a new where condition by primary field name. The optional parameter <where> is like follows: 123 []int{1, 2, 3} "john" []string{"john", "smith"} g.Map{"id": g.Slice{1,2,3}} g.Map{"id": 1, "name": "john"} etc.

Note that it returns the given <where> parameter directly if there's the <primary> is empty.

func GetWhereConditionOfStruct

func GetWhereConditionOfStruct(pointer interface{}) (where string, args []interface{})

GetWhereConditionOfStruct returns the where condition sql and arguments by given struct pointer. This function automatically retrieves primary or unique field and its attribute value as condition.

func Register added in v1.11.6

func Register(name string, driver Driver) error

Register registers custom database driver to gdb.

func SetConfig

func SetConfig(config Config)

SetConfig sets the global configuration for package. It will overwrite the old configuration of package.

func SetConfigGroup

func SetConfigGroup(group string, nodes ConfigGroup)

SetConfigGroup sets the configuration for given group.

func SetDefaultGroup

func SetDefaultGroup(name string)

SetDefaultGroup sets the group name for default configuration.

Types

type Config

type Config map[string]ConfigGroup

Config is the configuration management object.

type ConfigGroup

type ConfigGroup []ConfigNode

ConfigGroup is a slice of configuration node for specified named group.

func GetConfig

func GetConfig(group string) ConfigGroup

GetConfig retrieves and returns the configuration of given group.

type ConfigNode

type ConfigNode struct {
	Host             string        // Host of server, ip or domain like: 127.0.0.1, localhost
	Port             string        // Port, it's commonly 3306.
	User             string        // Authentication username.
	Pass             string        // Authentication password.
	Name             string        // Default used database name.
	Type             string        // Database type: mysql, sqlite, mssql, pgsql, oracle.
	Role             string        // (Optional, "master" in default) Node role, used for master-slave mode: master, slave.
	Debug            bool          // (Optional) Debug mode enables debug information logging and output.
	Prefix           string        // (Optional) Table prefix.
	DryRun           bool          // (Optional) Dry run, which does SELECT but no INSERT/UPDATE/DELETE statements.
	Weight           int           // (Optional) Weight for load balance calculating, it's useless if there's just one node.
	Charset          string        // (Optional, "utf8mb4" in default) Custom charset when operating on database.
	LinkInfo         string        // (Optional) Custom link information, when it is used, configuration Host/Port/User/Pass/Name are ignored.
	MaxIdleConnCount int           // (Optional) Max idle connection configuration for underlying connection pool.
	MaxOpenConnCount int           // (Optional) Max open connection configuration for underlying connection pool.
	MaxConnLifetime  time.Duration // (Optional) Max connection TTL configuration for underlying connection pool.
}

ConfigNode is configuration for one node.

func (*ConfigNode) String

func (node *ConfigNode) String() string

String returns the node as string.

type Core added in v1.11.6

type Core struct {
	DB DB // DB interface object.
	// contains filtered or unexported fields
}

Core is the base struct for database management.

func (*Core) BatchInsert added in v1.11.6

func (c *Core) BatchInsert(table string, list interface{}, batch ...int) (sql.Result, error)

BatchInsert batch inserts data. The parameter <list> must be type of slice of map or struct.

func (*Core) BatchInsertIgnore added in v1.11.6

func (c *Core) BatchInsertIgnore(table string, list interface{}, batch ...int) (sql.Result, error)

BatchInsert batch inserts data with ignore option. The parameter <list> must be type of slice of map or struct.

func (*Core) BatchReplace added in v1.11.6

func (c *Core) BatchReplace(table string, list interface{}, batch ...int) (sql.Result, error)

BatchReplace batch replaces data. The parameter <list> must be type of slice of map or struct.

func (*Core) BatchSave added in v1.11.6

func (c *Core) BatchSave(table string, list interface{}, batch ...int) (sql.Result, error)

BatchSave batch replaces data. The parameter <list> must be type of slice of map or struct.

func (*Core) Begin added in v1.11.6

func (c *Core) Begin() (*TX, error)

Begin starts and returns the transaction object. You should call Commit or Rollback functions of the transaction object if you no longer use the transaction. Commit or Rollback functions will also close the transaction automatically.

func (*Core) Delete added in v1.11.6

func (c *Core) Delete(table string, condition interface{}, args ...interface{}) (result sql.Result, err error)

Delete does "DELETE FROM ... " statement for the table.

The parameter <condition> can be type of string/map/gmap/slice/struct/*struct, etc. It is commonly used with parameter <args>. Eg: "uid=10000", "uid", 10000 "money>? AND name like ?", 99999, "vip_%" "status IN (?)", g.Slice{1,2,3} "age IN(?,?)", 18, 50 User{ Id : 1, UserName : "john"}

func (*Core) DoBatchInsert added in v1.11.6

func (c *Core) DoBatchInsert(link Link, table string, list interface{}, option int, batch ...int) (result sql.Result, err error)

DoBatchInsert batch inserts/replaces/saves data.

func (*Core) DoDelete added in v1.11.6

func (c *Core) DoDelete(link Link, table string, condition string, args ...interface{}) (result sql.Result, err error)

DoDelete does "DELETE FROM ... " statement for the table. Also see Delete.

func (*Core) DoExec added in v1.11.6

func (c *Core) DoExec(link Link, sql string, args ...interface{}) (result sql.Result, err error)

DoExec commits the sql string and its arguments to underlying driver through given link object and returns the execution result.

func (*Core) DoGetAll added in v1.11.6

func (c *Core) DoGetAll(link Link, sql string, args ...interface{}) (result Result, err error)

DoGetAll queries and returns data records from database.

func (*Core) DoInsert added in v1.11.6

func (c *Core) DoInsert(link Link, table string, data interface{}, option int, batch ...int) (result sql.Result, err error)

doInsert inserts or updates data for given table.

The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})

The parameter <option> values are as follows: 0: insert: just insert, if there's unique/primary key in the data, it returns error; 1: replace: if there's unique/primary key in the data, it deletes it from table and inserts a new one; 2: save: if there's unique/primary key in the data, it updates it or else inserts a new one; 3: ignore: if there's unique/primary key in the data, it ignores the inserting;

func (*Core) DoPrepare added in v1.11.6

func (c *Core) DoPrepare(link Link, sql string) (*sql.Stmt, error)

doPrepare calls prepare function on given link object and returns the statement object.

func (*Core) DoQuery added in v1.11.6

func (c *Core) DoQuery(link Link, sql string, args ...interface{}) (rows *sql.Rows, err error)

DoQuery commits the sql string and its arguments to underlying driver through given link object and returns the execution result.

func (*Core) DoUpdate added in v1.11.6

func (c *Core) DoUpdate(link Link, table string, data interface{}, condition string, args ...interface{}) (result sql.Result, err error)

doUpdate does "UPDATE ... " statement for the table. Also see Update.

func (*Core) Exec added in v1.11.6

func (c *Core) Exec(sql string, args ...interface{}) (result sql.Result, err error)

Exec commits one query SQL to underlying driver and returns the execution result. It is most commonly used for data inserting and updating.

func (*Core) GetAll added in v1.11.6

func (c *Core) GetAll(sql string, args ...interface{}) (Result, error)

GetAll queries and returns data records from database.

func (*Core) GetArray added in v1.11.6

func (c *Core) GetArray(sql string, args ...interface{}) ([]Value, error)

GetArray queries and returns data values as slice from database. Note that if there're multiple columns in the result, it returns just one column values randomly.

func (*Core) GetCache added in v1.11.6

func (c *Core) GetCache() *gcache.Cache

GetCache returns the internal cache object.

func (*Core) GetChars added in v1.11.6

func (c *Core) GetChars() (charLeft string, charRight string)

GetChars returns the security char for current database. It does nothing in default.

func (*Core) GetCount added in v1.11.6

func (c *Core) GetCount(sql string, args ...interface{}) (int, error)

GetCount queries and returns the count from database.

func (*Core) GetDebug added in v1.11.6

func (c *Core) GetDebug() bool

GetDebug returns the debug value.

func (*Core) GetDryRun added in v1.12.2

func (c *Core) GetDryRun() bool

GetDryRun returns the DryRun value.

func (*Core) GetGroup added in v1.12.2

func (c *Core) GetGroup() string

GetGroup returns the group string configured.

func (*Core) GetLogger added in v1.11.6

func (c *Core) GetLogger() *glog.Logger

GetLogger returns the logger of the orm.

func (*Core) GetMaster added in v1.11.6

func (c *Core) GetMaster(schema ...string) (*sql.DB, error)

GetMaster acts like function Master but with additional <schema> parameter specifying the schema for the connection. It is defined for internal usage. Also see Master.

func (*Core) GetOne added in v1.11.6

func (c *Core) GetOne(sql string, args ...interface{}) (Record, error)

GetOne queries and returns one record from database.

func (*Core) GetPrefix added in v1.11.6

func (c *Core) GetPrefix() string

GetPrefix returns the table prefix string configured.

func (*Core) GetScan added in v1.11.6

func (c *Core) GetScan(pointer interface{}, sql string, args ...interface{}) error

GetScan queries one or more records from database and converts them to given struct or struct array.

If parameter <pointer> is type of struct pointer, it calls GetStruct internally for the conversion. If parameter <pointer> is type of slice, it calls GetStructs internally for conversion.

func (*Core) GetSchema added in v1.11.6

func (c *Core) GetSchema() string

GetSchema returns the schema configured.

func (*Core) GetSlave added in v1.11.6

func (c *Core) GetSlave(schema ...string) (*sql.DB, error)

GetSlave acts like function Slave but with additional <schema> parameter specifying the schema for the connection. It is defined for internal usage. Also see Slave.

func (*Core) GetStruct added in v1.11.6

func (c *Core) GetStruct(pointer interface{}, sql string, args ...interface{}) error

GetStruct queries one record from database and converts it to given struct. The parameter <pointer> should be a pointer to struct.

func (*Core) GetStructs added in v1.11.6

func (c *Core) GetStructs(pointer interface{}, sql string, args ...interface{}) error

GetStructs queries records from database and converts them to given struct. The parameter <pointer> should be type of struct slice: []struct/[]*struct.

func (*Core) GetValue added in v1.11.6

func (c *Core) GetValue(sql string, args ...interface{}) (Value, error)

GetValue queries and returns the field value from database. The sql should queries only one field from database, or else it returns only one field of the result.

func (*Core) HandleSqlBeforeCommit added in v1.11.6

func (c *Core) HandleSqlBeforeCommit(sql string) string

HandleSqlBeforeCommit handles the sql before posts it to database. It does nothing in default.

func (*Core) Insert added in v1.11.6

func (c *Core) Insert(table string, data interface{}, batch ...int) (sql.Result, error)

Insert does "INSERT INTO ..." statement for the table. If there's already one unique record of the data in the table, it returns error.

The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})

The parameter <batch> specifies the batch operation count when given data is slice.

func (*Core) InsertIgnore added in v1.11.6

func (c *Core) InsertIgnore(table string, data interface{}, batch ...int) (sql.Result, error)

InsertIgnore does "INSERT IGNORE INTO ..." statement for the table. If there's already one unique record of the data in the table, it ignores the inserting.

The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})

The parameter <batch> specifies the batch operation count when given data is slice.

func (*Core) MarshalJSON added in v1.11.6

func (c *Core) MarshalJSON() ([]byte, error)

MarshalJSON implements the interface MarshalJSON for json.Marshal. It just returns the pointer address.

Note that this interface implements mainly for workaround for a json infinite loop bug of Golang version < v1.14.

func (*Core) Master added in v1.11.6

func (c *Core) Master() (*sql.DB, error)

Master creates and returns a connection from master node if master-slave configured. It returns the default connection if master-slave not configured.

func (*Core) Model added in v1.11.6

func (c *Core) Model(table ...string) *Model

Model is alias of Core.Table. See Core.Table.

func (*Core) PingMaster added in v1.11.6

func (c *Core) PingMaster() error

PingMaster pings the master node to check authentication or keeps the connection alive.

func (*Core) PingSlave added in v1.11.6

func (c *Core) PingSlave() error

PingSlave pings the slave node to check authentication or keeps the connection alive.

func (*Core) Prepare added in v1.11.6

func (c *Core) Prepare(sql string, execOnMaster ...bool) (*sql.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.

The parameter <execOnMaster> specifies whether executing the sql on master node, or else it executes the sql on slave node if master-slave configured.

func (*Core) Query added in v1.11.6

func (c *Core) Query(sql string, args ...interface{}) (rows *sql.Rows, err error)

Query commits one query SQL to underlying driver and returns the execution result. It is most commonly used for data querying.

func (*Core) QuotePrefixTableName added in v1.11.6

func (c *Core) QuotePrefixTableName(table string) string

QuotePrefixTableName adds prefix string and quotes chars for the table. It handles table string like: "user", "user u", "user,user_detail", "user u, user_detail ut", "user as u, user_detail as ut".

Note that, this will automatically checks the table prefix whether already added, if true it does nothing to the table name, or else adds the prefix to the table name.

func (*Core) QuoteString added in v1.11.6

func (c *Core) QuoteString(s string) string

QuoteString quotes string with quote chars. Strings like: "user", "user u", "user,user_detail", "user u, user_detail ut", "u.id asc".

func (*Core) QuoteWord added in v1.11.6

func (c *Core) QuoteWord(s string) string

QuoteWord checks given string <s> a word, if true quotes it with security chars of the database and returns the quoted string; or else return <s> without any change.

func (*Core) Replace added in v1.11.6

func (c *Core) Replace(table string, data interface{}, batch ...int) (sql.Result, error)

Replace does "REPLACE INTO ..." statement for the table. If there's already one unique record of the data in the table, it deletes the record and inserts a new one.

The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})

The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc. If given data is type of slice, it then does batch replacing, and the optional parameter <batch> specifies the batch operation count.

func (*Core) Save added in v1.11.6

func (c *Core) Save(table string, data interface{}, batch ...int) (sql.Result, error)

Save does "INSERT INTO ... ON DUPLICATE KEY UPDATE..." statement for the table. It updates the record if there's primary or unique index in the saving data, or else it inserts a new record into the table.

The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})

If given data is type of slice, it then does batch saving, and the optional parameter <batch> specifies the batch operation count.

func (*Core) Schema added in v1.11.6

func (c *Core) Schema(schema string) *Schema

Schema creates and returns a schema.

func (*Core) SetDebug added in v1.11.6

func (c *Core) SetDebug(debug bool)

SetDebug enables/disables the debug mode.

func (*Core) SetDryRun added in v1.12.2

func (c *Core) SetDryRun(dryrun bool)

SetDryRun enables/disables the DryRun feature.

func (*Core) SetLogger added in v1.11.6

func (c *Core) SetLogger(logger *glog.Logger)

SetLogger sets the logger for orm.

func (*Core) SetMaxConnLifetime added in v1.11.6

func (c *Core) SetMaxConnLifetime(d time.Duration)

SetMaxConnLifetime sets the connection TTL for underlying connection pool. If parameter <d> <= 0, it means the connection never expires.

func (*Core) SetMaxIdleConnCount added in v1.11.6

func (c *Core) SetMaxIdleConnCount(n int)

SetMaxIdleConnCount sets the max idle connection count for underlying connection pool.

func (*Core) SetMaxOpenConnCount added in v1.11.6

func (c *Core) SetMaxOpenConnCount(n int)

SetMaxOpenConnCount sets the max open connection count for underlying connection pool.

func (*Core) SetSchema added in v1.11.6

func (c *Core) SetSchema(schema string)

SetSchema changes the schema for this database connection object. Importantly note that when schema configuration changed for the database, it affects all operations on the database object in the future.

func (*Core) Slave added in v1.11.6

func (c *Core) Slave() (*sql.DB, error)

Slave creates and returns a connection from slave node if master-slave configured. It returns the default connection if master-slave not configured.

func (*Core) Table added in v1.11.6

func (c *Core) Table(table ...string) *Model

Table creates and returns a new ORM model from given schema. The parameter <table> can be more than one table names, and also alias name, like:

  1. Table names: Table("user") Table("user u") Table("user, user_detail") Table("user u, user_detail ud")
  2. Table name with alias: Table("user", "u")

func (*Core) TableFields added in v1.11.6

func (c *Core) TableFields(table string, schema ...string) (fields map[string]*TableField, err error)

TableFields retrieves and returns the fields information of specified table of current schema.

Note that it returns a map containing the field name and its corresponding fields. As a map is unsorted, the TableField struct has a "Index" field marks its sequence in the fields.

It's using cache feature to enhance the performance, which is never expired util the process restarts.

It does nothing in default.

func (*Core) Tables added in v1.11.6

func (c *Core) Tables(schema ...string) (tables []string, err error)

Tables retrieves and returns the tables of current schema. It's mainly used in cli tool chain for automatically generating the models.

It does nothing in default.

func (*Core) Update added in v1.11.6

func (c *Core) Update(table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error)

Update does "UPDATE ... " statement for the table.

The parameter <data> can be type of string/map/gmap/struct/*struct, etc. Eg: "uid=10000", "uid", 10000, g.Map{"uid": 10000, "name":"john"}

The parameter <condition> can be type of string/map/gmap/slice/struct/*struct, etc. It is commonly used with parameter <args>. Eg: "uid=10000", "uid", 10000 "money>? AND name like ?", 99999, "vip_%" "status IN (?)", g.Slice{1,2,3} "age IN(?,?)", 18, 50 User{ Id : 1, UserName : "john"}

type DB

type DB interface {
	// Open creates a raw connection object for database with given node configuration.
	// Note that it is not recommended using the this function manually.
	Open(config *ConfigNode) (*sql.DB, error)

	// Query APIs.
	Query(sql string, args ...interface{}) (*sql.Rows, error)
	Exec(sql string, args ...interface{}) (sql.Result, error)
	Prepare(sql string, execOnMaster ...bool) (*sql.Stmt, error)

	// Internal APIs for CURD, which can be overwrote for custom CURD implements.
	DoQuery(link Link, sql string, args ...interface{}) (rows *sql.Rows, err error)
	DoGetAll(link Link, sql string, args ...interface{}) (result Result, err error)
	DoExec(link Link, sql string, args ...interface{}) (result sql.Result, err error)
	DoPrepare(link Link, sql string) (*sql.Stmt, error)
	DoInsert(link Link, table string, data interface{}, option int, batch ...int) (result sql.Result, err error)
	DoBatchInsert(link Link, table string, list interface{}, option int, batch ...int) (result sql.Result, err error)
	DoUpdate(link Link, table string, data interface{}, condition string, args ...interface{}) (result sql.Result, err error)
	DoDelete(link Link, table string, condition string, args ...interface{}) (result sql.Result, err error)

	// Query APIs for convenience purpose.
	GetAll(sql string, args ...interface{}) (Result, error)
	GetOne(sql string, args ...interface{}) (Record, error)
	GetValue(sql string, args ...interface{}) (Value, error)
	GetArray(sql string, args ...interface{}) ([]Value, error)
	GetCount(sql string, args ...interface{}) (int, error)
	GetStruct(objPointer interface{}, sql string, args ...interface{}) error
	GetStructs(objPointerSlice interface{}, sql string, args ...interface{}) error
	GetScan(objPointer interface{}, sql string, args ...interface{}) error

	// Master/Slave specification support.
	Master() (*sql.DB, error)
	Slave() (*sql.DB, error)

	// Ping-Pong.
	PingMaster() error
	PingSlave() error

	// Transaction.
	Begin() (*TX, error)

	Insert(table string, data interface{}, batch ...int) (sql.Result, error)
	InsertIgnore(table string, data interface{}, batch ...int) (sql.Result, error)
	Replace(table string, data interface{}, batch ...int) (sql.Result, error)
	Save(table string, data interface{}, batch ...int) (sql.Result, error)

	BatchInsert(table string, list interface{}, batch ...int) (sql.Result, error)
	BatchReplace(table string, list interface{}, batch ...int) (sql.Result, error)
	BatchSave(table string, list interface{}, batch ...int) (sql.Result, error)

	Update(table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error)
	Delete(table string, condition interface{}, args ...interface{}) (sql.Result, error)

	// Model creation.
	Table(table ...string) *Model
	Model(table ...string) *Model
	Schema(schema string) *Schema

	// Configuration methods.
	GetCache() *gcache.Cache
	SetDebug(debug bool)
	GetDebug() bool
	SetSchema(schema string)
	GetSchema() string
	GetPrefix() string
	GetGroup() string
	SetDryRun(dryrun bool)
	GetDryRun() bool
	SetLogger(logger *glog.Logger)
	GetLogger() *glog.Logger
	SetMaxIdleConnCount(n int)
	SetMaxOpenConnCount(n int)
	SetMaxConnLifetime(d time.Duration)

	// Utility methods.
	GetChars() (charLeft string, charRight string)
	GetMaster(schema ...string) (*sql.DB, error)
	GetSlave(schema ...string) (*sql.DB, error)
	QuoteWord(s string) string
	QuoteString(s string) string
	QuotePrefixTableName(table string) string
	Tables(schema ...string) (tables []string, err error)
	TableFields(table string, schema ...string) (map[string]*TableField, error)

	// HandleSqlBeforeCommit is a hook function, which deals with the sql string before
	// it's committed to underlying driver. The parameter <link> specifies the current
	// database connection operation object. You can modify the sql string <sql> and its
	// arguments <args> as you wish before they're committed to driver.
	HandleSqlBeforeCommit(link Link, sql string, args []interface{}) (string, []interface{})
	// contains filtered or unexported methods
}

DB defines the interfaces for ORM operations.

func Instance

func Instance(name ...string) (db DB, err error)

Instance returns an instance for DB operations. The parameter <name> specifies the configuration group name, which is DEFAULT_GROUP_NAME in default.

func New

func New(name ...string) (db DB, err error)

New creates and returns an ORM object with global configurations. The parameter <name> specifies the configuration group name, which is DEFAULT_GROUP_NAME in default.

type Driver added in v1.11.6

type Driver interface {
	// New creates and returns a database object for specified database server.
	New(core *Core, node *ConfigNode) (DB, error)
}

Driver is the interface for integrating sql drivers into package gdb.

type DriverMssql added in v1.11.6

type DriverMssql struct {
	*Core
}

DriverMssql is the driver for SQL server database.

func (*DriverMssql) GetChars added in v1.11.6

func (d *DriverMssql) GetChars() (charLeft string, charRight string)

GetChars returns the security char for this type of database.

func (*DriverMssql) HandleSqlBeforeCommit added in v1.11.6

func (d *DriverMssql) HandleSqlBeforeCommit(link Link, sql string, args []interface{}) (string, []interface{})

HandleSqlBeforeCommit deals with the sql string before commits it to underlying sql driver.

func (*DriverMssql) New added in v1.11.6

func (d *DriverMssql) New(core *Core, node *ConfigNode) (DB, error)

New creates and returns a database object for SQL server. It implements the interface of gdb.Driver for extra database driver installation.

func (*DriverMssql) Open added in v1.11.6

func (d *DriverMssql) Open(config *ConfigNode) (*sql.DB, error)

Open creates and returns a underlying sql.DB object for mssql.

func (*DriverMssql) TableFields added in v1.11.6

func (d *DriverMssql) TableFields(table string, schema ...string) (fields map[string]*TableField, err error)

TableFields retrieves and returns the fields information of specified table of current schema.

func (*DriverMssql) Tables added in v1.11.6

func (d *DriverMssql) Tables(schema ...string) (tables []string, err error)

Tables retrieves and returns the tables of current schema. It's mainly used in cli tool chain for automatically generating the models.

type DriverMysql added in v1.11.6

type DriverMysql struct {
	*Core
}

DriverMysql is the driver for mysql database.

func (*DriverMysql) GetChars added in v1.11.6

func (d *DriverMysql) GetChars() (charLeft string, charRight string)

GetChars returns the security char for this type of database.

func (*DriverMysql) HandleSqlBeforeCommit added in v1.11.6

func (d *DriverMysql) HandleSqlBeforeCommit(link Link, sql string, args []interface{}) (string, []interface{})

HandleSqlBeforeCommit handles the sql before posts it to database.

func (*DriverMysql) New added in v1.11.6

func (d *DriverMysql) New(core *Core, node *ConfigNode) (DB, error)

New creates and returns a database object for mysql. It implements the interface of gdb.Driver for extra database driver installation.

func (*DriverMysql) Open added in v1.11.6

func (d *DriverMysql) Open(config *ConfigNode) (*sql.DB, error)

Open creates and returns a underlying sql.DB object for mysql.

func (*DriverMysql) TableFields added in v1.11.6

func (d *DriverMysql) TableFields(table string, schema ...string) (fields map[string]*TableField, err error)

TableFields retrieves and returns the fields information of specified table of current schema.

Note that it returns a map containing the field name and its corresponding fields. As a map is unsorted, the TableField struct has a "Index" field marks its sequence in the fields.

It's using cache feature to enhance the performance, which is never expired util the process restarts.

func (*DriverMysql) Tables added in v1.11.6

func (d *DriverMysql) Tables(schema ...string) (tables []string, err error)

Tables retrieves and returns the tables of current schema. It's mainly used in cli tool chain for automatically generating the models.

type DriverOracle added in v1.11.6

type DriverOracle struct {
	*Core
}

DriverOracle is the driver for oracle database.

func (*DriverOracle) DoBatchInsert added in v1.11.6

func (d *DriverOracle) DoBatchInsert(link Link, table string, list interface{}, option int, batch ...int) (result sql.Result, err error)

func (*DriverOracle) DoInsert added in v1.11.6

func (d *DriverOracle) DoInsert(link Link, table string, data interface{}, option int, batch ...int) (result sql.Result, err error)

func (*DriverOracle) GetChars added in v1.11.6

func (d *DriverOracle) GetChars() (charLeft string, charRight string)

GetChars returns the security char for this type of database.

func (*DriverOracle) HandleSqlBeforeCommit added in v1.11.6

func (d *DriverOracle) HandleSqlBeforeCommit(link Link, sql string, args []interface{}) (string, []interface{})

HandleSqlBeforeCommit deals with the sql string before commits it to underlying sql driver.

func (*DriverOracle) New added in v1.11.6

func (d *DriverOracle) New(core *Core, node *ConfigNode) (DB, error)

New creates and returns a database object for oracle. It implements the interface of gdb.Driver for extra database driver installation.

func (*DriverOracle) Open added in v1.11.6

func (d *DriverOracle) Open(config *ConfigNode) (*sql.DB, error)

Open creates and returns a underlying sql.DB object for oracle.

func (*DriverOracle) TableFields added in v1.11.6

func (d *DriverOracle) TableFields(table string, schema ...string) (fields map[string]*TableField, err error)

TableFields retrieves and returns the fields information of specified table of current schema.

func (*DriverOracle) Tables added in v1.11.6

func (d *DriverOracle) Tables(schema ...string) (tables []string, err error)

Tables retrieves and returns the tables of current schema. It's mainly used in cli tool chain for automatically generating the models. Note that it ignores the parameter <schema> in oracle database, as it is not necessary.

type DriverPgsql added in v1.11.6

type DriverPgsql struct {
	*Core
}

DriverPgsql is the driver for postgresql database.

func (*DriverPgsql) GetChars added in v1.11.6

func (d *DriverPgsql) GetChars() (charLeft string, charRight string)

GetChars returns the security char for this type of database.

func (*DriverPgsql) HandleSqlBeforeCommit added in v1.11.6

func (d *DriverPgsql) HandleSqlBeforeCommit(link Link, sql string, args []interface{}) (string, []interface{})

HandleSqlBeforeCommit deals with the sql string before commits it to underlying sql driver.

func (*DriverPgsql) New added in v1.11.6

func (d *DriverPgsql) New(core *Core, node *ConfigNode) (DB, error)

New creates and returns a database object for postgresql. It implements the interface of gdb.Driver for extra database driver installation.

func (*DriverPgsql) Open added in v1.11.6

func (d *DriverPgsql) Open(config *ConfigNode) (*sql.DB, error)

Open creates and returns a underlying sql.DB object for pgsql.

func (*DriverPgsql) TableFields added in v1.11.6

func (d *DriverPgsql) TableFields(table string, schema ...string) (fields map[string]*TableField, err error)

TableFields retrieves and returns the fields information of specified table of current schema.

func (*DriverPgsql) Tables added in v1.11.6

func (d *DriverPgsql) Tables(schema ...string) (tables []string, err error)

Tables retrieves and returns the tables of current schema. It's mainly used in cli tool chain for automatically generating the models.

type DriverSqlite added in v1.11.6

type DriverSqlite struct {
	*Core
}

DriverSqlite is the driver for sqlite database.

func (*DriverSqlite) GetChars added in v1.11.6

func (d *DriverSqlite) GetChars() (charLeft string, charRight string)

GetChars returns the security char for this type of database.

func (*DriverSqlite) HandleSqlBeforeCommit added in v1.11.6

func (d *DriverSqlite) HandleSqlBeforeCommit(link Link, sql string, args []interface{}) (string, []interface{})

HandleSqlBeforeCommit deals with the sql string before commits it to underlying sql driver. TODO 需要增加对Save方法的支持,可使用正则来实现替换, TODO 将ON DUPLICATE KEY UPDATE触发器修改为两条SQL语句(INSERT OR IGNORE & UPDATE)

func (*DriverSqlite) New added in v1.11.6

func (d *DriverSqlite) New(core *Core, node *ConfigNode) (DB, error)

New creates and returns a database object for sqlite. It implements the interface of gdb.Driver for extra database driver installation.

func (*DriverSqlite) Open added in v1.11.6

func (d *DriverSqlite) Open(config *ConfigNode) (*sql.DB, error)

Open creates and returns a underlying sql.DB object for sqlite.

func (*DriverSqlite) TableFields added in v1.11.6

func (d *DriverSqlite) TableFields(table string, schema ...string) (fields map[string]*TableField, err error)

TableFields retrieves and returns the fields information of specified table of current schema.

func (*DriverSqlite) Tables added in v1.11.6

func (d *DriverSqlite) Tables(schema ...string) (tables []string, err error)

Tables retrieves and returns the tables of current schema. It's mainly used in cli tool chain for automatically generating the models.

type Link interface {
	Query(sql string, args ...interface{}) (*sql.Rows, error)
	Exec(sql string, args ...interface{}) (sql.Result, error)
	Prepare(sql string) (*sql.Stmt, error)
}

Link is a common database function wrapper interface.

type List

type List = []Map

List is type of map array.

type Map

type Map = map[string]interface{}

Map is alias of map[string]interface{}, which is the most common usage map type.

type Model

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

Model is the DAO for ORM.

func (*Model) All

func (m *Model) All(where ...interface{}) (Result, error)

All does "SELECT FROM ..." statement for the model. It retrieves the records from table and returns the result as slice type. It returns nil if there's no record retrieved with the given conditions from table.

The optional parameter <where> is the same as the parameter of Model.Where function, see Model.Where.

func (*Model) And

func (m *Model) And(where interface{}, args ...interface{}) *Model

And adds "AND" condition to the where statement.

func (*Model) Array added in v1.11.6

func (m *Model) Array(fieldsAndWhere ...interface{}) ([]Value, error)

Array queries and returns data values as slice from database. Note that if there're multiple columns in the result, it returns just one column values randomly.

If the optional parameter <fieldsAndWhere> is given, the fieldsAndWhere[0] is the selected fields and fieldsAndWhere[1:] is treated as where condition fields. Also see Model.Fields and Model.Where functions.

func (*Model) As added in v1.11.2

func (m *Model) As(as string) *Model

As sets an alias name for current table.

func (*Model) Batch

func (m *Model) Batch(batch int) *Model

Batch sets the batch operation number for the model.

func (*Model) Cache

func (m *Model) Cache(duration time.Duration, name ...string) *Model

Cache sets the cache feature for the model. It caches the result of the sql, which means if there's another same sql request, it just reads and returns the result from cache, it but not committed and executed into the database.

If the parameter <duration> < 0, which means it clear the cache with given <name>. If the parameter <duration> = 0, which means it never expires. If the parameter <duration> > 0, which means it expires after <duration>.

The optional parameter <name> is used to bind a name to the cache, which means you can later control the cache like changing the <duration> or clearing the cache with specified <name>.

Note that, the cache feature is disabled if the model is operating on a transaction.

func (*Model) Chunk

func (m *Model) Chunk(limit int, callback func(result Result, err error) bool)

Chunk iterates the query result with given size and callback function.

func (*Model) Clone

func (m *Model) Clone() *Model

Clone creates and returns a new model which is a clone of current model. Note that it uses deep-copy for the clone.

func (*Model) Count

func (m *Model) Count(where ...interface{}) (int, error)

Count does "SELECT COUNT(x) FROM ..." statement for the model. The optional parameter <where> is the same as the parameter of Model.Where function, see Model.Where.

func (*Model) DB added in v1.10.1

func (m *Model) DB(db DB) *Model

DB sets/changes the db object for current operation.

func (*Model) Data

func (m *Model) Data(data ...interface{}) *Model

Data sets the operation data for the model. The parameter <data> can be type of string/map/gmap/slice/struct/*struct, etc. Eg: Data("uid=10000") Data("uid", 10000) Data("uid=? AND name=?", 10000, "john") Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})

func (*Model) Delete

func (m *Model) Delete(where ...interface{}) (result sql.Result, err error)

Delete does "DELETE FROM ... " statement for the model. The optional parameter <where> is the same as the parameter of Model.Where function, see Model.Where.

func (*Model) Fields

func (m *Model) Fields(fields string) *Model

Fields sets the operation fields of the model, multiple fields joined using char ','.

func (*Model) FieldsEx added in v1.10.0

func (m *Model) FieldsEx(fields string) *Model

FieldsEx sets the excluded operation fields of the model, multiple fields joined using char ','.

func (*Model) FieldsExStr added in v1.11.5

func (m *Model) FieldsExStr(fields string, prefix ...string) string

FieldsExStr retrieves and returns fields which are not in parameter <fields> from the table, joined with char ','. The parameter <fields> specifies the fields that are excluded. The optional parameter <prefix> specifies the prefix for each field, eg: FieldsExStr("id", "u.").

func (*Model) FieldsStr added in v1.11.5

func (m *Model) FieldsStr(prefix ...string) string

FieldsStr retrieves and returns all fields from the table, joined with char ','. The optional parameter <prefix> specifies the prefix for each field, eg: FieldsStr("u.").

func (*Model) Filter

func (m *Model) Filter() *Model

Filter marks filtering the fields which does not exist in the fields of the operated table.

func (*Model) FindAll added in v1.10.1

func (m *Model) FindAll(where ...interface{}) (Result, error)

FindAll retrieves and returns Result by by Model.WherePri and Model.All. Also see Model.WherePri and Model.All.

func (*Model) FindArray added in v1.11.6

func (m *Model) FindArray(fieldsAndWhere ...interface{}) ([]Value, error)

FindArray queries and returns data values as slice from database. Note that if there're multiple columns in the result, it returns just one column values randomly. Also see Model.WherePri and Model.Value.

func (*Model) FindCount added in v1.10.1

func (m *Model) FindCount(where ...interface{}) (int, error)

FindCount retrieves and returns the record number by Model.WherePri and Model.Count. Also see Model.WherePri and Model.Count.

func (*Model) FindOne added in v1.10.1

func (m *Model) FindOne(where ...interface{}) (Record, error)

FindOne retrieves and returns a single Record by Model.WherePri and Model.One. Also see Model.WherePri and Model.One.

func (*Model) FindScan added in v1.11.0

func (m *Model) FindScan(pointer interface{}, where ...interface{}) error

FindScan retrieves and returns the record/records by Model.WherePri and Model.Scan. Also see Model.WherePri and Model.Scan.

func (*Model) FindValue added in v1.10.1

func (m *Model) FindValue(fieldsAndWhere ...interface{}) (Value, error)

FindValue retrieves and returns single field value by Model.WherePri and Model.Value. Also see Model.WherePri and Model.Value.

func (*Model) ForPage

func (m *Model) ForPage(page, limit int) *Model

ForPage is alias of Model.Page. See Model.Page. Deprecated.

func (*Model) Group added in v1.10.1

func (m *Model) Group(groupBy string) *Model

Group sets the "GROUP BY" statement for the model.

func (*Model) GroupBy

func (m *Model) GroupBy(groupBy string) *Model

GroupBy is alias of Model.Group. See Model.Group. Deprecated.

func (*Model) Having added in v1.12.2

func (m *Model) Having(having interface{}, args ...interface{}) *Model

Having sets the having statement for the model. The parameters of this function usage are as the same as function Where. See Where.

func (*Model) InnerJoin

func (m *Model) InnerJoin(table ...string) *Model

InnerJoin does "INNER JOIN ... ON ..." statement on the model. The parameter <table> can be joined table and its joined condition, and also with its alias name, like: Table("user").InnerJoin("user_detail", "user_detail.uid=user.uid") Table("user", "u").InnerJoin("user_detail", "ud", "ud.uid=u.uid")

func (*Model) Insert

func (m *Model) Insert(data ...interface{}) (result sql.Result, err error)

Insert does "INSERT INTO ..." statement for the model. The optional parameter <data> is the same as the parameter of Model.Data function, see Model.Data.

func (*Model) InsertIgnore added in v1.11.5

func (m *Model) InsertIgnore(data ...interface{}) (result sql.Result, err error)

InsertIgnore does "INSERT IGNORE INTO ..." statement for the model. The optional parameter <data> is the same as the parameter of Model.Data function, see Model.Data.

func (*Model) LeftJoin

func (m *Model) LeftJoin(table ...string) *Model

LeftJoin does "LEFT JOIN ... ON ..." statement on the model. The parameter <table> can be joined table and its joined condition, and also with its alias name, like: Table("user").LeftJoin("user_detail", "user_detail.uid=user.uid") Table("user", "u").LeftJoin("user_detail", "ud", "ud.uid=u.uid")

func (*Model) Limit

func (m *Model) Limit(limit ...int) *Model

Limit sets the "LIMIT" statement for the model. The parameter <limit> can be either one or two number, if passed two number is passed, it then sets "LIMIT limit[0],limit[1]" statement for the model, or else it sets "LIMIT limit[0]" statement.

func (*Model) LockShared added in v1.11.7

func (m *Model) LockShared() *Model

LockShared sets the lock in share mode for current operation.

func (*Model) LockUpdate added in v1.11.7

func (m *Model) LockUpdate() *Model

LockUpdate sets the lock for update for current operation.

func (*Model) Master

func (m *Model) Master() *Model

Master marks the following operation on master node.

func (*Model) Offset

func (m *Model) Offset(offset int) *Model

Offset sets the "OFFSET" statement for the model. It only makes sense for some databases like SQLServer, PostgreSQL, etc.

func (*Model) OmitEmpty added in v1.10.1

func (m *Model) OmitEmpty() *Model

OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers the data and where attributes for empty values.

func (*Model) One

func (m *Model) One(where ...interface{}) (Record, error)

One retrieves one record from table and returns the result as map type. It returns nil if there's no record retrieved with the given conditions from table.

The optional parameter <where> is the same as the parameter of Model.Where function, see Model.Where.

func (*Model) Option added in v1.9.7

func (m *Model) Option(option int) *Model

Option adds extra operation option for the model.

func (*Model) OptionOmitEmpty added in v1.9.10

func (m *Model) OptionOmitEmpty() *Model

OptionOmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers the data and where attributes for empty values. Deprecated, use OmitEmpty instead.

func (*Model) Or

func (m *Model) Or(where interface{}, args ...interface{}) *Model

Or adds "OR" condition to the where statement.

func (*Model) Order added in v1.10.1

func (m *Model) Order(orderBy string) *Model

Order sets the "ORDER BY" statement for the model.

func (*Model) OrderBy

func (m *Model) OrderBy(orderBy string) *Model

OrderBy is alias of Model.Order. See Model.Order. Deprecated.

func (*Model) Page added in v1.10.1

func (m *Model) Page(page, limit int) *Model

Page sets the paging number for the model. The parameter <page> is started from 1 for paging. Note that, it differs that the Limit function start from 0 for "LIMIT" statement.

func (*Model) Replace

func (m *Model) Replace(data ...interface{}) (result sql.Result, err error)

Replace does "REPLACE INTO ..." statement for the model. The optional parameter <data> is the same as the parameter of Model.Data function, see Model.Data.

func (*Model) RightJoin

func (m *Model) RightJoin(table ...string) *Model

RightJoin does "RIGHT JOIN ... ON ..." statement on the model. The parameter <table> can be joined table and its joined condition, and also with its alias name, like: Table("user").RightJoin("user_detail", "user_detail.uid=user.uid") Table("user", "u").RightJoin("user_detail", "ud", "ud.uid=u.uid")

func (*Model) Safe

func (m *Model) Safe(safe ...bool) *Model

Safe marks this model safe or unsafe. If safe is true, it clones and returns a new model object whenever the operation done, or else it changes the attribute of current model.

func (*Model) Save

func (m *Model) Save(data ...interface{}) (result sql.Result, err error)

Save does "INSERT INTO ... ON DUPLICATE KEY UPDATE..." statement for the model. The optional parameter <data> is the same as the parameter of Model.Data function, see Model.Data.

It updates the record if there's primary or unique index in the saving data, or else it inserts a new record into the table.

func (*Model) Scan

func (m *Model) Scan(pointer interface{}, where ...interface{}) error

Scan automatically calls Struct or Structs function according to the type of parameter <pointer>. It calls function Struct if <pointer> is type of *struct/**struct. It calls function Structs if <pointer> is type of *[]struct/*[]*struct.

The optional parameter <where> is the same as the parameter of Model.Where function, see Model.Where.

Note that it returns sql.ErrNoRows if there's no record retrieved with the given conditions from table.

Eg: user := new(User) err := db.Table("user").Where("id", 1).Struct(user)

user := (*User)(nil) err := db.Table("user").Where("id", 1).Struct(&user)

users := ([]User)(nil) err := db.Table("user").Structs(&users)

users := ([]*User)(nil) err := db.Table("user").Structs(&users)

func (*Model) Schema added in v1.11.1

func (m *Model) Schema(schema string) *Model

Schema sets the schema for current operation.

func (*Model) Select

func (m *Model) Select(where ...interface{}) (Result, error)

Select is alias of Model.All. See Model.All. Deprecated.

func (*Model) Slave

func (m *Model) Slave() *Model

Slave marks the following operation on slave node. Note that it makes sense only if there's any slave node configured.

func (*Model) Struct

func (m *Model) Struct(pointer interface{}, where ...interface{}) error

Struct retrieves one record from table and converts it into given struct. The parameter <pointer> should be type of *struct/**struct. If type **struct is given, it can create the struct internally during converting.

The optional parameter <where> is the same as the parameter of Model.Where function, see Model.Where.

Note that it returns sql.ErrNoRows if there's no record retrieved with the given conditions from table.

Eg: user := new(User) err := db.Table("user").Where("id", 1).Struct(user)

user := (*User)(nil) err := db.Table("user").Where("id", 1).Struct(&user)

func (*Model) Structs

func (m *Model) Structs(pointer interface{}, where ...interface{}) error

Structs retrieves records from table and converts them into given struct slice. The parameter <pointer> should be type of *[]struct/*[]*struct. It can create and fill the struct slice internally during converting.

The optional parameter <where> is the same as the parameter of Model.Where function, see Model.Where.

Note that it returns sql.ErrNoRows if there's no record retrieved with the given conditions from table.

Eg: users := ([]User)(nil) err := db.Table("user").Structs(&users)

users := ([]*User)(nil) err := db.Table("user").Structs(&users)

func (*Model) TX added in v1.10.1

func (m *Model) TX(tx *TX) *Model

TX sets/changes the transaction for current operation.

func (*Model) Unscoped added in v1.12.2

func (m *Model) Unscoped(unscoped ...bool) *Model

Unscoped enables/disables the soft deleting feature.

func (*Model) Update

func (m *Model) Update(dataAndWhere ...interface{}) (result sql.Result, err error)

Update does "UPDATE ... " statement for the model.

If the optional parameter <dataAndWhere> is given, the dataAndWhere[0] is the updated data field, and dataAndWhere[1:] is treated as where condition fields. Also see Model.Data and Model.Where functions.

func (*Model) Value

func (m *Model) Value(fieldsAndWhere ...interface{}) (Value, error)

Value retrieves a specified record value from table and returns the result as interface type. It returns nil if there's no record found with the given conditions from table.

If the optional parameter <fieldsAndWhere> is given, the fieldsAndWhere[0] is the selected fields and fieldsAndWhere[1:] is treated as where condition fields. Also see Model.Fields and Model.Where functions.

func (*Model) Where

func (m *Model) Where(where interface{}, args ...interface{}) *Model

Where sets the condition statement for the model. The parameter <where> can be type of string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times, multiple conditions will be joined into where statement using "AND". Eg: Where("uid=10000") Where("uid", 10000) Where("money>? AND name like ?", 99999, "vip_%") Where("uid", 1).Where("name", "john") Where("status IN (?)", g.Slice{1,2,3}) Where("age IN(?,?)", 18, 50) Where(User{ Id : 1, UserName : "john"})

func (*Model) WherePri added in v1.10.1

func (m *Model) WherePri(where interface{}, args ...interface{}) *Model

WherePri does the same logic as Model.Where except that if the parameter <where> is a single condition like int/string/float/slice, it treats the condition as the primary key value. That is, if primary key is "id" and given <where> parameter as "123", the WherePri function treats it as "id=123", but Model.Where treats it as string "123".

type Record

type Record map[string]Value

Record is the row record of the table.

func (Record) GMap added in v1.9.7

func (r Record) GMap() *gmap.StrAnyMap

GMap converts <r> to a gmap.

func (Record) IsEmpty added in v1.10.0

func (r Record) IsEmpty() bool

IsEmpty checks and returns whether <r> is empty.

func (Record) Json added in v1.9.7

func (r Record) Json() string

Json converts <r> to JSON format content.

func (Record) Map added in v1.9.7

func (r Record) Map() Map

Map converts <r> to map[string]interface{}.

func (Record) Struct added in v1.9.7

func (r Record) Struct(pointer interface{}) error

Struct converts <r> to a struct. Note that the parameter <pointer> should be type of *struct/**struct.

func (Record) ToJson

func (r Record) ToJson() string

Deprecated.

func (Record) ToMap

func (r Record) ToMap() Map

Deprecated.

func (Record) ToStruct

func (r Record) ToStruct(pointer interface{}) error

Deprecated.

func (Record) ToXml

func (r Record) ToXml(rootTag ...string) string

Deprecated.

func (Record) Xml added in v1.9.7

func (r Record) Xml(rootTag ...string) string

Xml converts <r> to XML format content.

type Result

type Result []Record

Result is the row record array.

func (Result) Array added in v1.11.6

func (r Result) Array(field ...string) []Value

Array retrieves and returns specified column values as slice. The parameter <field> is optional is the column field is only one.

func (Result) Chunk added in v1.12.2

func (r Result) Chunk(size int) []Result

Chunk splits an Result into multiple Results, the size of each array is determined by <size>. The last chunk may contain less than size elements.

func (Result) IsEmpty added in v1.10.0

func (r Result) IsEmpty() bool

IsEmpty checks and returns whether <r> is empty.

func (Result) Json added in v1.9.7

func (r Result) Json() string

Json converts <r> to JSON format content.

func (Result) List added in v1.9.7

func (r Result) List() List

List converts <r> to a List.

func (Result) MapKeyInt added in v1.9.7

func (r Result) MapKeyInt(key string) map[int]Map

MapKeyInt converts <r> to a map[int]Map of which key is specified by <key>.

func (Result) MapKeyStr added in v1.9.7

func (r Result) MapKeyStr(key string) map[string]Map

MapKeyStr converts <r> to a map[string]Map of which key is specified by <key>.

func (Result) MapKeyUint added in v1.9.7

func (r Result) MapKeyUint(key string) map[uint]Map

MapKeyUint converts <r> to a map[uint]Map of which key is specified by <key>.

func (Result) RecordKeyInt added in v1.9.7

func (r Result) RecordKeyInt(key string) map[int]Record

RecordKeyInt converts <r> to a map[int]Record of which key is specified by <key>.

func (Result) RecordKeyStr added in v1.9.7

func (r Result) RecordKeyStr(key string) map[string]Record

RecordKeyInt converts <r> to a map[int]Record of which key is specified by <key>.

func (Result) RecordKeyUint added in v1.9.7

func (r Result) RecordKeyUint(key string) map[uint]Record

RecordKeyUint converts <r> to a map[uint]Record of which key is specified by <key>.

func (Result) Structs added in v1.9.7

func (r Result) Structs(pointer interface{}) (err error)

Structs converts <r> to struct slice. Note that the parameter <pointer> should be type of *[]struct/*[]*struct.

func (Result) ToIntMap

func (r Result) ToIntMap(key string) map[int]Map

Deprecated.

func (Result) ToIntRecord

func (r Result) ToIntRecord(key string) map[int]Record

Deprecated.

func (Result) ToJson

func (r Result) ToJson() string

Deprecated.

func (Result) ToList

func (r Result) ToList() List

Deprecated.

func (Result) ToStringMap

func (r Result) ToStringMap(key string) map[string]Map

Deprecated.

func (Result) ToStringRecord

func (r Result) ToStringRecord(key string) map[string]Record

Deprecated.

func (Result) ToStructs

func (r Result) ToStructs(pointer interface{}) (err error)

Deprecated.

func (Result) ToUintMap

func (r Result) ToUintMap(key string) map[uint]Map

Deprecated.

func (Result) ToUintRecord

func (r Result) ToUintRecord(key string) map[uint]Record

Deprecated.

func (Result) ToXml

func (r Result) ToXml(rootTag ...string) string

Deprecated.

func (Result) Xml added in v1.9.7

func (r Result) Xml(rootTag ...string) string

Xml converts <r> to XML format content.

type Schema added in v1.11.2

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

Schema is a schema object from which it can then create a Model.

func (*Schema) Model added in v1.11.2

func (s *Schema) Model(table string) *Model

Model is alias of Core.Table. See Core.Table.

func (*Schema) Table added in v1.11.2

func (s *Schema) Table(table string) *Model

Table creates and returns a new ORM model. The parameter <tables> can be more than one table names, like : "user", "user u", "user, user_detail", "user u, user_detail ud"

type Sql

type Sql struct {
	Sql    string        // SQL string(may contain reserved char '?').
	Args   []interface{} // Arguments for this sql.
	Format string        // Formatted sql which contains arguments in the sql.
	Error  error         // Execution result.
	Start  int64         // Start execution timestamp in milliseconds.
	End    int64         // End execution timestamp in milliseconds.
}

Sql is the sql recording struct.

type SqlResult added in v1.11.7

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

SqlResult is execution result for sql operations. It also supports batch operation result for rowsAffected.

func (*SqlResult) LastInsertId added in v1.11.7

func (r *SqlResult) LastInsertId() (int64, error)

see sql.Result.LastInsertId

func (*SqlResult) MustGetAffected added in v1.11.7

func (r *SqlResult) MustGetAffected() int64

MustGetAffected returns the affected rows count, if any error occurs, it panics.

func (*SqlResult) MustGetInsertId added in v1.11.7

func (r *SqlResult) MustGetInsertId() int64

MustGetInsertId returns the last insert id, if any error occurs, it panics.

func (*SqlResult) RowsAffected added in v1.11.7

func (r *SqlResult) RowsAffected() (int64, error)

see sql.Result.RowsAffected

type TX

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

TX is the struct for transaction management.

func (*TX) BatchInsert

func (tx *TX) BatchInsert(table string, list interface{}, batch ...int) (sql.Result, error)

BatchInsert batch inserts data. The parameter <list> must be type of slice of map or struct.

func (*TX) BatchInsertIgnore added in v1.11.5

func (tx *TX) BatchInsertIgnore(table string, list interface{}, batch ...int) (sql.Result, error)

BatchInsert batch inserts data with ignore option. The parameter <list> must be type of slice of map or struct.

func (*TX) BatchReplace

func (tx *TX) BatchReplace(table string, list interface{}, batch ...int) (sql.Result, error)

BatchReplace batch replaces data. The parameter <list> must be type of slice of map or struct.

func (*TX) BatchSave

func (tx *TX) BatchSave(table string, list interface{}, batch ...int) (sql.Result, error)

BatchSave batch replaces data. The parameter <list> must be type of slice of map or struct.

func (*TX) Commit

func (tx *TX) Commit() error

Commit commits the transaction.

func (*TX) Delete

func (tx *TX) Delete(table string, condition interface{}, args ...interface{}) (sql.Result, error)

Delete does "DELETE FROM ... " statement for the table.

The parameter <condition> can be type of string/map/gmap/slice/struct/*struct, etc. It is commonly used with parameter <args>. Eg: "uid=10000", "uid", 10000 "money>? AND name like ?", 99999, "vip_%" "status IN (?)", g.Slice{1,2,3} "age IN(?,?)", 18, 50 User{ Id : 1, UserName : "john"}

func (*TX) Exec

func (tx *TX) Exec(sql string, args ...interface{}) (sql.Result, error)

Exec does none query operation on transaction. See Core.Exec.

func (*TX) GetAll

func (tx *TX) GetAll(sql string, args ...interface{}) (Result, error)

GetAll queries and returns data records from database.

func (*TX) GetCount

func (tx *TX) GetCount(sql string, args ...interface{}) (int, error)

GetCount queries and returns the count from database.

func (*TX) GetOne

func (tx *TX) GetOne(sql string, args ...interface{}) (Record, error)

GetOne queries and returns one record from database.

func (*TX) GetScan

func (tx *TX) GetScan(objPointer interface{}, sql string, args ...interface{}) error

GetScan queries one or more records from database and converts them to given struct or struct array.

If parameter <pointer> is type of struct pointer, it calls GetStruct internally for the conversion. If parameter <pointer> is type of slice, it calls GetStructs internally for conversion.

func (*TX) GetStruct

func (tx *TX) GetStruct(obj interface{}, sql string, args ...interface{}) error

GetStruct queries one record from database and converts it to given struct. The parameter <pointer> should be a pointer to struct.

func (*TX) GetStructs

func (tx *TX) GetStructs(objPointerSlice interface{}, sql string, args ...interface{}) error

GetStructs queries records from database and converts them to given struct. The parameter <pointer> should be type of struct slice: []struct/[]*struct.

func (*TX) GetValue

func (tx *TX) GetValue(sql string, args ...interface{}) (Value, error)

GetValue queries and returns the field value from database. The sql should queries only one field from database, or else it returns only one field of the result.

func (*TX) Insert

func (tx *TX) Insert(table string, data interface{}, batch ...int) (sql.Result, error)

Insert does "INSERT INTO ..." statement for the table. If there's already one unique record of the data in the table, it returns error.

The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})

The parameter <batch> specifies the batch operation count when given data is slice.

func (*TX) InsertIgnore added in v1.11.5

func (tx *TX) InsertIgnore(table string, data interface{}, batch ...int) (sql.Result, error)

InsertIgnore does "INSERT IGNORE INTO ..." statement for the table. If there's already one unique record of the data in the table, it ignores the inserting.

The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})

The parameter <batch> specifies the batch operation count when given data is slice.

func (*TX) Model added in v1.11.0

func (tx *TX) Model(table ...string) *Model

Model is alias of tx.Table. See tx.Table.

func (*TX) Prepare

func (tx *TX) Prepare(sql string) (*sql.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 (*TX) Query

func (tx *TX) Query(sql string, args ...interface{}) (rows *sql.Rows, err error)

Query does query operation on transaction. See Core.Query.

func (*TX) Replace

func (tx *TX) Replace(table string, data interface{}, batch ...int) (sql.Result, error)

Replace does "REPLACE INTO ..." statement for the table. If there's already one unique record of the data in the table, it deletes the record and inserts a new one.

The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})

The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc. If given data is type of slice, it then does batch replacing, and the optional parameter <batch> specifies the batch operation count.

func (*TX) Rollback

func (tx *TX) Rollback() error

Rollback aborts the transaction.

func (*TX) Save

func (tx *TX) Save(table string, data interface{}, batch ...int) (sql.Result, error)

Save does "INSERT INTO ... ON DUPLICATE KEY UPDATE..." statement for the table. It updates the record if there's primary or unique index in the saving data, or else it inserts a new record into the table.

The parameter <data> can be type of map/gmap/struct/*struct/[]map/[]struct, etc. Eg: Data(g.Map{"uid": 10000, "name":"john"}) Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})

If given data is type of slice, it then does batch saving, and the optional parameter <batch> specifies the batch operation count.

func (*TX) Schema added in v1.11.2

func (tx *TX) Schema(schema string) *Schema

Schema creates and returns a initialization model from schema, from which it can then create a Model.

func (*TX) Table

func (tx *TX) Table(table ...string) *Model

Table acts like Core.Table except it operates on transaction. See Core.Table.

func (*TX) Update

func (tx *TX) Update(table string, data interface{}, condition interface{}, args ...interface{}) (sql.Result, error)

Update does "UPDATE ... " statement for the table.

The parameter <data> can be type of string/map/gmap/struct/*struct, etc. Eg: "uid=10000", "uid", 10000, g.Map{"uid": 10000, "name":"john"}

The parameter <condition> can be type of string/map/gmap/slice/struct/*struct, etc. It is commonly used with parameter <args>. Eg: "uid=10000", "uid", 10000 "money>? AND name like ?", 99999, "vip_%" "status IN (?)", g.Slice{1,2,3} "age IN(?,?)", 18, 50 User{ Id : 1, UserName : "john"}

type TableField

type TableField struct {
	Index   int         // For ordering purpose as map is unordered.
	Name    string      // Field name.
	Type    string      // Field type.
	Null    bool        // Field can be null or not.
	Key     string      // The index information(empty if it's not a index).
	Default interface{} // Default value for the field.
	Extra   string      // Extra information.
	Comment string      // Comment.
}

TableField is the struct for table field.

type Value

type Value = *gvar.Var

Value is the field value type.

Jump to

Keyboard shortcuts

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