sqlca

package module
v2.8.1 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: MIT Imports: 33 Imported by: 6

README

SQLCA

The simplest ORM for gopher which supports mysql/sqlite/mssql-server/postgresql

Quick start

database models generation

  • create database
/*
MySQL - 8.0.23 : Database - sqlca-db
*********************************************************************
*/

/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`sqlca-db` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;

USE `sqlca-db`;

/*Table structure for table `user` */

CREATE TABLE `user` (
                        `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'auto inc id',
                        `name` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'user name',
                        `phone` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'phone number',
                        `sex` tinyint unsigned NOT NULL DEFAULT '0' COMMENT 'user sex',
                        `email` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'email',
                        `disable` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'disabled(0=false 1=true)',
                        `balance` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT 'balance of decimal',
                        `sex_name` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '' COMMENT 'sex name',
                        `data_size` bigint NOT NULL DEFAULT '0' COMMENT 'data size',
                        `extra_data` json DEFAULT NULL COMMENT 'extra data (json)',
                        `created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'created time',
                        `updated_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'updated time',
                        PRIMARY KEY (`id`) USING BTREE,
                        KEY `phone` (`phone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;


  • install db2go
$ go install github.com/civet148/db2go@latest
  • script to generate
#!/bin/sh

# output directory
OUT_DIR=..
# golang package name of models
PACK_NAME=models
# model file suffix
SUFFIX_NAME=do
# set columns to readonly, they will be ignored when insert or update
READ_ONLY=created_time,updated_time
# more tags separated by colon
TAGS=bson
# database source name
DSN_URL='mysql://root:123456@127.0.0.1:3306/sqlca-db?charset=utf8'
# customized types for table columns
SPEC_TYPES='user.is_admin=bool, user.extra_data=UserExtra'
# tiny int columns as boolean when exporting for all tables
TINYINT_TO_BOOL=deleted,disabled,banned,is_admin
# the models import path for --dao flag
IMPORT_MODELS=/path/to/models

db2go --url "${DSN_URL}" --out "${OUT_DIR}" --enable-decimal --spec-type "${SPEC_TYPES}" \
      --suffix "${SUFFIX_NAME}" --package "${PACK_NAME}" --readonly "${READ_ONLY}" --tag "${TAGS}" --tinyint-as-bool "${TINYINT_TO_BOOL}" \
      --dao dao --import-models "${IMPORT_MODELS}"

gofmt -w "${OUT_DIR}"/"${PACK_NAME}"
  • model sample

    /path/to/models/user_do.go

// Code generated by db2go. DO NOT EDIT.
// https://github.com/civet148/sqlca

package models

import "github.com/civet148/sqlca/v2"

const TableNameUser = "user" 

const (
	USER_COLUMN_ID           = "id"
	USER_COLUMN_NAME         = "name"
	USER_COLUMN_PHONE        = "phone"
	USER_COLUMN_SEX          = "sex"
	USER_COLUMN_EMAIL        = "email"
	USER_COLUMN_DISABLE      = "disable"
	USER_COLUMN_BALANCE      = "balance"
	USER_COLUMN_SEX_NAME     = "sex_name"
	USER_COLUMN_DATA_SIZE    = "data_size"
	USER_COLUMN_EXTRA_DATA   = "extra_data"
	USER_COLUMN_CREATED_TIME = "created_time"
	USER_COLUMN_UPDATED_TIME = "updated_time"
)

type UserDO struct {
	Id          uint64        `json:"id" db:"id" bson:"_id"`                                               //auto inc id
	Name        string        `json:"name" db:"name" bson:"name"`                                          //user name
	Phone       string        `json:"phone" db:"phone" bson:"phone"`                                       //phone number
	Sex         uint8         `json:"sex" db:"sex" bson:"sex"`                                             //user sex
	Email       string        `json:"email" db:"email" bson:"email"`                                       //email
	Disable     int8          `json:"disable" db:"disable" bson:"disable"`                                 //disabled(0=false 1=true)
	Balance     sqlca.Decimal `json:"balance" db:"balance" bson:"balance"`                                 //balance of decimal
	SexName     string        `json:"sex_name" db:"sex_name" bson:"sex_name"`                              //sex name
	DataSize    int64         `json:"data_size" db:"data_size" bson:"data_size"`                           //data size
	ExtraData   UserExtra     `json:"extra_data" db:"extra_data" sqlca:"isnull" bson:"extra_data"`         //extra data (json)
	CreatedTime string        `json:"created_time" db:"created_time" sqlca:"readonly" bson:"created_time"` //created time
	UpdatedTime string        `json:"updated_time" db:"updated_time" sqlca:"readonly" bson:"updated_time"` //updated time
}

type UserExtra struct {
	HomeAddress string `json:"home_address"`
}

database connection

package main

import (
    "github.com/civet148/log"
    "github.com/civet148/sqlca-bench/models"
    "github.com/civet148/sqlca/v2"
)

const (
    MysqlDSN = "mysql://root:123456@127.0.0.1:3306/sqlca-db?charset=utf8mb4"
)

var db *sqlca.Engine

func main() {
    var err error
    db, err = sqlca.NewEngine(MysqlDSN)
    if err != nil {
        log.Panic(err.Error())
    }
    //db.Debug(true) //open debug mode
}

query by id

func QueryById(db *sqlca.Engine) (err error) {
    var rows int64
    var user *models.UserDO
    
    //SELECT * FROM user WHERE id=1
    var userId = 1
    rows, err = db.Model(&user).
                    Table(models.TableNameUser).
                    Id(userId).
                    Query()
    if err != nil {
        return log.Errorf(err.Error())
    }
    if rows == 0 || user.Id == 0 {
        return log.Errorf("query user by id %v not found", userId)
    }
    log.Infof("[SELECT * FROM user WHERE id=1] query result: [%+v]", user)
    return nil
}

query by page


func QueryByPage(db *sqlca.Engine) (err error) {
	var rows, total int64
	var users []*models.UserDO

	//SELECT id, name, sex_name, balance, created_time, updated_time FROM user LIMIT 0, 100
	rows, total, err = db.Model(&users).
		Table(models.TableNameUser).
		Select(models.USER_COLUMN_ID, models.USER_COLUMN_NAME, models.USER_COLUMN_SEX_NAME, models.USER_COLUMN_CREATED_TIME, models.USER_COLUMN_UPDATED_TIME, models.USER_COLUMN_BALANCE).
		Page(0, 100).
		QueryEx()
	if err != nil {
		return log.Errorf(err.Error())
	}
	log.Infof("[SELECT id, name, sex_name, balance, created_time, updated_time FROM user LIMIT 0, 100] query result: rows [%v] total [%v]", rows, total)
	return nil
}

query by conditions

func QueryByConditions(db *sqlca.Engine, id int64, name, createdTime string) (err error) {
    var rows int64
    var users []*models.UserDO
    
    //SELECT id, name, sex_name, balance, created_time, updated_time FROM user WHERE id = ? AND name = ? AND created_time >= ?
    e := db.Model(&users).
            Table(models.TableNameUser).
            Select(models.USER_COLUMN_ID, models.USER_COLUMN_NAME, models.USER_COLUMN_SEX_NAME, models.USER_COLUMN_CREATED_TIME, models.USER_COLUMN_UPDATED_TIME, models.USER_COLUMN_BALANCE)
    if id != 0 {
        e.Eq(models.USER_COLUMN_ID, id)
    }
    if name != "" {
        e.Eq(models.USER_COLUMN_NAME, name)
    }
    if createdTime != "" {
        e.Gte(models.USER_COLUMN_CREATED_TIME, createdTime)
    }
    if rows, err = e.Query(); err != nil {
        return log.Errorf(err.Error())
    }
    log.Infof("[SELECT id, name, sex_name, balance, created_time, updated_time FROM user  WHERE id = ? AND name = ? AND created_time >= ?] query result: rows [%v] users [%+v]", rows, users)
    return nil
}

insert

func Insert(db *sqlca.Engine) (err error) {
	//INSERT INTO user(name, phone, sex_name, balance) VALUES('john', '+0014155787342', 'male', '12423.32356')
	var user = &models.UserDO{
		Name:    "john",
		Phone:   "+0014155787342",
		Balance: sqlca.NewDecimal("12423.32356"),
		SexName: "male",
	}
	var id int64
	id, err = db.Model(&user).Table(models.TableNameUser).Insert()
	if err != nil {
		return log.Errorf(err.Error())
	}
	log.Infof("[INSERT INTO user(name, phone, sex_name, balance) VALUES('john', '+0014155787342', 'male', '12423.32356')] result: last insert id [%v]", id)
	return nil
}

insert batch

func InsertBatch(db *sqlca.Engine) (err error) {
	//INSERT INTO user(name, phone, sex_name, balance) VALUES('john', '+0014155787342', 'male', '12423.32356'),('rose', '+0014155787343', 'female', '423.006')
	var users = []*models.UserDO{
		{
			Name:    "john",
			Phone:   "+0014155787342",
			Balance: sqlca.NewDecimal("12423.32356"),
			SexName: "male",
		},
		{
			Name:    "rose",
			Phone:   "+0014155787343",
			Balance: sqlca.NewDecimal("423.006"),
			SexName: "female",
		},
	}
	_, err = db.Model(&users).Table(models.TableNameUser).Insert()
	if err != nil {
		return log.Errorf(err.Error())
	}
	log.Infof("[INSERT INTO user(name, phone, sex_name, balance) VALUES('john', '+0014155787342', 'male', '12423.32356'),('rose', '+0014155787343', 'female', '423.006')] successful")
	return nil
}

Documentation

Index

Constants

View Source
const (
	DefaultConnMax  = 150
	DefaultConnIdle = 5
)
View Source
const (
	JoinType_Inner = 0 //inner join
	JoinType_Left  = 1 //left join
	JoinType_Right = 2 //right join
)

Variables

This section is empty.

Functions

func Url2MySql added in v2.7.3

func Url2MySql(strUrl string) (string, error)

Types

type CaseWhen

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

func (*CaseWhen) Case

func (c *CaseWhen) Case(strThen string, strWhen string, args ...interface{}) *CaseWhen

func (*CaseWhen) Else

func (c *CaseWhen) Else(strElse string) *CaseWhen

func (*CaseWhen) End

func (c *CaseWhen) End(strName string) *Engine

type Decimal

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

func NewDecimal

func NewDecimal(v interface{}) (d Decimal)

func (Decimal) Abs

func (d Decimal) Abs() Decimal

Abs returns the absolute value of the decimal.

func (Decimal) Add

func (d Decimal) Add(d2 interface{}) Decimal

Add returns d + d2

func (Decimal) Amount2Btc added in v2.2.0

func (d Decimal) Amount2Btc() Decimal

func (Decimal) Amount2Coin added in v2.2.0

func (d Decimal) Amount2Coin(prec int) Decimal

func (Decimal) Amount2Ether added in v2.2.0

func (d Decimal) Amount2Ether() Decimal

func (Decimal) Amount2FIL added in v2.2.9

func (d Decimal) Amount2FIL() Decimal

func (Decimal) BigInt added in v2.2.0

func (d Decimal) BigInt() (b *big.Int, ok bool)

func (Decimal) Btc2Amount added in v2.2.0

func (d Decimal) Btc2Amount() Decimal

func (Decimal) Cmp

func (d Decimal) Cmp(d2 interface{}) int

Cmp compares the numbers represented by d and d2 and returns:

-1 if d <  d2
 0 if d == d2
+1 if d >  d2

func (Decimal) Coin2Amount added in v2.2.0

func (d Decimal) Coin2Amount(prec int) Decimal

func (Decimal) Cos

func (d Decimal) Cos() Decimal

Cos returns the cosine of the radian argument x.

func (Decimal) Div

func (d Decimal) Div(d2 interface{}) Decimal

Div returns d / d2. If it doesn't divide exactly, the result will have DivisionPrecision digits after the decimal point.

func (Decimal) Equal

func (d Decimal) Equal(d2 interface{}) bool

Equal returns whether the numbers represented by d and d2 are equal.

func (Decimal) Ether2Amount added in v2.2.0

func (d Decimal) Ether2Amount() Decimal

func (Decimal) FIL2Amount added in v2.2.9

func (d Decimal) FIL2Amount() Decimal

func (Decimal) Float64

func (d Decimal) Float64() (f float64)

Float64 returns the nearest float64 value for d and a bool indicating whether f represents d exactly.

func (*Decimal) FromFloat

func (d *Decimal) FromFloat(v float64)

func (*Decimal) FromInt

func (d *Decimal) FromInt(v int64)

func (*Decimal) FromString

func (d *Decimal) FromString(v string)

func (Decimal) GreaterThan

func (d Decimal) GreaterThan(d2 interface{}) bool

GreaterThan (GT) returns true when d is greater than d2.

func (Decimal) GreaterThanOrEqual

func (d Decimal) GreaterThanOrEqual(d2 interface{}) bool

GreaterThanOrEqual (GTE) returns true when d is greater than or equal to d2.

func (Decimal) IntPart

func (d Decimal) IntPart() int64

IntPart returns the integer component of the decimal.

func (Decimal) IsNegative

func (d Decimal) IsNegative() bool

IsNegative return

true if d < 0
false if d == 0
false if d > 0

func (Decimal) IsPositive

func (d Decimal) IsPositive() bool

IsPositive return

true if d > 0
false if d == 0
false if d < 0

func (Decimal) IsZero

func (d Decimal) IsZero() bool

IsZero return

true if d == 0
false if d > 0
false if d < 0

func (Decimal) LessThan

func (d Decimal) LessThan(d2 interface{}) bool

LessThan (LT) returns true when d is less than d2.

func (Decimal) LessThanOrEqual

func (d Decimal) LessThanOrEqual(d2 interface{}) bool

LessThanOrEqual (LTE) returns true when d is less than or equal to d2.

func (Decimal) Marshal added in v2.4.0

func (d Decimal) Marshal() ([]byte, error)

func (Decimal) MarshalBSON added in v2.4.0

func (d Decimal) MarshalBSON() ([]byte, error)

MarshalBSON implements the bson.Marshaler interface.

func (Decimal) MarshalBSONValue added in v2.4.0

func (d Decimal) MarshalBSONValue() (bsontype.Type, []byte, error)

MarshalBSONValue implements the bson.Marshaler interface.

func (Decimal) MarshalBinary

func (d Decimal) MarshalBinary() (data []byte, err error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (Decimal) MarshalJSON

func (d Decimal) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (Decimal) MarshalText

func (d Decimal) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface for XML serialization.

func (Decimal) Max

func (d Decimal) Max(rest ...Decimal) Decimal

Max returns the largest Decimal that was passed in the arguments. To call this function with an array, you must do: This makes it harder to accidentally call Max with 0 arguments.

func (Decimal) Min

func (d Decimal) Min(rest ...Decimal) Decimal

Min returns the smallest Decimal that was passed in the arguments. To call this function with an array, you must do: This makes it harder to accidentally call Min with 0 arguments.

func (Decimal) Mod

func (d Decimal) Mod(d2 interface{}) Decimal

Mod returns d % d2.

func (Decimal) Mul

func (d Decimal) Mul(d2 interface{}) Decimal

Mul returns d * d2.

func (Decimal) Neg

func (d Decimal) Neg() Decimal

Neg returns -d.

func (Decimal) Pow

func (d Decimal) Pow(d2 interface{}) Decimal

Pow returns d to the power d2

func (Decimal) Round

func (d Decimal) Round(places int32) Decimal

Round rounds the decimal to places decimal places. If places < 0, it will round the integer part to the nearest 10^(-places).

Example:

NewFromFloat(5.45).Round(1).String() // output: "5.5"
NewFromFloat(545).Round(-1).String() // output: "550"

func (*Decimal) Scan

func (d *Decimal) Scan(src interface{}) error

Scan implements the sql.Scanner interface for database deserialization.

func (Decimal) Sign

func (d Decimal) Sign() int

Sign returns:

-1 if d <  0
 0 if d == 0
+1 if d >  0

func (Decimal) Sin

func (d Decimal) Sin() Decimal

Sin returns the sine of the radian argument x.

func (Decimal) String

func (d Decimal) String() string

String returns the string representation of the decimal with the fixed point.

Example:

d := New(-12345, -3)
println(d.String())

Output:

-12.345

func (Decimal) StringFixed

func (d Decimal) StringFixed(places int32) string

StringFixed returns a rounded fixed-point string with places digits after the decimal point.

Example:

NewFromFloat(0).StringFixed(2) // output: "0.00"
NewFromFloat(0).StringFixed(0) // output: "0"
NewFromFloat(5.45).StringFixed(0) // output: "5"
NewFromFloat(5.45).StringFixed(1) // output: "5.5"
NewFromFloat(5.45).StringFixed(2) // output: "5.45"
NewFromFloat(5.45).StringFixed(3) // output: "5.450"
NewFromFloat(545).StringFixed(-1) // output: "550"

func (Decimal) StringScaled

func (d Decimal) StringScaled(exp int32) string

StringScaled first scales the decimal then calls .String() on it. NOTE: buggy, unintuitive, and DEPRECATED! Use StringFixed instead.

func (Decimal) Sub

func (d Decimal) Sub(d2 interface{}) Decimal

Sub returns d - d2.

func (Decimal) Sum

func (d Decimal) Sum(rest ...Decimal) Decimal

Sum returns the combined total of the provided first and rest Decimals

func (Decimal) Tan

func (d Decimal) Tan() Decimal

Tan returns the tangent of the radian argument x.

func (Decimal) Truncate

func (d Decimal) Truncate(precision int32) Decimal

Truncate truncates off digits from the number, without rounding.

NOTE: precision is the last digit that will not be truncated (must be >= 0).

Example:

decimal.NewFromString("123.456").Truncate(2).String() // "123.45"

func (*Decimal) Unmarshal added in v2.4.0

func (d *Decimal) Unmarshal(data []byte) error

func (*Decimal) UnmarshalBSON added in v2.4.0

func (d *Decimal) UnmarshalBSON(data []byte) error

func (*Decimal) UnmarshalBSONValue added in v2.4.0

func (d *Decimal) UnmarshalBSONValue(bt bsontype.Type, data []byte) error

UnmarshalBSONValue implements the bson.Unmarshaler interface.

func (*Decimal) UnmarshalBinary

func (d *Decimal) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. As a string representation is already used when encoding to text, this method stores that string as []byte

func (*Decimal) UnmarshalJSON

func (d *Decimal) UnmarshalJSON(decimalBytes []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Decimal) UnmarshalText

func (d *Decimal) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface for XML deserialization.

func (Decimal) Value

func (d Decimal) Value() (driver.Value, error)

Value implements the driver.Valuer interface for database serialization.

type Engine

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

func NewEngine

func NewEngine(strUrl string, options ...*Options) (*Engine, error)

func (*Engine) And

func (e *Engine) And(strFmt string, args ...interface{}) *Engine

func (*Engine) Asc

func (e *Engine) Asc(strColumns ...string) *Engine

Asc order by [field1,field2...] asc

func (*Engine) Attach

func (e *Engine) Attach(strDatabaseName string, db *sqlx.DB) *Engine

Attach attach from a exist sqlx db instance

func (*Engine) AutoRollback

func (e *Engine) AutoRollback() *Engine

func (*Engine) Avg

func (e *Engine) Avg(strColumn string, strAS ...string) *Engine

func (*Engine) Case

func (e *Engine) Case(strThen string, strWhen string, args ...interface{}) *CaseWhen

func (*Engine) Close added in v2.4.0

func (e *Engine) Close() *Engine

Close disconnect all database connections

func (*Engine) Count

func (e *Engine) Count(strColumn string, strAS ...string) *Engine

func (*Engine) Counter

func (e *Engine) Counter() *counter

func (*Engine) Debug

func (e *Engine) Debug(ok bool)

Debug log debug mode on or off

func (*Engine) Delete

func (e *Engine) Delete() (rowsAffected int64, err error)

Delete orm delete record(s) from db

func (*Engine) Desc

func (e *Engine) Desc(strColumns ...string) *Engine

Desc order by [field1,field2...] desc

func (*Engine) Distinct

func (e *Engine) Distinct() *Engine

Distinct set distinct when select

func (*Engine) Eq added in v2.5.0

func (e *Engine) Eq(strColumn string, value interface{}) *Engine

Eq alias of Equal

func (*Engine) Equal added in v2.0.14

func (e *Engine) Equal(strColumn string, value interface{}) *Engine

func (*Engine) Exclude

func (e *Engine) Exclude(strColumns ...string) *Engine

Exclude orm select/update columns

func (*Engine) ExecRaw

func (e *Engine) ExecRaw(strQuery string, args ...interface{}) (rowsAffected, lastInsertId int64, err error)

ExecRaw use raw sql to insert/update database, results can not be cached to redis/memcached/memory... return rows affected and error, if err is not nil must be something wrong

func (*Engine) Find

func (e *Engine) Find(conditions map[string]interface{}) (rowsAffected int64, err error)

Find orm find with customer conditions (map[string]interface{})

func (*Engine) Force

func (e *Engine) Force() *Engine

Force force update/insert read only column(s)

func (*Engine) From added in v2.7.0

func (e *Engine) From(exprs ...string) *Engine

From alias of Table method

func (*Engine) GeoHash

func (e *Engine) GeoHash(lng, lat float64, precision int) (strGeoHash string, strNeighbors []string)

GeoHash encode geo hash string (precision 1~8)

returns geo hash and neighbors areas

func (*Engine) GetAdapter

func (e *Engine) GetAdapter() types.AdapterType

func (*Engine) GetPkName

func (e *Engine) GetPkName() string

func (*Engine) GreaterEqual added in v2.2.5

func (e *Engine) GreaterEqual(strColumn string, value interface{}) *Engine

func (*Engine) GreaterThan added in v2.2.5

func (e *Engine) GreaterThan(strColumn string, value interface{}) *Engine

func (*Engine) GroupBy

func (e *Engine) GroupBy(strColumns ...string) *Engine

GroupBy group by [field1,field2...]

func (*Engine) Gt added in v2.5.0

func (e *Engine) Gt(strColumn string, value interface{}) *Engine

Gt alias of GreaterThan

func (*Engine) Gte added in v2.5.0

func (e *Engine) Gte(strColumn string, value interface{}) *Engine

Gte alias of GreaterEqual

func (*Engine) GteLte added in v2.5.0

func (e *Engine) GteLte(strColumn string, value1, value2 interface{}) *Engine

GteLte greater than equal and less than equal

func (*Engine) Having

func (e *Engine) Having(strFmt string, args ...interface{}) *Engine

Having having [condition]

func (*Engine) Id

func (e *Engine) Id(value interface{}) *Engine

Id set orm primary key's value

func (*Engine) In

func (e *Engine) In(strColumn string, args ...interface{}) *Engine

In `field_name` IN ('1','2',...)

func (*Engine) InnerJoin

func (e *Engine) InnerJoin(strTableName string) *Join

func (*Engine) Insert

func (e *Engine) Insert() (lastInsertId int64, err error)

Insert orm insert return last insert id and error, if err is not nil must be something wrong NOTE: Model function is must be called before call this function

func (*Engine) IsNULL added in v2.5.1

func (e *Engine) IsNULL(strColumn string) *Engine

func (*Engine) JsonContainArray added in v2.8.0

func (e *Engine) JsonContainArray(strColumn string, value interface{}) *Engine

SELECT * FROM news WHERE JSON_CONTAINS(tags, JSON_ARRAY("#Blockchain"))

func (*Engine) JsonEqual added in v2.2.5

func (e *Engine) JsonEqual(strColumn, strPath string, value interface{}) *Engine

func (*Engine) JsonGreater added in v2.2.5

func (e *Engine) JsonGreater(strColumn, strPath string, value interface{}) *Engine

func (*Engine) JsonGreaterEqual added in v2.2.5

func (e *Engine) JsonGreaterEqual(strColumn, strPath string, value interface{}) *Engine

func (*Engine) JsonLess added in v2.2.5

func (e *Engine) JsonLess(strColumn, strPath string, value interface{}) *Engine

func (*Engine) JsonLessEqual added in v2.2.5

func (e *Engine) JsonLessEqual(strColumn, strPath string, value interface{}) *Engine

func (*Engine) JsonMarshal

func (e *Engine) JsonMarshal(v interface{}) (strJson string)

func (*Engine) JsonUnmarshal

func (e *Engine) JsonUnmarshal(strJson string, v interface{}) (err error)

func (*Engine) LeftJoin

func (e *Engine) LeftJoin(strTableName string) *Join

func (*Engine) LessEqual added in v2.0.14

func (e *Engine) LessEqual(strColumn string, value interface{}) *Engine

func (*Engine) LessThan added in v2.0.14

func (e *Engine) LessThan(strColumn string, value interface{}) *Engine

func (*Engine) Like added in v2.0.14

func (e *Engine) Like(strColumn, strSub string) *Engine

func (*Engine) Limit

func (e *Engine) Limit(args ...int) *Engine

Limit query limit Limit(10) - query records limit 10 (mysql/postgres)

func (*Engine) Lt added in v2.5.0

func (e *Engine) Lt(strColumn string, value interface{}) *Engine

Lt alias of LessThan

func (*Engine) Lte added in v2.5.0

func (e *Engine) Lte(strColumn string, value interface{}) *Engine

Lte alias of LessEqual

func (*Engine) Max

func (e *Engine) Max(strColumn string, strAS ...string) *Engine

func (*Engine) Min

func (e *Engine) Min(strColumn string, strAS ...string) *Engine

func (*Engine) Model

func (e *Engine) Model(args ...interface{}) *Engine

Model orm model use to get result set, support single struct object or slice [pointer type] notice: will clone a new engine object for orm operations(query/update/insert/upsert)

func (*Engine) Ne added in v2.6.1

func (e *Engine) Ne(strColumn string, value interface{}) *Engine

Ne not equal

func (*Engine) NearBy

func (e *Engine) NearBy(strLngCol, strLatCol, strAS string, lng, lat, distance float64) *Engine

NearBy -- select geo point as distance where distance <= n km (float64) SELECT

a.*,
(
6371 * ACOS (
COS( RADIANS( a.lat ) ) * COS( RADIANS( 28.8039097230 ) ) * COS(
  RADIANS( 121.5619236231 ) - RADIANS( a.lng )
 ) + SIN( RADIANS( a.lat ) ) * SIN( RADIANS( 28.8039097230 ) )
)
) AS distance

FROM

t_address a

HAVING distance <= 200 -- less than or equal 200km ORDER BY

distance
LIMIT 10

func (*Engine) NewID added in v2.6.0

func (e *Engine) NewID() ID

func (*Engine) NoVerbose added in v2.0.8

func (e *Engine) NoVerbose() *Engine

func (*Engine) NotIn added in v2.6.2

func (e *Engine) NotIn(strColumn string, args ...interface{}) *Engine

NotIn `field_name` NOT IN ('1','2',...)

func (*Engine) NotNULL added in v2.5.1

func (e *Engine) NotNULL(strColumn string) *Engine

func (*Engine) Offset

func (e *Engine) Offset(offset int) *Engine

Offset query offset (for mysql/postgres)

func (*Engine) OnConflict

func (e *Engine) OnConflict(strColumns ...string) *Engine

OnConflict set the conflict columns for upsert only for postgresql

func (*Engine) Open

func (e *Engine) Open(strUrl string, options ...*Options) (*Engine, error)

open a database or cache connection pool strUrl:

  1. data source name

    [mysql] Open("mysql://root:123456@127.0.0.1:3306/test?charset=utf8mb4") [postgres] Open("postgres://root:123456@127.0.0.1:5432/test?sslmode=disable") [mssql] Open("mssql://sa:123456@127.0.0.1:1433/mydb?instance=SQLExpress&windows=false") [sqlite] Open("sqlite:///var/lib/test.db")

options:

  1. specify master or slave, MySQL/Postgres (optional)

func (*Engine) Or

func (e *Engine) Or(strFmt string, args ...interface{}) *Engine

func (*Engine) OrderBy

func (e *Engine) OrderBy(orders ...string) *Engine

OrderBy order by [field1,field2...] [ASC]

func (*Engine) Page

func (e *Engine) Page(pageNo, pageSize int) *Engine

Page page query

SELECT ... FROM ... WHERE ... LIMIT (pageNo*pageSize), pageSize

func (*Engine) Ping

func (e *Engine) Ping() (err error)

Ping ping database

func (*Engine) Query

func (e *Engine) Query() (rowsAffected int64, err error)

Query orm query return rows affected and error, if err is not nil must be something wrong NOTE: Model function is must be called before call this function if slave == true, try query from a slave connection, if not exist query from master

func (*Engine) QueryEx

func (e *Engine) QueryEx() (rowsAffected, total int64, err error)

QueryEx orm query with total count return rows affected and error, if err is not nil must be something wrong NOTE: Model function is must be called before call this function if slave == true, try query from a slave connection, if not exist query from master

func (*Engine) QueryJson

func (e *Engine) QueryJson() (s string, err error)

QueryJson query result marshal to json

func (*Engine) QueryMap

func (e *Engine) QueryMap(strQuery string, args ...interface{}) (rowsAffected int64, err error)

QueryMap use raw sql to query results into a map slice (model type is []map[string]string) return results and error NOTE: Model function is must be called before call this function

func (*Engine) QueryRaw

func (e *Engine) QueryRaw(strQuery string, args ...interface{}) (rowsAffected int64, err error)

QueryRaw use raw sql to query results return rows affected and error, if err is not nil must be something wrong NOTE: Model function is must be called before call this function

func (*Engine) RightJoin

func (e *Engine) RightJoin(strTableName string) *Join

func (*Engine) Round added in v2.0.13

func (e *Engine) Round(strColumn string, round int, strAS ...string) *Engine

func (*Engine) Select

func (e *Engine) Select(strColumns ...string) *Engine

Select orm select/update columns

func (*Engine) SetCustomTag

func (e *Engine) SetCustomTag(tagNames ...string) *Engine

SetCustomTag set your customer tag for db query/insert/update (eg. go structure generated by protobuf not contain 'db' tag) this function must calls before Model()

func (*Engine) SetLogFile

func (e *Engine) SetLogFile(strPath string)

SetLogFile set log file

func (*Engine) SetPkName

func (e *Engine) SetPkName(strName string) *Engine

SetPkName set orm primary key's name, default named 'id'

func (*Engine) SetReadOnly

func (e *Engine) SetReadOnly(columns ...string)

SetReadOnly set read only columns

func (*Engine) Slave

func (e *Engine) Slave() *Engine

Slave orm query from a slave db

func (*Engine) SlowQuery

func (e *Engine) SlowQuery(on bool, ms int)

SlowQuery slow query alert on or off

on -> true/false
ms -> milliseconds (can be 0 if on is false)

func (*Engine) Sum

func (e *Engine) Sum(strColumn string, strAS ...string) *Engine

func (*Engine) Table

func (e *Engine) Table(strNames ...string) *Engine

Table set orm query table name(s) when your struct type name is not a table name

func (*Engine) ToSQL

func (e *Engine) ToSQL(operType types.OperType) (strSql string)

make SQL from orm model and operation type

func (*Engine) TxBegin

func (e *Engine) TxBegin() (*Engine, error)

func (*Engine) TxCommit

func (e *Engine) TxCommit() error

func (*Engine) TxExec

func (e *Engine) TxExec(strQuery string, args ...interface{}) (lastInsertId, rowsAffected int64, err error)

func (*Engine) TxFunc

func (e *Engine) TxFunc(fn func(tx *Engine) error) (err error)

TxFunc execute transaction by customize function

auto rollback when function return error

func (*Engine) TxFuncContext

func (e *Engine) TxFuncContext(ctx context.Context, fn func(ctx context.Context, tx *Engine) error) (err error)

TxFuncContext execute transaction by customize function with context

auto rollback when function return error

func (*Engine) TxGet

func (e *Engine) TxGet(dest interface{}, strQuery string, args ...interface{}) (count int64, err error)

func (*Engine) TxHandle

func (e *Engine) TxHandle(handler TxHandler) (err error)

TxHandle execute transaction by customize handler auto rollback when handler return error

func (*Engine) TxRollback

func (e *Engine) TxRollback() error

func (*Engine) Update

func (e *Engine) Update() (rowsAffected int64, err error)

Update orm update from model strColumns... if set, columns will be updated, if none all columns in model will be updated except primary key return rows affected and error, if err is not nil must be something wrong NOTE: Model function is must be called before call this function

func (*Engine) Upsert

func (e *Engine) Upsert(strCustomizeUpdates ...string) (lastInsertId int64, err error)

Upsert orm insert or update if key(s) conflict return last insert id and error, if err is not nil must be something wrong, if your primary key is not a int/int64 type, maybe id return 0 NOTE: Model function is must be called before call this function and call OnConflict function when you are on postgresql updates -> customize updates condition when key(s) conflict [MySQL] INSERT INTO messages(id, message_type, unread_count) VALUES('10000', '2', '1', '3') ON DUPLICATE KEY UPDATE message_type=values(message_type), unread_count=unread_count+values(unread_count) --------------------------------------------------------------------------------------------------------------------------------------- e.Model(&do).Table("messages").Upsert("message_type=values(message_type)", "unread_count=unread_count+values(unread_count)") ---------------------------------------------------------------------------------------------------------------------------------------

func (*Engine) Use added in v2.4.0

func (e *Engine) Use(strDatabaseName string) (*Engine, error)

Use switch database (returns a new instance)

func (*Engine) Where

func (e *Engine) Where(strWhere string, args ...interface{}) *Engine

Where orm where condition

type Fetcher

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

type ID added in v2.6.0

type ID = snowflake.ID

type Join

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

func (*Join) On

func (j *Join) On(strOn string, args ...interface{}) *Engine

type JoinType

type JoinType int

func (JoinType) GoString

func (t JoinType) GoString() string

func (JoinType) String

func (t JoinType) String() string

func (JoinType) ToKeyWord

func (t JoinType) ToKeyWord() string

type ModelReflector

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

func (*ModelReflector) ToMap

func (s *ModelReflector) ToMap(tagNames ...string) map[string]interface{}

parse struct tag and value to map

type Options

type Options struct {
	Debug      bool       //enable debug mode
	Max        int        //max active connections
	Idle       int        //max idle connections
	Slave      bool       //is a slave DSN ?
	SSH        *SSH       //ssh tunnel server config
	SnowFlake  *SnowFlake //snowflake id config
	PageOffset bool       //page offset for LIMIT
}

type SSH

type SSH struct {
	User       string //SSH tunnel server login account
	Password   string //SSH tunnel server login password
	PrivateKey string //SSH tunnel server private key, eg. "/home/test/.ssh/private-key.pem"
	Host       string //SSH tunnel server host [ip or domain], default port 22 if not specified
	// contains filtered or unexported fields
}

func (*SSH) GoString

func (s *SSH) GoString() string

func (*SSH) String

func (s *SSH) String() string

type SnowFlake added in v2.6.0

type SnowFlake struct {
	NodeId int64 //node id (0~1023)
}

type TxHandler

type TxHandler interface {
	OnTransaction(tx *Engine) error
}

type UrlInfo

type UrlInfo struct {
	Scheme     string
	Host       string // host name and port like '127.0.0.1:3306'
	User       string
	Password   string
	Path       string
	Fragment   string
	Opaque     string
	ForceQuery bool
	Queries    map[string]string
}

func ParseUrl

func ParseUrl(strUrl string) (ui *UrlInfo)

URL have some special characters in password(支持URL中密码包含特殊字符)

func (*UrlInfo) Url added in v2.4.0

func (ui *UrlInfo) Url() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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