sqlchemy

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2023 License: Apache-2.0 Imports: 18 Imported by: 44

README

sqlchemy

CircleCI codecov Go Report Card

A lightweight golang ORM library inspired by python sqlalchemy.

Features

  • Automatic creation and synchronization of table schema based on golang struct
  • Query syntax inpired by sqlalchemy
  • Support: MySQL/MariaDB with InnoDB engine / Sqlite (Exprimental) / ClickHouse (Exprimental)
  • Support select, insert, update and insertOrupdate (no delete)

Quick Examples

Database initialization

Before using sqlchemy, database connection should be setup first.

Setup database of default backend(MySQL with InnoDB)
dbconn := sql.Open("mysql", "testgo:openstack@tcp(127.0.0.1:3306)/testgo?charset=utf8&parseTime")

sqlchemy.SetDefaultDB(dbconn)
Setup database of MySQL with InnoDB explicitly
dbconn := sql.Open("mysql", "testgo:openstack@tcp(127.0.0.1:3306)/testgo?charset=utf8&parseTime")

sqlchemy.SetDBWithNameBackend(dbconn, sqlchemy.DBName("mysqldb"), sqlchemy.MySQLBackend)
Setup database of SQLite
dbconn := sql.Open("sqlite3", "file:mydb.s3db?cache=shared&mode=rwc")

sqlchemy.SetDBWithNameBackend(dbconn, sqlchemy.DBName("sqlitedb"), sqlchemy.SQLiteBackend)
Setup database of ClickHouse
dbconn := sql.Open("clickhouse", "tcp://host1:9000?username=user&password=qwerty&database=clicks")

sqlchemy.SetDBWithNameBackend(dbconn, sqlchemy.DBName("clickhousedb"), sqlchemy.ClickhouseBackend)

Table Schema

Table schema is defined by struct field tags

type TestTable struct {
    Id        string               `primary:"true" width:"128" charset:"ascii" nullable:"false"`
    Name      string               `width:"64" charset:"utf8" index:"true"`
    Gender    string               `width:"10" charset:"ascii"`
    Age       uint8                `default:"18"`
    Info      jsonutils.JSONObject `nullable:"false"`
    Compond   *SCompondStruct      `width:1024`
    CreatedAt time.Time            `nullable:"false" created_at:"true"`
    UpdatedAt time.Time            `nullable:"false" updated_at:"true"`
    Version   int                  `default:"0" nullable:"false" auto_version:"true"`
    DeletedAt time.Time            ``
    Deleted   bool                 `nullable:"false" default:"false"`
    Notes     string               `default:"default notes"`
}

Table initialization

Create a table from a struct schema

tablespec := sqlchemy.NewTableSpecFromStruct(TestTable{}, "testtable")
tablespec := sqlchemy.NewTableSpecFromStructWithDBName(TestTable{}, "testtable", sqlchemy.DBName("mydb"))

Check whether table schema definition is consistent with schema in database.

if !tablespec.CheckSync() {
    log.Fatalf("table not in sync")
}

Synchronize database table schema and make it consistent with the struct defintion.

err := tablespec.Sync()
if err != nil {
    log.Fataf("synchronize table schema failed: %s", er)
}

Query

Construct query
ti := tablespec.Instance()

// select * from testtable
q := ti.Query()

// select * from testtable where id = '981b10ed-b6f9-4120-8a77-a3b03e343143'
// query by field name, in which the name is unique in the query
q := ti.Query().Equals("id", "981b10ed-b6f9-4120-8a77-a3b03e343143")

// query by field instance, in which the field name might be ambiguous
q := ti.Query().Filter(sqlchemy.Equals(ti.Field("id"), "981b10ed-b6f9-4120-8a77-a3b03e343143"))

// joint query

// select * from t1 join t2 on t1.id=t2.testtable_id where t2.created_at > '2019-11-02'
q := ti.Query("name").Join(t2, sqlchemy.Equals(ti.Field("id"), t2.Field("testtable_id"))).Filter(sqlchermy.GT(t2.Field("created_at"), '2019-11-02')

// union query
// select id, name from testtable where id = '981b10ed-b6f9-4120-8a77-a3b03e343143' union select id, name from testtable where id='6fcc87ca-c1da-40ab-849a-305ff2663901'
q1 := t1.Query("id", "name").Equals("id", "981b10ed-b6f9-4120-8a77-a3b03e343143")
q2 := t1.Query("id", "name").Equals("id", "6fcc87ca-c1da-40ab-849a-305ff2663901")
qu := sqlchemy.Union(q1, q2)
Fetch data
q := ti.Query().Equals("id", "e2bc9b659cec407590dc2f3fcb009acb")

// fetch single row into object
row := TestTable{}
err := q.First(&row)
if err != nil {
    log.Fatalf("fetch object error %s", err)
}

// fetch single row into a string map, where strMap is map[string]string
strMap, err := q.FirstStringMap()
if err != nil {
    log.Fatalf("fetch object error %s", err)
}

q := ti.Query().Startswith("id", "abc")
// fetch rows
rows := make([]TestTable, 0)
err := q.All(&rows)
if err != nil {
    log.Fatalf("query failure: %s", err)
}

// fetch rows into string maps, where maps is []map[string]string
maps, err := q.AllStringMap()
if err != nil {
    log.Fatalf("query failure: %s", err)
}
SubQuery

Query can be used as a subquery in other queries.

// derive a subquery from an ordinary query
subq := t1.Query("id").Equals("version", "v2.0").SubQuery()
// use subquery
q := t1.Query().In("id", subq)

Insert

// hook to initialize data field before insert
func (t *TestTable) BeforeInsert() {
    t.Id = uuid4()
}
// initialize data struct
dt1 := TestTable{
    Name: "Test",
}
// insert the data, primary key fields must be populated
// the primary key has been populated by the BeforeInsert hook
err = tablespec.Insert(&dt1)

// insert or update
// insert the object if no primary key conflict, otherwise, update the record
err = tablespec.InsertOrUpdate(&dt1)

Update

// update the field
_, err = tablespec.Update(&dt3, func() error {
    dt3.Name = "New name 4"
    dt3.Compond = &SCompondStruct{Id: "998822333", Age: 80}
    return nil
})

Please refer to sqltest/main.go for more examples.

Documentation

Index

Constants

View Source
const (
	// MySQL is the backend name for MySQL/MariaDB
	MySQLBackend = DBBackendName("MySQL")
	// Clickhouse is the backend name of Clickhouse
	ClickhouseBackend = DBBackendName("Clickhouse")
	// SQLiteBackend is the backend name of Sqlite3
	SQLiteBackend = DBBackendName("SQLite")
)
View Source
const (
	// SQL_OP_AND represents AND operator
	SQL_OP_AND = "AND"
	// SQL_OP_OR represents OR operator
	SQL_OP_OR = "OR"
	// SQL_OP_NOT represents NOT operator
	SQL_OP_NOT = "NOT"
	// SQL_OP_LIKE represents LIKE operator
	SQL_OP_LIKE = "LIKE"
	// SQL_OP_REGEXP represents REGEXP operator
	SQL_OP_REGEXP = "REGEXP"
	// SQL_OP_IN represents IN operator
	SQL_OP_IN = "IN"
	// SQL_OP_NOTIN represents NOT IN operator
	SQL_OP_NOTIN = "NOT IN"
	// SQL_OP_EQUAL represents EQUAL operator
	SQL_OP_EQUAL = "="
	// SQL_OP_LT represents < operator
	SQL_OP_LT = "<"
	// SQL_OP_LE represents <= operator
	SQL_OP_LE = "<="
	// SQL_OP_GT represents > operator
	SQL_OP_GT = ">"
	// SQL_OP_GE represents >= operator
	SQL_OP_GE = ">="
	// SQL_OP_BETWEEN represents BETWEEN operator
	SQL_OP_BETWEEN = "BETWEEN"
	// SQL_OP_NOTEQUAL represents NOT EQUAL operator
	SQL_OP_NOTEQUAL = "<>"
)
View Source
const (
	// TAG_IGNORE is a field tag that indicates the field is ignored, not represents a table column
	TAG_IGNORE = "ignore"
	// TAG_NAME is a field tag that indicates the column name of this field
	TAG_NAME = "name"
	// TAG_WIDTH is a field tag that indicates the width of the column, like VARCHAR(15)
	// Supported by: mysql
	TAG_WIDTH = "width"
	// TAG_TEXT_LENGTH is a field tag that indicates the length of a text column
	// Supported by: mysql
	TAG_TEXT_LENGTH = "length"
	// TAG_CHARSET is a field tag that indicates the charset of a text column
	// Supported by: mysql
	TAG_CHARSET = "charset"
	// TAG_PRECISION is a field tag that indicates the precision of a float column
	TAG_PRECISION = "precision"
	// TAG_DEFAULT is a field tag that indicates the default value of a column
	TAG_DEFAULT = "default"
	// TAG_UNIQUE is a field tag that indicates the column value is unique
	TAG_UNIQUE = "unique"
	// TAG_INDEX is a field tag that indicates the column is a indexable column
	TAG_INDEX = "index"
	// TAG_PRIMARY is a field tag that indicates the column is part of primary key
	TAG_PRIMARY = "primary"
	// TAG_NULLABLE is a field tag that indicates the column is nullable
	TAG_NULLABLE = "nullable"
	// TAG_AUTOINCREMENT is a field tag that indicates the integer column is auto_increment, the column should must be primary
	TAG_AUTOINCREMENT = "auto_increment"
	// TAG_AUTOVERSION is a field tag that indicates the integer column is used to records the update version of a record
	TAG_AUTOVERSION = "auto_version"
	// TAG_UPDATE_TIMESTAMP is a field tag that indicates the datetime column is the updated_at timestamp
	TAG_UPDATE_TIMESTAMP = "updated_at"
	// TAG_CREATE_TIMESTAMP is a field tag that indicates the datetime column is the created_at timestamp
	TAG_CREATE_TIMESTAMP = "created_at"
	// TAG_ALLOW_ZERO is a field tag that indicates whether the column allow zero value
	TAG_ALLOW_ZERO = "allow_zero"
)
View Source
const (
	// ErrNoDataToUpdate is an Error constant: no data to update
	ErrNoDataToUpdate = errors.Error("No data to update")

	// ErrDuplicateEntry is an Error constant: duplicate entry
	ErrDuplicateEntry = errors.Error("duplicate entry")

	// ErrEmptyQuery is an Error constant: empty query
	ErrEmptyQuery = errors.Error("empty query")

	// ErrEmptyPrimaryKey is an Error constant: no primary key
	ErrEmptyPrimaryKey = errors.Error("empty primary keys")

	// ErrUnexpectRowCount is an Error constant: the number of rows impacted by modification unexpected
	ErrUnexpectRowCount = errors.Error("unexpected row count")

	// ErrNeedsPointer is an Error constant: input should be a pointer
	ErrNeedsPointer = errors.Error("input needs pointer input")

	// ErrNeedsArray is an Error constant: input should be an Array or Slice
	ErrNeedsArray = errors.Error("input needs slice or array")

	// ErrReadOnly is an Error constant: database is read-only
	ErrReadOnly = errors.Error("read only input")

	// ErrNotSupported is an Error constant: method not supported yet
	ErrNotSupported = errors.ErrNotSupported

	// ErrTableNotExists is an Error constant: table not exists
	ErrTableNotExists = errors.Error("TableNotExists")

	// ErrUnionFieldsNotMatch is an Error constant: fields of union queries not match
	ErrUnionFieldsNotMatch = errors.Error("cannot union, name of fields not match")

	// ErrUnionDatabasesNotMatch is an Error constant: backend database of union queries not match
	ErrUnionAcrossDatabases = errors.Error("cannot union across different databases")
)
View Source
const DefaultDB = DBName("__default__")

DefaultDB is the name for the default database instance

View Source
const IndexLimit int = 64

Variables

View Source
var (
	// DEBUG_SQLCHEMY is a global constant that indicates turn on SQL debug
	DEBUG_SQLCHEMY = false
)

Functions

func CloseDB

func CloseDB()

CloseDB close DB connection

func DiffCols added in v1.1.0

func DiffCols(tableName string, cols1 []IColumnSpec, cols2 []IColumnSpec) ([]IColumnSpec, []SUpdateColumnSpec, []IColumnSpec)

func Exec

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

Exec execute a raw SQL query for the default db instance Deprecated

func FetchColumns added in v1.1.0

func FetchColumns(match string) []string

func GetDB

func GetDB() *sql.DB

GetDB get DB instance Deprecated

func GetStringValue added in v1.1.0

func GetStringValue(dat interface{}) string

func GetTables

func GetTables() []string

GetTables get all tables' name in default database Deprecated

func RegisterBackend added in v1.1.0

func RegisterBackend(drv IBackend)

RegisterBackend registers a backend

func ResetTableID added in v1.1.0

func ResetTableID()

func SetDB

func SetDB(db *sql.DB)

Deprecated SetDB sets global DB instance

func SetDBWithNameBackend added in v1.1.0

func SetDBWithNameBackend(db *sql.DB, name DBName, backend DBBackendName)

SetDBWithName sets a DB instance with given name param: name DBName

func SetDefaultDB added in v1.1.0

func SetDefaultDB(db *sql.DB)

SetDefaultDB save default global DB instance

func SetupMockDatabaseBackend added in v1.1.0

func SetupMockDatabaseBackend()

func VarConditionWhereClause added in v1.1.2

func VarConditionWhereClause(v interface{}) string

Types

type DBBackendName added in v1.1.0

type DBBackendName string

type DBName added in v1.1.0

type DBName string

DBName is a type of string for name of database

type IBackend added in v1.1.0

type IBackend interface {
	// Name returns the name of the driver
	Name() DBBackendName
	// GetTableSQL returns the SQL for query tablenames
	GetTableSQL() string
	// GetCreateSQL returns the SQL for create a table
	GetCreateSQLs(ts ITableSpec) []string
	// IsSupportIndexAndContraints returns whether the backend supports index and contraints such as foreigh keys
	//     MySQL: true
	//     Sqlite: true
	//     Clickhouse: false
	IsSupportIndexAndContraints() bool
	// FetchTableColumnSpecs parse the table definition in database to extract columns' specification of a table
	FetchTableColumnSpecs(ts ITableSpec) ([]IColumnSpec, error)
	// FetchIndexesAndConstraints parse the table defintion in database to extract index and constraints information of a table
	FetchIndexesAndConstraints(ts ITableSpec) ([]STableIndex, []STableConstraint, error)
	// GetColumnSpecByFieldType parse the field of model struct to extract column specifiction of a field
	GetColumnSpecByFieldType(table *STableSpec, fieldType reflect.Type, fieldname string, tagmap map[string]string, isPointer bool) IColumnSpec
	// CurrentUTCTimeStampString returns the string represents current UTC time
	CurrentUTCTimeStampString() string
	// CurrentTimeStampString returns the string represents current local time
	CurrentTimeStampString() string
	//
	CaseInsensitiveLikeString() string
	//
	RegexpWhereClause(cond *SRegexpConition) string
	//
	UnionAllString() string
	//
	UnionDistinctString() string
	// support mixed insert vars
	SupportMixedInsertVariables() bool
	// Drop table
	DropTableSQL(table string) string

	// CanUpdate returns wether the backend supports update
	CanUpdate() bool
	// CanInsert returns wether the backend supports Insert
	CanInsert() bool
	// CanInsertOrUpdate returns weather the backend supports InsertOrUpdate
	CanInsertOrUpdate() bool

	// InsertSQLTemplate returns the template of insert SQL
	InsertSQLTemplate() string
	// UpdateSQLTemplate returns the template of update SQL
	UpdateSQLTemplate() string
	// InsertOrUpdateSQLTemplate returns the template of insert or update SQL
	InsertOrUpdateSQLTemplate() string

	// CanSupportRowAffected returns wether the backend support RowAffected method after update
	//     MySQL: true
	//     Sqlite: false
	//     Clickhouse: false
	CanSupportRowAffected() bool

	// CommitTableChangeSQL outputs the SQLs to alter a table
	CommitTableChangeSQL(ts ITableSpec, changes STableChanges) []string

	// cast
	CAST(field IQueryField, typeStr string, fieldname string) IQueryField
	// TIMESTAMPADD
	TIMESTAMPADD(name string, field IQueryField, offsetSeconds int) IQueryField
	// DATE_FORMAT
	DATE_FORMAT(name string, field IQueryField, format string) IQueryField
	// INET_ATON
	INET_ATON(field IQueryField) IQueryField
	// AND_Val
	AND_Val(name string, field IQueryField, v interface{}) IQueryField
	// OR_Val
	OR_Val(name string, field IQueryField, v interface{}) IQueryField
	// SUBSTR
	SUBSTR(name string, field IQueryField, pos, length int) IQueryField
	// CONCAT
	CONCAT(name string, fields ...IQueryField) IQueryField
	// REPLACE
	REPLACE(name string, field IQueryField, old string, new string) IQueryField
	// GROUP_CONCAT2
	GROUP_CONCAT2(name string, sep string, field IQueryField) IQueryField
	// DISTINCT
	DISTINCT(name string, field IQueryField) IQueryField
	// COUNT
	COUNT(name string, field ...IQueryField) IQueryField
	// MAX
	MAX(name string, field IQueryField) IQueryField
	// MIN
	MIN(name string, field IQueryField) IQueryField
	// SUM
	SUM(name string, field IQueryField) IQueryField
	// LENGTH
	LENGTH(name string, field IQueryField) IQueryField
	// LOWER
	LOWER(name string, field IQueryField) IQueryField
	// UPPER
	UPPER(name string, field IQueryField) IQueryField
	// DATEDIFF
	DATEDIFF(unit string, field1, field2 IQueryField) IQueryField
}

IBackend is the interface for all kinds of sql backends, e.g. MySQL, ClickHouse, Sqlite, PostgreSQL, etc.

type IColumnSpec

type IColumnSpec interface {
	// Name returns the name of the column
	Name() string

	// ColType returns type of the column, e.g. INTEGER, VARCHAR
	ColType() string

	// Default returns default value of the column, represents in string
	Default() string

	// IsSupportDefault returns whether this column supports being given a default value
	IsSupportDefault() bool

	// IsNullable returns whether this column is nullable
	IsNullable() bool

	// SetNullable sets this column as nullable
	SetNullable(on bool)

	// IsPrimary returns whether this column is part of the primary keys
	IsPrimary() bool

	SetPrimary(on bool)

	// IsUnique returns whether the value of this column unique for each row
	IsUnique() bool

	// IsIndex returns whether this column is indexable, if it is true, a index of this column will be automatically created
	IsIndex() bool

	// ExtraDefs returns some extra column attribute definitions, not covered by the standard fields
	ExtraDefs() string

	// DefinitionString return the SQL presentation of this column
	DefinitionString() string

	// IsText returns whether this column is actually a text, such a Datetime column is actually a text
	IsText() bool

	// IsSearchable returns whether this column is searchable, e.g. a integer column is not searchable, but a text field is searchable
	IsSearchable() bool

	// IsAscii returns whether this column is an ASCII type text, if true, the column should be compared with a UTF8 string
	IsAscii() bool

	// IsNumeric returns whether this column is a numeric type column, e.g. integer or float
	IsNumeric() bool

	// ConvertFromString returns the SQL representation of a value in string format for this column
	ConvertFromString(str string) interface{}

	// ConvertFromValue returns the SQL representation of a value for this column
	ConvertFromValue(val interface{}) interface{}

	// IsZero is used to determine a value is the zero value for this column
	IsZero(val interface{}) bool

	// AllowZero returns whether this column allow a zero value
	AllowZero() bool

	// Tags returns the field tags for this column, which is in the struct definition
	Tags() map[string]string

	// IsPointer returns whether this column is a pointer type definition, e.g. *int, *bool
	IsPointer() bool

	// SetDefault sets the default value in the format of string for this column
	SetDefault(defStr string)

	// IsAutoVersion
	IsAutoVersion() bool

	// IsUpdatedAt
	IsUpdatedAt() bool

	// IsCreatedAt
	IsCreatedAt() bool

	// IsAutoIncrement
	IsAutoIncrement() bool

	AutoIncrementOffset() int64

	SetAutoIncrement(val bool)

	SetAutoIncrementOffset(offset int64)

	IsString() bool

	IsDateTime() bool

	// index of column, to preserve the column position
	GetColIndex() int
	// setter of column index
	SetColIndex(idx int)
}

IColumnSpec is an interface that represents a column of a table

type ICondition

type ICondition interface {
	WhereClause() string
	Variables() []interface{}
	// contains filtered or unexported methods
}

ICondition is the interface representing a condition for SQL query e.g. WHERE a1 = b1 is a condition of equal the condition support nested condition, with AND, OR and NOT boolean operators

func AND

func AND(cond ...ICondition) ICondition

AND method that combines many conditions with AND operator

func Between

func Between(f IQueryField, r1, r2 interface{}) ICondition

Between SQL operator

func Contains

func Contains(f IQueryField, v string) ICondition

Contains method is a shortcut of LIKE method, Contains represents the condtion that a field contains a substring

func ContainsAny

func ContainsAny(f IQueryField, v []string) ICondition

ContainsAny is a OR combination of serveral Contains conditions

func Endswith

func Endswith(f IQueryField, v string) ICondition

Endswith method is a shortcut of LIKE condition, Endswith represents that condition that field endswith a substring

func Equals

func Equals(f IQueryField, v interface{}) ICondition

Equals method represents equal of two fields

func GE

func GE(f IQueryField, v interface{}) ICondition

GE method represetns operation of Greate Than Or Equal to, e.g. a >= b

func GT

func GT(f IQueryField, v interface{}) ICondition

GT method represents operation of Great Than, e.g. a > b

func In

func In(f IQueryField, v interface{}) ICondition

In SQL operator

func IsEmpty

func IsEmpty(f IQueryField) ICondition

IsEmpty method that justifies where a text field is empty, e.g. length is zero

func IsFalse

func IsFalse(f IQueryField) ICondition

IsFalse method justifies a boolean is false

func IsNotEmpty

func IsNotEmpty(f IQueryField) ICondition

IsNotEmpty method justifies a field is not empty

func IsNotNull

func IsNotNull(f IQueryField) ICondition

IsNotNull methods that justifies a field is not null

func IsNull

func IsNull(f IQueryField) ICondition

IsNull methods that justifies a field is null

func IsNullOrEmpty

func IsNullOrEmpty(f IQueryField) ICondition

IsNullOrEmpty is the ethod justifies a field is null or empty, e.g. a is null or length(a) == 0

func IsTrue

func IsTrue(f IQueryField) ICondition

IsTrue method that justifies a field is true, e.g. field == 1

func LE

func LE(f IQueryField, v interface{}) ICondition

LE method represents operation of Less Than Or Equal to, e.q. a <= b

func LT

func LT(f IQueryField, v interface{}) ICondition

LT method represents operation of Less Than, e.g. a < b

func Like

func Like(f IQueryField, v string) ICondition

Like SQL operator

func NOT

func NOT(cond ICondition) ICondition

NOT method that makes negative operator on a condition

func NoEarlierThan

func NoEarlierThan(f IQueryField) ICondition

NoEarlierThan justifies a field is no earlier than current time

func NoLaterThan

func NoLaterThan(f IQueryField) ICondition

NoLaterThan method justifies a DATETIME field is before current time

func NotEquals

func NotEquals(f IQueryField, v interface{}) ICondition

NotEquals method represents not equal of two fields

func NotIn

func NotIn(f IQueryField, v interface{}) ICondition

NotIn SQL operator

func OR

func OR(cond ...ICondition) ICondition

OR method that combines many conditions with OR operator

func Regexp added in v1.1.2

func Regexp(f IQueryField, v string) ICondition

Regexp SQL operator

func Startswith

func Startswith(f IQueryField, v string) ICondition

Startswith method is a shortcut of LIKE method, Startswith represents the condition that field starts with a substring

type IFunction

type IFunction interface {
	// contains filtered or unexported methods
}

IFunction is the interface for a SQL embedded function, such as MIN, MAX, NOW, etc.

type IQuery

type IQuery interface {
	// String returns the queryString
	String(fields ...IQueryField) string

	// QueryFields returns fields in the select clause
	QueryFields() []IQueryField

	// Variables returns variables in statement
	Variables() []interface{}

	// SubQuery convert this SQL to a subquery
	SubQuery() *SSubQuery

	// Field reference to a field by name
	Field(name string) IQueryField
	// contains filtered or unexported methods
}

IQuery is an interface that reprsents a SQL query, e.g. SELECT ... FROM ... WHERE ...

type IQueryField

type IQueryField interface {
	// the string after select
	Expression() string

	// the name of thie field
	Name() string

	// the reference string in where clause
	Reference() string

	// give this field an alias name
	Label(label string) IQueryField

	// return variables
	Variables() []interface{}
	// contains filtered or unexported methods
}

IQueryField is an interface that represents a select field in a SQL query

func ADD added in v1.0.2

func ADD(name string, fields ...IQueryField) IQueryField

func AND_Val

func AND_Val(name string, field IQueryField, v interface{}) IQueryField

AND_Val represents a SQL function that does binary & operation on a field

func CAST added in v1.1.0

func CAST(field IQueryField, typeStr string, fieldname string) IQueryField

CAST represents a SQL function cast types

func CONCAT

func CONCAT(name string, fields ...IQueryField) IQueryField

CONCAT represents a SQL function CONCAT

func COUNT

func COUNT(name string, field ...IQueryField) IQueryField

COUNT represents the SQL function COUNT

func DATEDIFF added in v1.1.2

func DATEDIFF(unit string, field1, field2 IQueryField) IQueryField

func DATE_FORMAT added in v1.1.2

func DATE_FORMAT(name string, field IQueryField, format string) IQueryField

DATE_FORMAT represents a SQL function DATE_FORMAT

func DISTINCT

func DISTINCT(name string, field IQueryField) IQueryField

DISTINCT represents the SQL function DISTINCT

func DIV added in v1.0.2

func DIV(name string, fields ...IQueryField) IQueryField

func GROUP_CONCAT

func GROUP_CONCAT(name string, field IQueryField) IQueryField

GROUP_CONCAT represents the SQL function GROUP_CONCAT

func GROUP_CONCAT2 added in v1.1.2

func GROUP_CONCAT2(name string, sep string, field IQueryField) IQueryField

GROUP_CONCAT2 represents the SQL function GROUP_CONCAT

func INET_ATON

func INET_ATON(field IQueryField) IQueryField

INET_ATON represents a SQL function INET_ATON

func LENGTH added in v1.1.2

func LENGTH(name string, field IQueryField) IQueryField

LENGTH represents a SQL function of LENGTH

func LOWER added in v1.1.2

func LOWER(name string, field IQueryField) IQueryField

LOWER represents the SQL function SUM

func MAX

func MAX(name string, field IQueryField) IQueryField

MAX represents the SQL function MAX

func MIN

func MIN(name string, field IQueryField) IQueryField

MIN represents the SQL function MIN

func MUL added in v1.0.2

func MUL(name string, fields ...IQueryField) IQueryField

func NewFunction

func NewFunction(ifunc IFunction, name string) IQueryField

NewFunction creates a field with SQL function for example: SUM(count) as total

func NewFunctionField

func NewFunctionField(name string, funcexp string, fields ...IQueryField) IQueryField

NewFunctionField returns an instance of query field by calling a SQL embedded function

func OR_Val

func OR_Val(name string, field IQueryField, v interface{}) IQueryField

OR_Val represents a SQL function that does binary | operation on a field

func REPLACE

func REPLACE(name string, field IQueryField, old string, new string) IQueryField

REPLACE represents the SQL function REPLACE

func SUB added in v1.0.2

func SUB(name string, fields ...IQueryField) IQueryField

func SUBSTR added in v1.1.0

func SUBSTR(name string, field IQueryField, pos, length int) IQueryField

SUBSTR represents a SQL function SUBSTR

func SUM

func SUM(name string, field IQueryField) IQueryField

SUM represents the SQL function SUM

func SubStr

func SubStr(name string, field IQueryField, pos, length int) IQueryField

SubStr represents a SQL function SUBSTR Deprecated

func TIMESTAMPADD added in v1.1.2

func TIMESTAMPADD(name string, field IQueryField, offsetSeconds int) IQueryField

TIMESTAMPADD represents a SQL function TimestampAdd

func TimestampAdd

func TimestampAdd(name string, field IQueryField, offsetSeconds int) IQueryField

TimestampAdd represents a SQL function TimestampAdd

func UPPER added in v1.1.2

func UPPER(name string, field IQueryField) IQueryField

UPPER represents the SQL function SUM

type IQuerySource

type IQuerySource interface {
	// Expression string in select ... from (expresson here)
	Expression() string

	// Alias is the alias in select ... from (express) as alias
	Alias() string

	// variables in statement
	Variables() []interface{}

	// Field reference to a field by name, optionally giving an alias name
	Field(id string, alias ...string) IQueryField

	// Fields return all the fields that this source provides
	Fields() []IQueryField
	// contains filtered or unexported methods
}

IQuerySource is an interface that represents a data source of a SQL query. the source can be a table or a subquery e.g. SELECT ... FROM (SELECT * FROM tbl) AS A

type IRowScanner

type IRowScanner interface {
	Scan(desc ...interface{}) error
}

IRowScanner is an interface for sql data fetching

type ITableSpec

type ITableSpec interface {
	// Insert performs an insert operation that insert one record at a time
	Insert(dt interface{}) error

	// InsertOrUpdate performs an atomic insert or update operation that insert a new record to update the record with current value
	InsertOrUpdate(dt interface{}) error

	// Update performs an update operation
	Update(dt interface{}, onUpdate func() error) (UpdateDiffs, error)

	// Increment performs a special update that do an atomic incremental update of the numeric fields
	Increment(diff, target interface{}) error

	// Decrement performs a special update that do an atomic decremental update of the numeric fields
	Decrement(diff, target interface{}) error

	// DataType returns the data type corresponding to the table
	DataType() reflect.Type

	// ColumnSpec returns the column definition of a spcific column
	ColumnSpec(name string) IColumnSpec

	// Name returns the name of the table
	Name() string

	// Columns returns the array of columns definitions
	Columns() []IColumnSpec

	// PrimaryColumns returns the array of columns of primary keys
	PrimaryColumns() []IColumnSpec

	// Indexes
	Indexes() []STableIndex

	// Expression returns expression of the table
	Expression() string

	// Instance returns an instance of STable for this spec
	Instance() *STable

	// DropForeignKeySQL returns the SQL statements to drop foreignkeys for this table
	DropForeignKeySQL() []string

	// AddIndex adds index to table
	AddIndex(unique bool, cols ...string) bool

	// SyncSQL returns SQL strings to synchronize the data and model definition of the table
	SyncSQL() []string

	// Sync forces synchronize the data and model definition of the table
	Sync() error

	// Fetch query a struct
	Fetch(dt interface{}) error

	// Database returns the database of this table
	Database() *SDatabase

	// Drop drops table
	Drop() error
}

ITableSpec is the interface represents a table

type InsertSqlResult added in v1.1.0

type InsertSqlResult struct {
	Sql       string
	Values    []interface{}
	Primaries map[string]interface{}
}

type QueryJoinType

type QueryJoinType string

QueryJoinType is the Join type of SQL query, namely, innerjoin, leftjoin and rightjoin

const (
	// INNERJOIN represents innerjoin
	INNERJOIN QueryJoinType = "JOIN"

	// LEFTJOIN represents left join
	LEFTJOIN QueryJoinType = "LEFT JOIN"

	// RIGHTJOIN represents right-join
	RIGHTJOIN QueryJoinType = "RIGHT JOIN"
)

type QueryOrderType

type QueryOrderType string

QueryOrderType indicates the query order type, either ASC or DESC

const (
	// SQL_ORDER_ASC represents Ascending order
	SQL_ORDER_ASC QueryOrderType = "ASC"

	// SQL_ORDER_DESC represents Descending order
	SQL_ORDER_DESC QueryOrderType = "DESC"
)

func (QueryOrderType) Equals

func (qot QueryOrderType) Equals(orderType string) bool

Equals of QueryOrderType determines whether two order type identical

type SAndConditions

type SAndConditions struct {
	SCompoundConditions
}

SAndConditions represents the AND condition, which is a SCompoundConditions

func (*SAndConditions) WhereClause

func (c *SAndConditions) WhereClause() string

WhereClause implementation of SAndConditions for IConditionq

type SBaseBackend added in v1.1.0

type SBaseBackend struct{}

func (*SBaseBackend) AND_Val added in v1.1.2

func (bb *SBaseBackend) AND_Val(name string, field IQueryField, v interface{}) IQueryField

AND_Val represents a SQL function that does binary & operation on a field

func (*SBaseBackend) CAST added in v1.1.2

func (bb *SBaseBackend) CAST(field IQueryField, typeStr string, fieldname string) IQueryField

func (*SBaseBackend) CONCAT added in v1.1.2

func (bb *SBaseBackend) CONCAT(name string, fields ...IQueryField) IQueryField

CONCAT represents a SQL function CONCAT

func (*SBaseBackend) COUNT added in v1.1.2

func (bb *SBaseBackend) COUNT(name string, field ...IQueryField) IQueryField

COUNT represents the SQL function COUNT

func (*SBaseBackend) CanInsert added in v1.1.2

func (bb *SBaseBackend) CanInsert() bool

func (*SBaseBackend) CanInsertOrUpdate added in v1.1.2

func (bb *SBaseBackend) CanInsertOrUpdate() bool

func (*SBaseBackend) CanSupportRowAffected added in v1.1.0

func (bb *SBaseBackend) CanSupportRowAffected() bool

func (*SBaseBackend) CanUpdate added in v1.1.2

func (bb *SBaseBackend) CanUpdate() bool

func (*SBaseBackend) CaseInsensitiveLikeString added in v1.1.2

func (bb *SBaseBackend) CaseInsensitiveLikeString() string

func (*SBaseBackend) CommitTableChangeSQL added in v1.1.2

func (bb *SBaseBackend) CommitTableChangeSQL(ts ITableSpec, changes STableChanges) []string

func (*SBaseBackend) CurrentTimeStampString added in v1.1.2

func (bb *SBaseBackend) CurrentTimeStampString() string

func (*SBaseBackend) CurrentUTCTimeStampString added in v1.1.2

func (bb *SBaseBackend) CurrentUTCTimeStampString() string

func (*SBaseBackend) DATEDIFF added in v1.1.2

func (bb *SBaseBackend) DATEDIFF(unit string, field1, field2 IQueryField) IQueryField

DATEDIFF represents SQL function of DATEDIFF

func (*SBaseBackend) DATE_FORMAT added in v1.1.2

func (bb *SBaseBackend) DATE_FORMAT(name string, field IQueryField, format string) IQueryField

DATE_FORMAT represents a SQL function DATE_FORMAT

func (*SBaseBackend) DISTINCT added in v1.1.2

func (bb *SBaseBackend) DISTINCT(name string, field IQueryField) IQueryField

DISTINCT represents the SQL function DISTINCT

func (*SBaseBackend) DropIndexSQLTemplate added in v1.1.0

func (bb *SBaseBackend) DropIndexSQLTemplate() string

func (*SBaseBackend) DropTableSQL added in v1.1.2

func (bb *SBaseBackend) DropTableSQL(table string) string

func (*SBaseBackend) FetchIndexesAndConstraints added in v1.1.0

func (bb *SBaseBackend) FetchIndexesAndConstraints(ts ITableSpec) ([]STableIndex, []STableConstraint, error)

func (*SBaseBackend) FetchTableColumnSpecs added in v1.1.2

func (bb *SBaseBackend) FetchTableColumnSpecs(ts ITableSpec) ([]IColumnSpec, error)

func (*SBaseBackend) GROUP_CONCAT2 added in v1.1.2

func (bb *SBaseBackend) GROUP_CONCAT2(name string, sep string, field IQueryField) IQueryField

func (*SBaseBackend) GetColumnSpecByFieldType added in v1.1.2

func (bb *SBaseBackend) GetColumnSpecByFieldType(table *STableSpec, fieldType reflect.Type, fieldname string, tagmap map[string]string, isPointer bool) IColumnSpec

func (*SBaseBackend) GetCreateSQLs added in v1.1.2

func (bb *SBaseBackend) GetCreateSQLs(ts ITableSpec) []string

func (*SBaseBackend) GetTableSQL added in v1.1.0

func (bb *SBaseBackend) GetTableSQL() string

func (*SBaseBackend) INET_ATON added in v1.1.2

func (bb *SBaseBackend) INET_ATON(field IQueryField) IQueryField

INET_ATON represents a SQL function INET_ATON

func (*SBaseBackend) InsertOrUpdateSQLTemplate added in v1.1.0

func (bb *SBaseBackend) InsertOrUpdateSQLTemplate() string

func (*SBaseBackend) InsertSQLTemplate added in v1.1.0

func (bb *SBaseBackend) InsertSQLTemplate() string

func (*SBaseBackend) IsSupportIndexAndContraints added in v1.1.2

func (bb *SBaseBackend) IsSupportIndexAndContraints() bool

func (*SBaseBackend) LENGTH added in v1.1.2

func (bb *SBaseBackend) LENGTH(name string, field IQueryField) IQueryField

LENGTH represents SQL function LENGTH

func (*SBaseBackend) LOWER added in v1.1.2

func (bb *SBaseBackend) LOWER(name string, field IQueryField) IQueryField

LOWER represents SQL function of LOWER

func (*SBaseBackend) MAX added in v1.1.2

func (bb *SBaseBackend) MAX(name string, field IQueryField) IQueryField

MAX represents the SQL function MAX

func (*SBaseBackend) MIN added in v1.1.2

func (bb *SBaseBackend) MIN(name string, field IQueryField) IQueryField

MIN represents the SQL function MIN

func (*SBaseBackend) Name added in v1.1.2

func (bb *SBaseBackend) Name() DBBackendName

func (*SBaseBackend) OR_Val added in v1.1.2

func (bb *SBaseBackend) OR_Val(name string, field IQueryField, v interface{}) IQueryField

OR_Val represents a SQL function that does binary | operation on a field

func (*SBaseBackend) REPLACE added in v1.1.2

func (bb *SBaseBackend) REPLACE(name string, field IQueryField, old string, new string) IQueryField

REPLACE represents a SQL function REPLACE

func (*SBaseBackend) RegexpWhereClause added in v1.1.2

func (bb *SBaseBackend) RegexpWhereClause(cond *SRegexpConition) string

func (*SBaseBackend) SUBSTR added in v1.1.2

func (bb *SBaseBackend) SUBSTR(name string, field IQueryField, pos, length int) IQueryField

SubStr represents a SQL function SUBSTR

func (*SBaseBackend) SUM added in v1.1.2

func (bb *SBaseBackend) SUM(name string, field IQueryField) IQueryField

SUM represents the SQL function SUM

func (*SBaseBackend) SupportMixedInsertVariables added in v1.1.2

func (bb *SBaseBackend) SupportMixedInsertVariables() bool

func (*SBaseBackend) TIMESTAMPADD added in v1.1.2

func (bb *SBaseBackend) TIMESTAMPADD(name string, field IQueryField, offsetSeconds int) IQueryField

TimestampAdd represents a SQL function TimestampAdd

func (*SBaseBackend) UPPER added in v1.1.2

func (bb *SBaseBackend) UPPER(name string, field IQueryField) IQueryField

UPPER represents SQL function of UPPER

func (*SBaseBackend) UnionAllString added in v1.1.2

func (bb *SBaseBackend) UnionAllString() string

func (*SBaseBackend) UnionDistinctString added in v1.1.2

func (bb *SBaseBackend) UnionDistinctString() string

func (*SBaseBackend) UpdateSQLTemplate added in v1.1.2

func (bb *SBaseBackend) UpdateSQLTemplate() string

type SBaseColumn

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

SBaseColumn is the base structure represents a column

func NewBaseColumn

func NewBaseColumn(name string, sqltype string, tagmap map[string]string, isPointer bool) SBaseColumn

NewBaseColumn returns an instance of SBaseColumn

func (*SBaseColumn) AllowZero

func (c *SBaseColumn) AllowZero() bool

AllowZero implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) AutoIncrementOffset added in v1.1.0

func (c *SBaseColumn) AutoIncrementOffset() int64

func (*SBaseColumn) ColType

func (c *SBaseColumn) ColType() string

ColType implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) ConvertFromValue

func (c *SBaseColumn) ConvertFromValue(val interface{}) interface{}

ConvertFromValue implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) Default

func (c *SBaseColumn) Default() string

Default implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) ExtraDefs

func (c *SBaseColumn) ExtraDefs() string

ExtraDefs implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) GetColIndex added in v1.1.2

func (c *SBaseColumn) GetColIndex() int

func (*SBaseColumn) IsAscii

func (c *SBaseColumn) IsAscii() bool

IsAscii implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) IsAutoIncrement added in v1.1.0

func (c *SBaseColumn) IsAutoIncrement() bool

func (*SBaseColumn) IsAutoVersion added in v1.1.0

func (c *SBaseColumn) IsAutoVersion() bool

func (*SBaseColumn) IsCreatedAt added in v1.1.0

func (c *SBaseColumn) IsCreatedAt() bool

func (*SBaseColumn) IsDateTime added in v1.1.0

func (c *SBaseColumn) IsDateTime() bool

func (*SBaseColumn) IsIndex

func (c *SBaseColumn) IsIndex() bool

IsIndex implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) IsNullable

func (c *SBaseColumn) IsNullable() bool

IsNullable implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) IsNumeric

func (c *SBaseColumn) IsNumeric() bool

IsNumeric implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) IsPointer

func (c *SBaseColumn) IsPointer() bool

IsPointer implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) IsPrimary

func (c *SBaseColumn) IsPrimary() bool

IsPrimary implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) IsSearchable

func (c *SBaseColumn) IsSearchable() bool

IsSearchable implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) IsString added in v1.1.0

func (c *SBaseColumn) IsString() bool

func (*SBaseColumn) IsSupportDefault

func (c *SBaseColumn) IsSupportDefault() bool

IsSupportDefault implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) IsText

func (c *SBaseColumn) IsText() bool

IsText implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) IsUnique

func (c *SBaseColumn) IsUnique() bool

IsUnique implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) IsUpdatedAt added in v1.1.0

func (c *SBaseColumn) IsUpdatedAt() bool

func (*SBaseColumn) Name

func (c *SBaseColumn) Name() string

Name implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) SetAutoIncrement added in v1.1.0

func (c *SBaseColumn) SetAutoIncrement(val bool)

func (*SBaseColumn) SetAutoIncrementOffset added in v1.1.0

func (c *SBaseColumn) SetAutoIncrementOffset(offset int64)

func (*SBaseColumn) SetColIndex added in v1.1.2

func (c *SBaseColumn) SetColIndex(idx int)

func (*SBaseColumn) SetDefault

func (c *SBaseColumn) SetDefault(defStr string)

SetDefault implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) SetNullable

func (c *SBaseColumn) SetNullable(on bool)

SetNullable implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) SetPrimary added in v1.1.0

func (c *SBaseColumn) SetPrimary(on bool)

func (*SBaseColumn) Tags

func (c *SBaseColumn) Tags() map[string]string

Tags implementation of SBaseColumn for IColumnSpec

type SBaseCompoundColumn added in v1.1.0

type SBaseCompoundColumn struct{}

func (*SBaseCompoundColumn) ConvertFromString added in v1.1.0

func (c *SBaseCompoundColumn) ConvertFromString(str string) interface{}

ConvertFromString implementation of CompoundColumn for IColumnSpec

func (*SBaseCompoundColumn) ConvertFromValue added in v1.1.0

func (c *SBaseCompoundColumn) ConvertFromValue(val interface{}) interface{}

ConvertFromValue implementation of CompoundColumn for IColumnSpec

type SBaseWidthColumn

type SBaseWidthColumn struct {
	SBaseColumn
	// contains filtered or unexported fields
}

SBaseWidthColumn represents a type of column that with width attribute, such as VARCHAR(20), INT(10)

func NewBaseWidthColumn

func NewBaseWidthColumn(name string, sqltype string, tagmap map[string]string, isPointer bool) SBaseWidthColumn

NewBaseWidthColumn return an instance of SBaseWidthColumn

func (*SBaseWidthColumn) ColType

func (c *SBaseWidthColumn) ColType() string

ColType implementation of SBaseWidthColumn for IColumnSpec

type SBetweenCondition

type SBetweenCondition struct {
	STripleCondition
}

SBetweenCondition represents BETWEEN operator, e.g. c between a and b

func (*SBetweenCondition) WhereClause

func (t *SBetweenCondition) WhereClause() string

WhereClause implementation of SBetweenCondition for ICondition

type SCaseFunction

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

SCaseFunction represents function of case ... when ... branch

func NewCase

func NewCase() *SCaseFunction

NewCase creates a case... when...else... representation instance

func (*SCaseFunction) Else

func (cf *SCaseFunction) Else(field IQueryField) *SCaseFunction

Else adds else clause for case when function

func (*SCaseFunction) When

func (cf *SCaseFunction) When(when ICondition, then IQueryField) *SCaseFunction

When adds when clause for case when function

type SCompoundConditions

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

SCompoundConditions is a Compound condition represents AND or OR boolean operation Compound condition also follows the ICondition interface

func (*SCompoundConditions) Variables

func (c *SCompoundConditions) Variables() []interface{}

Variables implementation of SCompoundConditions for ICondition

func (*SCompoundConditions) WhereClause

func (c *SCompoundConditions) WhereClause() string

WhereClause implementation of SCompoundConditions for ICondition

type SConstField

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

SConstField is a query field of a constant

func NewConstField

func NewConstField(variable interface{}) *SConstField

NewConstField returns an instance of SConstField

func (*SConstField) Expression

func (s *SConstField) Expression() string

Expression implementation of SConstField for IQueryField

func (*SConstField) Label

func (s *SConstField) Label(label string) IQueryField

Label implementation of SConstField for IQueryField

func (*SConstField) Name

func (s *SConstField) Name() string

Name implementation of SConstField for IQueryField

func (*SConstField) Reference

func (s *SConstField) Reference() string

Reference implementation of SConstField for IQueryField

func (*SConstField) Variables

func (s *SConstField) Variables() []interface{}

Variables implementation of SConstField for IQueryField

type SDatabase added in v1.1.0

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

SDatabase represents a SQL database

func GetDBWithName added in v1.1.0

func GetDBWithName(name DBName) *SDatabase

GetDBWithName returns the db instance with given name

func GetDefaultDB added in v1.1.0

func GetDefaultDB() *SDatabase

GetDefaultDB get the DB instance set by default

func (*SDatabase) DB added in v1.1.2

func (db *SDatabase) DB() *sql.DB

func (*SDatabase) Exec added in v1.1.0

func (db *SDatabase) Exec(sql string, args ...interface{}) (sql.Result, error)

Exec execute a raw SQL query for a db instance

func (*SDatabase) GetTables added in v1.1.0

func (db *SDatabase) GetTables() []string

GetTables get all tables' name in database

func (*SDatabase) NewRawQuery added in v1.1.0

func (db *SDatabase) NewRawQuery(sqlStr string, fields ...string) *SQuery

NewRawQuery returns an instance of SQuery with raw SQL query for a database, e.g. show tables

func (*SDatabase) TxBatchExec added in v1.1.0

func (db *SDatabase) TxBatchExec(sqlstr string, varsList [][]interface{}) ([]SSqlResult, error)

func (*SDatabase) TxExec added in v1.1.0

func (db *SDatabase) TxExec(sqlstr string, vars ...interface{}) (sql.Result, error)

type SEqualsCondition

type SEqualsCondition struct {
	STupleCondition
}

SEqualsCondition represents equal operation between two fields

func (*SEqualsCondition) WhereClause

func (t *SEqualsCondition) WhereClause() string

WhereClause implementation of SEqualsCondition for ICondition

type SFalseCondition

type SFalseCondition struct{}

SFalseCondition is a dummy condition that is always false

func (*SFalseCondition) Variables

func (t *SFalseCondition) Variables() []interface{}

Variables implementation of SFalseCondition for ICondition

func (*SFalseCondition) WhereClause

func (t *SFalseCondition) WhereClause() string

WhereClause implementation of SFalseCondition for ICondition

type SFunctionFieldBase

type SFunctionFieldBase struct {
	IFunction
	// contains filtered or unexported fields
}

SFunctionFieldBase is a query field that is the result of a SQL embedded function, e.g. COUNT(*) as count

func (*SFunctionFieldBase) Expression

func (ff *SFunctionFieldBase) Expression() string

Expression implementation of SFunctionFieldBase for IQueryField

func (*SFunctionFieldBase) Label

func (ff *SFunctionFieldBase) Label(label string) IQueryField

Label implementation of SFunctionFieldBase for IQueryField

func (*SFunctionFieldBase) Name

func (ff *SFunctionFieldBase) Name() string

Name implementation of SFunctionFieldBase for IQueryField

func (*SFunctionFieldBase) Reference

func (ff *SFunctionFieldBase) Reference() string

Reference implementation of SFunctionFieldBase for IQueryField

func (*SFunctionFieldBase) Variables

func (ff *SFunctionFieldBase) Variables() []interface{}

Variables implementation of SFunctionFieldBase for IQueryField

type SGreatEqualCondition

type SGreatEqualCondition struct {
	STupleCondition
}

SGreatEqualCondition represents >= operation on two fields

func (*SGreatEqualCondition) WhereClause

func (t *SGreatEqualCondition) WhereClause() string

WhereClause implementation of SGreatEqualCondition for ICondition

type SGreatThanCondition

type SGreatThanCondition struct {
	STupleCondition
}

SGreatThanCondition represetns > operation on two fields

func (*SGreatThanCondition) WhereClause

func (t *SGreatThanCondition) WhereClause() string

WhereClause implementation of SGreatThanCondition for ICondition

type SInCondition

type SInCondition struct {
	STupleCondition
	// contains filtered or unexported fields
}

SInCondition represents a IN operation in SQL query

func (*SInCondition) WhereClause

func (t *SInCondition) WhereClause() string

WhereClause implementation of SInCondition for ICondition

type SIsEmptyCondition

type SIsEmptyCondition struct {
	SSingleCondition
}

SIsEmptyCondition is a condition representing the empty status of a field

func (*SIsEmptyCondition) WhereClause

func (c *SIsEmptyCondition) WhereClause() string

WhereClause implementation of SIsEmptyCondition for ICondition

type SIsFalseCondition

type SIsFalseCondition struct {
	SSingleCondition
}

SIsFalseCondition represents a boolean is false

func (*SIsFalseCondition) WhereClause

func (c *SIsFalseCondition) WhereClause() string

WhereClause implementation of SIsFalseCondition for ICondition

type SIsNotEmptyCondition

type SIsNotEmptyCondition struct {
	SSingleCondition
}

SIsNotEmptyCondition represents a condition that represents a field is not empty

func (*SIsNotEmptyCondition) WhereClause

func (c *SIsNotEmptyCondition) WhereClause() string

WhereClause implementation of SIsNotEmptyCondition for ICondition

type SIsNotNullCondition

type SIsNotNullCondition struct {
	SSingleCondition
}

SIsNotNullCondition is a condition represents a comparison with not null, e.g. a is not null

func (*SIsNotNullCondition) WhereClause

func (c *SIsNotNullCondition) WhereClause() string

WhereClause implementation of SIsNotNullCondition for ICondition

type SIsNullCondition

type SIsNullCondition struct {
	SSingleCondition
}

SIsNullCondition is a condition representing a comparison with null, e.g. a is null

func (*SIsNullCondition) WhereClause

func (c *SIsNullCondition) WhereClause() string

WhereClause implementation for SIsNullCondition for ICondition

type SIsNullOrEmptyCondition

type SIsNullOrEmptyCondition struct {
	SSingleCondition
}

SIsNullOrEmptyCondition is a condition that justifies a field is null or empty

func (*SIsNullOrEmptyCondition) WhereClause

func (c *SIsNullOrEmptyCondition) WhereClause() string

WhereClause implementation of SIsNullOrEmptyCondition for ICondition

type SIsTrueCondition

type SIsTrueCondition struct {
	SSingleCondition
}

SIsTrueCondition represents a boolean field (TINYINT) is true, e.g. a == 1

func (*SIsTrueCondition) WhereClause

func (c *SIsTrueCondition) WhereClause() string

WhereClause implementation of SIsTrueCondition for ICondition

type SLessEqualCondition

type SLessEqualCondition struct {
	STupleCondition
}

SLessEqualCondition represents <= operation on two fields

func (*SLessEqualCondition) WhereClause

func (t *SLessEqualCondition) WhereClause() string

WhereClause implementation of SLessEqualCondition for ICondition

type SLessThanCondition

type SLessThanCondition struct {
	STupleCondition
}

SLessThanCondition represents < operation on two fields

func (*SLessThanCondition) WhereClause

func (t *SLessThanCondition) WhereClause() string

WhereClause implementation of SLessThanCondition for ICondition

type SLikeCondition

type SLikeCondition struct {
	STupleCondition
}

SLikeCondition represents LIKE operation in a SQL query

func (*SLikeCondition) WhereClause

func (t *SLikeCondition) WhereClause() string

WhereClause implementation for SLikeCondition for ICondition

type SNoEarlierThanCondition

type SNoEarlierThanCondition struct {
	SSingleCondition
}

SNoEarlierThanCondition compares a field with current time and ensure the field is no earlier than NOW, e.g. a >= NOW()

func (*SNoEarlierThanCondition) WhereClause

func (c *SNoEarlierThanCondition) WhereClause() string

WhereClause implementation of SNoEarlierThanCondition for ICondition

type SNoLaterThanCondition

type SNoLaterThanCondition struct {
	SSingleCondition
}

SNoLaterThanCondition coompares a DATETIME field with current time and ensure the field is no later than now, e.g. a <= NOW()

func (*SNoLaterThanCondition) WhereClause

func (c *SNoLaterThanCondition) WhereClause() string

WhereClause implementation of SNoLaterThanCondition for ICondition

type SNotCondition

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

SNotCondition represents the NOT condition, which is a boolean operator

func (*SNotCondition) Variables

func (c *SNotCondition) Variables() []interface{}

Variables implementation of SNotCondition for ICondition

func (*SNotCondition) WhereClause

func (c *SNotCondition) WhereClause() string

WhereClause implementationq of SNotCondition for ICondition

type SNotEqualsCondition

type SNotEqualsCondition struct {
	STupleCondition
}

SNotEqualsCondition is the opposite of equal condition

func (*SNotEqualsCondition) WhereClause

func (t *SNotEqualsCondition) WhereClause() string

WhereClause implementation of SNotEqualsCondition for ICondition

type SOrConditions

type SOrConditions struct {
	SCompoundConditions
}

SOrConditions represents the OR condition, which is a SCompoundConditions

func (*SOrConditions) WhereClause

func (c *SOrConditions) WhereClause() string

WhereClause implementation of SOrConditions for ICondition

type SQuery

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

SQuery is a data structure represents a SQL query in the form of

SELECT ... FROM ... JOIN ... ON ... WHERE ... GROUP BY ... ORDER BY ... HAVING ...

func DoQuery

func DoQuery(from IQuerySource, f ...IQueryField) *SQuery

DoQuery returns a SQuery instance that query specified fields from a query source

func NewRawQuery

func NewRawQuery(sqlStr string, fields ...string) *SQuery

NewRawQuery returns an instance of SQuery with raw SQL query. e.g. show tables

func (*SQuery) All

func (tq *SQuery) All(dest interface{}) error

All return query results of all rows and store the result in an array of data struct

func (*SQuery) AllStringMap

func (tq *SQuery) AllStringMap() ([]map[string]string, error)

AllStringMap returns query result of all rows in an array of stringmap(map[string]string)

func (*SQuery) AppendField

func (tq *SQuery) AppendField(f ...IQueryField) *SQuery

AppendField appends query field to a query

func (*SQuery) Asc

func (tq *SQuery) Asc(fields ...interface{}) *SQuery

Asc of SQuery does query in ascending order of specified fields

func (*SQuery) Between

func (tq *SQuery) Between(f string, v1, v2 interface{}) *SQuery

Between filters query with a between condition

func (*SQuery) Contains

func (tq *SQuery) Contains(f string, v string) *SQuery

Contains filters query with a contains condition

func (*SQuery) Copy added in v1.1.2

func (self *SQuery) Copy() *SQuery

func (*SQuery) Count

func (tq *SQuery) Count() int

Count of SQuery returns the count of a query use CountWithError instead deprecated

func (*SQuery) CountQuery added in v1.1.0

func (tq *SQuery) CountQuery() *SQuery

func (*SQuery) CountWithError

func (tq *SQuery) CountWithError() (int, error)

CountWithError of SQuery returns the row count of a query

func (*SQuery) DebugQuery

func (tq *SQuery) DebugQuery()

DebugQuery show the full query string for debug

func (*SQuery) Desc

func (tq *SQuery) Desc(fields ...interface{}) *SQuery

Desc of SQuery does query in descending order of specified fields

func (*SQuery) Distinct

func (tq *SQuery) Distinct() *SQuery

Distinct of SQuery indicates a distinct query results

func (*SQuery) Endswith

func (tq *SQuery) Endswith(f string, v string) *SQuery

Endswith filters query with a endswith condition

func (*SQuery) Equals

func (tq *SQuery) Equals(f string, v interface{}) *SQuery

Equals filters query with a equals condition

func (*SQuery) Field

func (tq *SQuery) Field(name string) IQueryField

Field implementation of SQuery for IQuery

func (*SQuery) Filter

func (tq *SQuery) Filter(cond ICondition) *SQuery

Filter method filters a SQL query with given ICondition equivalent to add a clause in where conditions

func (*SQuery) FilterByFalse

func (tq *SQuery) FilterByFalse() *SQuery

FilterByFalse filters query with a false condition

func (*SQuery) FilterByTrue

func (tq *SQuery) FilterByTrue() *SQuery

FilterByTrue filters query with a true condition

func (*SQuery) First

func (tq *SQuery) First(dest interface{}) error

First return query result of first row and store the result in a data struct

func (*SQuery) FirstStringMap

func (tq *SQuery) FirstStringMap() (map[string]string, error)

FirstStringMap returns query result of the first row in a stringmap(map[string]string)

func (*SQuery) GE

func (tq *SQuery) GE(f string, v interface{}) *SQuery

GE filters the query with a >= condition

func (*SQuery) GT

func (tq *SQuery) GT(f string, v interface{}) *SQuery

GT filters the query with a > condition

func (*SQuery) GroupBy

func (tq *SQuery) GroupBy(f ...interface{}) *SQuery

GroupBy of SQuery does query group by specified fields

func (*SQuery) HasField added in v1.1.2

func (tq *SQuery) HasField(f IQueryField) bool

func (*SQuery) In

func (tq *SQuery) In(f string, v interface{}) *SQuery

In filters query with a in condition

func (*SQuery) IsAltered

func (tq *SQuery) IsAltered() bool

IsAltered of SQuery indicates whether a query was altered. By comparing with the saved query snapshot, we can tell whether a query is altered

func (*SQuery) IsEmpty

func (tq *SQuery) IsEmpty(f string) *SQuery

IsEmpty filters the query with a is_empty condition

func (*SQuery) IsFalse

func (tq *SQuery) IsFalse(f string) *SQuery

IsFalse filters the query with a is false condition

func (*SQuery) IsGroupBy added in v1.1.0

func (tq *SQuery) IsGroupBy() bool

IsGroupBy returns wether the query contains group by clauses

func (*SQuery) IsNotEmpty

func (tq *SQuery) IsNotEmpty(f string) *SQuery

IsNotEmpty filters the query with a is not empty condition

func (*SQuery) IsNotNull

func (tq *SQuery) IsNotNull(f string) *SQuery

IsNotNull filters the query with a is not null condition

func (*SQuery) IsNull

func (tq *SQuery) IsNull(f string) *SQuery

IsNull filters the query with a is null condition

func (*SQuery) IsNullOrEmpty

func (tq *SQuery) IsNullOrEmpty(f string) *SQuery

IsNullOrEmpty filters the query with a is null or empty condition

func (*SQuery) IsTrue

func (tq *SQuery) IsTrue(f string) *SQuery

IsTrue filters the query with a is true condition

func (*SQuery) Join

func (tq *SQuery) Join(from IQuerySource, on ICondition) *SQuery

Join of SQuery joins query with another IQuerySource on specified condition

func (*SQuery) LE

func (tq *SQuery) LE(f string, v interface{}) *SQuery

LE filters the query with a <= condition

func (*SQuery) LT

func (tq *SQuery) LT(f string, v interface{}) *SQuery

LT filters the query with a < condition

func (*SQuery) LeftJoin

func (tq *SQuery) LeftJoin(from IQuerySource, on ICondition) *SQuery

LeftJoin of SQuery left-joins query with another IQuerySource on specified condition

func (*SQuery) Like

func (tq *SQuery) Like(f string, v string) *SQuery

Like filters query with a like condition

func (*SQuery) Limit

func (tq *SQuery) Limit(limit int) *SQuery

Limit of SQuery adds limit to a query

func (*SQuery) NotBetween

func (tq *SQuery) NotBetween(f string, v1, v2 interface{}) *SQuery

NotBetween filters query with a not between condition

func (*SQuery) NotEquals

func (tq *SQuery) NotEquals(f string, v interface{}) *SQuery

NotEquals filters the query with a not equals condition

func (*SQuery) NotIn

func (tq *SQuery) NotIn(f string, v interface{}) *SQuery

NotIn filters query with a not in condition

func (*SQuery) NotLike

func (tq *SQuery) NotLike(f string, v string) *SQuery

NotLike filters query with a not like condition

func (*SQuery) Offset

func (tq *SQuery) Offset(offset int) *SQuery

Offset of SQuery adds offset to a query

func (*SQuery) QueryFields

func (tq *SQuery) QueryFields() []IQueryField

QueryFields of SQuery returns fields in SELECT clause of a query

func (*SQuery) Regexp added in v1.1.2

func (tq *SQuery) Regexp(f string, v string) *SQuery

Regexp filters query with a regexp condition

func (*SQuery) ResetFields added in v1.1.2

func (tq *SQuery) ResetFields() *SQuery

func (*SQuery) RightJoin

func (tq *SQuery) RightJoin(from IQuerySource, on ICondition) *SQuery

RightJoin of SQuery right-joins query with another IQuerySource on specified condition

func (*SQuery) Row

func (tq *SQuery) Row() *sql.Row

Row of SQuery returns an instance of sql.Row for native data fetching

func (*SQuery) Row2Map

func (tq *SQuery) Row2Map(row IRowScanner) (map[string]string, error)

Row2Map is a utility function that fetch stringmap(map[string]string) from a native sql.Row or sql.Rows

func (*SQuery) Row2Struct

func (tq *SQuery) Row2Struct(row IRowScanner, dest interface{}) error

Row2Struct is a utility function that fill a struct with the value of a sql.Row or sql.Rows

func (*SQuery) RowMap2Struct

func (tq *SQuery) RowMap2Struct(result map[string]string, dest interface{}) error

RowMap2Struct is a utility function that fetch struct from a native sql.Row or sql.Rows

func (*SQuery) Rows

func (tq *SQuery) Rows() (*sql.Rows, error)

Rows of SQuery returns an instance of sql.Rows for native data fetching

func (*SQuery) Snapshot

func (tq *SQuery) Snapshot() *SQuery

Snapshot of SQuery take a snapshot of the query, so we can tell wether the query is modified later by comparing the SQL with snapshot

func (*SQuery) Startswith

func (tq *SQuery) Startswith(f string, v string) *SQuery

Startswith filters query with a startswith condition

func (*SQuery) String

func (tq *SQuery) String(fields ...IQueryField) string

String of SQuery implemetation of SQuery for IQuery

func (*SQuery) SubQuery

func (tq *SQuery) SubQuery() *SSubQuery

SubQuery of SQuery generates a SSubQuery from a Query

func (*SQuery) Variables

func (tq *SQuery) Variables() []interface{}

Variables implementation of SQuery for IQuery

type SRawQueryField

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

SRawQueryField is a struct represents a field of a raw SQL query a raw query is a query that not follow standard SELECT ... FROM ... pattern e.g. show tables the struct implements IQueryField interface

func (*SRawQueryField) Expression

func (rqf *SRawQueryField) Expression() string

Expression implementation of SRawQueryField for IQueryField

func (*SRawQueryField) Label

func (rqf *SRawQueryField) Label(label string) IQueryField

Label implementation of SRawQueryField for IQueryField

func (*SRawQueryField) Name

func (rqf *SRawQueryField) Name() string

Name implementation of SRawQueryField for IQueryField

func (*SRawQueryField) Reference

func (rqf *SRawQueryField) Reference() string

Reference implementation of SRawQueryField for IQueryField

func (*SRawQueryField) Variables

func (rqf *SRawQueryField) Variables() []interface{}

Variables implementation of SRawQueryField for IQueryField

type SRegexpConition added in v1.1.2

type SRegexpConition struct {
	STupleCondition
}

SRegexpConition represents REGEXP operation in a SQL query

func (*SRegexpConition) WhereClause added in v1.1.2

func (t *SRegexpConition) WhereClause() string

WhereClause implementation for SRegexpConition for ICondition

type SSingleCondition

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

SSingleCondition represents a kind of condition that composed of one query field

func NewSingleCondition

func NewSingleCondition(field IQueryField) SSingleCondition

NewSingleCondition returns an instance of SSingleCondition

func (*SSingleCondition) Variables

func (c *SSingleCondition) Variables() []interface{}

Variables implementation of SSingleCondition for ICondition

type SSqlResult added in v1.1.0

type SSqlResult struct {
	Result sql.Result
	Error  error
}

type SStringField

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

SStringField is a query field of a string constant

func NewStringField

func NewStringField(strConst string) *SStringField

NewStringField returns an instance of SStringField

func (*SStringField) Expression

func (s *SStringField) Expression() string

Expression implementation of SStringField for IQueryField

func (*SStringField) Label

func (s *SStringField) Label(label string) IQueryField

Label implementation of SStringField for IQueryField

func (*SStringField) Name

func (s *SStringField) Name() string

Name implementation of SStringField for IQueryField

func (*SStringField) Reference

func (s *SStringField) Reference() string

Reference implementation of SStringField for IQueryField

func (*SStringField) Variables

func (s *SStringField) Variables() []interface{}

Variables implementation of SStringField for IQueryField

type SSubQuery

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

SSubQuery represents a subquery. A subquery is a query used as a query source SSubQuery should implementation IQuerySource At the same time, a subquery can be used in condition. e.g. IN condition

func (*SSubQuery) Alias

func (sq *SSubQuery) Alias() string

Alias implementation of SSubQuery for IQuerySource

func (*SSubQuery) DebugQuery

func (sqf *SSubQuery) DebugQuery()

DebugQuery show the full query string for a subquery for debug

func (*SSubQuery) Expression

func (sq *SSubQuery) Expression() string

Expression implementation of SSubQuery for IQuerySource

func (*SSubQuery) Field

func (sq *SSubQuery) Field(id string, alias ...string) IQueryField

Field implementation of SSubQuery for IQuerySource

func (*SSubQuery) Fields

func (sq *SSubQuery) Fields() []IQueryField

Fields implementation of SSubQuery for IQuerySource

func (*SSubQuery) Query

func (sq *SSubQuery) Query(f ...IQueryField) *SQuery

Query of SSubQuery generates a new query from a subquery

func (*SSubQuery) Variables

func (sq *SSubQuery) Variables() []interface{}

Variables implementation of SSubQuery for IQuerySource

type SSubQueryField

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

SSubQueryField represents a field of subquery, which implements IQueryField

func (*SSubQueryField) Expression

func (sqf *SSubQueryField) Expression() string

Expression implementation of SSubQueryField for IQueryField

func (*SSubQueryField) Label

func (sqf *SSubQueryField) Label(label string) IQueryField

Label implementation of SSubQueryField for IQueryField

func (*SSubQueryField) Name

func (sqf *SSubQueryField) Name() string

Name implementation of SSubQueryField for IQueryField

func (*SSubQueryField) Reference

func (sqf *SSubQueryField) Reference() string

Reference implementation of SSubQueryField for IQueryField

func (*SSubQueryField) Variables

func (sqf *SSubQueryField) Variables() []interface{}

Variables implementation of SSubQueryField for IQueryField

type STable

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

STable is an instance of table for query, system will automatically give a alias to this table

func NewTableInstance

func NewTableInstance(ts ITableSpec) *STable

NewTableInstance return an new table instance from an ITableSpec

func (*STable) Alias

func (tbl *STable) Alias() string

Alias implementation of STable for IQuerySource

func (*STable) Expression

func (tbl *STable) Expression() string

Expression implementation of STable for IQuerySource

func (*STable) Field

func (tbl *STable) Field(name string, alias ...string) IQueryField

Field implementation of STableSpec for IQuerySource

func (*STable) Fields

func (tbl *STable) Fields() []IQueryField

Fields implementation of STable for IQuerySource

func (*STable) Query

func (tbl *STable) Query(f ...IQueryField) *SQuery

Query of STable generates a new query from a table

func (*STable) Variables

func (tbl *STable) Variables() []interface{}

Variables implementation of STable for IQuerySource

type STableChanges added in v1.1.0

type STableChanges struct {
	// indexes
	RemoveIndexes []STableIndex
	AddIndexes    []STableIndex

	// Columns
	RemoveColumns  []IColumnSpec
	UpdatedColumns []SUpdateColumnSpec
	AddColumns     []IColumnSpec

	OldColumns []IColumnSpec
}

type STableConstraint added in v1.1.0

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

func NewTableConstraint added in v1.1.0

func NewTableConstraint(name string, cols []string, foreignTable string, fcols []string) STableConstraint

type STableField

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

STableField represents a field in a table, implements IQueryField

func (*STableField) Expression

func (c *STableField) Expression() string

Expression implementation of STableField for IQueryField

func (*STableField) Label

func (c *STableField) Label(label string) IQueryField

Label implementation of STableField for IQueryField

func (*STableField) Name

func (c *STableField) Name() string

Name implementation of STableField for IQueryField

func (*STableField) Reference

func (c *STableField) Reference() string

Reference implementation of STableField for IQueryField

func (*STableField) Variables

func (c *STableField) Variables() []interface{}

Variables implementation of STableField for IQueryField

type STableIndex added in v1.1.0

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

func NewTableIndex added in v1.1.0

func NewTableIndex(ts ITableSpec, name string, cols []string, unique bool) STableIndex

func (*STableIndex) IsIdentical added in v1.1.0

func (index *STableIndex) IsIdentical(cols ...string) bool

func (*STableIndex) Name added in v1.1.0

func (index *STableIndex) Name() string

func (*STableIndex) QuotedColumns added in v1.1.0

func (index *STableIndex) QuotedColumns() []string

type STableSpec

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

STableSpec defines the table specification, which implements ITableSpec

func NewTableSpecFromStruct

func NewTableSpecFromStruct(s interface{}, name string) *STableSpec

NewTableSpecFromStruct generates STableSpec based on the information of a struct model

func NewTableSpecFromStructWithDBName added in v1.1.0

func NewTableSpecFromStructWithDBName(s interface{}, name string, dbName DBName) *STableSpec

func (*STableSpec) AddIndex

func (ts *STableSpec) AddIndex(unique bool, cols ...string) bool

func (*STableSpec) CheckSync

func (ts *STableSpec) CheckSync() error

CheckSync checks whether the table in database consistent with TableSpec

func (*STableSpec) Clone

func (ts *STableSpec) Clone(name string, autoIncOffset int64) *STableSpec

Clone makes a clone of a table, so we may create a new table of the same schema

func (*STableSpec) CloneWithSyncColumnOrder added in v1.1.2

func (ts *STableSpec) CloneWithSyncColumnOrder(name string, autoIncOffset int64, syncColOrder bool) (*STableSpec, error)

Clone makes a clone of a table, so we may create a new table of the same schema

func (*STableSpec) ColumnSpec

func (ts *STableSpec) ColumnSpec(name string) IColumnSpec

ColumnSpec implementation of STableSpec for ITableSpec

func (*STableSpec) Columns

func (ts *STableSpec) Columns() []IColumnSpec

Columns implementation of STableSpec for ITableSpec

func (*STableSpec) CreateSQLs added in v1.1.0

func (ts *STableSpec) CreateSQLs() []string

CreateSQL returns the SQL for creating this table

func (*STableSpec) DBName added in v1.1.0

func (r *STableSpec) DBName() DBName

func (*STableSpec) DataType

func (ts *STableSpec) DataType() reflect.Type

DataType implementation of STableSpec for ITableSpec

func (*STableSpec) Database added in v1.1.0

func (r *STableSpec) Database() *SDatabase

func (*STableSpec) DebugInsert

func (t *STableSpec) DebugInsert(dt interface{}) error

DebugInsert does insert with debug mode on

func (*STableSpec) DebugInsertOrUpdate

func (t *STableSpec) DebugInsertOrUpdate(dt interface{}) error

DebugInsertOrUpdate does insertOrUpdate with debug mode on

func (*STableSpec) DebugUpdateFields

func (t *STableSpec) DebugUpdateFields(dt interface{}, fields map[string]interface{}) error

DebugUpdateFields does update with debug mode on

func (*STableSpec) Decrement

func (t *STableSpec) Decrement(diff interface{}, target interface{}) error

Decrement is similar to Increment methods, the difference is that this method will atomically decrease the numeric fields with the value of diff

func (*STableSpec) DeleteFrom added in v1.1.2

func (ts *STableSpec) DeleteFrom(filters map[string]interface{}) error

func (*STableSpec) Drop added in v1.1.2

func (ts *STableSpec) Drop() error

Drop drop table

func (*STableSpec) DropForeignKeySQL

func (ts *STableSpec) DropForeignKeySQL() []string

DropForeignKeySQL returns the SQL statements to do droping foreignkey for a TableSpec

func (*STableSpec) Exists

func (ts *STableSpec) Exists() bool

Exists checks wheter a table exists

func (*STableSpec) Expression

func (ts *STableSpec) Expression() string

Expression implementation of STableSpec for ITableSpec

func (*STableSpec) Fetch

func (ts *STableSpec) Fetch(dt interface{}) error

Fetch method fetches the values of a struct whose primary key values have been set input is a pointer to the model to be populated

func (*STableSpec) FetchAll

func (ts *STableSpec) FetchAll(dest interface{}) error

FetchAll method fetches the values of an array of structs whose primary key values have been set input is a pointer to the array of models to be populated

func (*STableSpec) Increment

func (t *STableSpec) Increment(diff interface{}, target interface{}) error

Increment perform an incremental update on a record, the primary key of the record is specified in diff, the numeric fields of this record will be atomically added by the value of the corresponding field in diff if target is given as a pointer to a variable, the result will be stored in the target if target is not given, the updated result will be stored in diff

func (*STableSpec) Indexes added in v1.1.0

func (ts *STableSpec) Indexes() []STableIndex

Indexes implementation of STableSpec for ITableSpec

func (*STableSpec) Insert

func (t *STableSpec) Insert(dt interface{}) error

Insert perform a insert operation, the value of the record is store in dt

func (*STableSpec) InsertBatch added in v1.1.2

func (t *STableSpec) InsertBatch(dataList []interface{}) error

func (*STableSpec) InsertOrUpdate

func (t *STableSpec) InsertOrUpdate(dt interface{}) error

InsertOrUpdate perform a insert or update operation, the value of the record is string in dt MySQL: INSERT INTO ... ON DUPLICATE KEY UPDATE ... works only for the cases that all values of primary keys are determeted before insert

func (*STableSpec) InsertSqlPrep added in v1.1.0

func (t *STableSpec) InsertSqlPrep(data interface{}, update bool) (*InsertSqlResult, error)

func (*STableSpec) Instance

func (ts *STableSpec) Instance() *STable

Instance return an new table instance from an instance of STableSpec

func (*STableSpec) Name

func (ts *STableSpec) Name() string

Name implementation of STableSpec for ITableSpec

func (*STableSpec) PrepareUpdate added in v1.1.2

func (ts *STableSpec) PrepareUpdate(dt interface{}) (*SUpdateSession, error)

func (*STableSpec) PrimaryColumns

func (ts *STableSpec) PrimaryColumns() []IColumnSpec

PrimaryColumns implementation of STableSpec for ITableSpec

func (*STableSpec) Query

func (ts *STableSpec) Query(f ...IQueryField) *SQuery

Query of STableSpec generates a new query from a STableSpec instance

func (*STableSpec) Sync

func (ts *STableSpec) Sync() error

Sync executes the SQLs to synchronize the DB definion of s SQL database by applying the SQL statements generated by SyncSQL()

func (*STableSpec) SyncColumnIndexes added in v1.1.2

func (ts *STableSpec) SyncColumnIndexes() error

func (*STableSpec) SyncSQL

func (ts *STableSpec) SyncSQL() []string

SyncSQL returns SQL statements that make table in database consistent with TableSpec definitions by comparing table definition derived from TableSpec and that in database

func (*STableSpec) Update

func (ts *STableSpec) Update(dt interface{}, doUpdate func() error) (UpdateDiffs, error)

Update method of STableSpec updates a record of a table, dt is the point to the struct storing the record doUpdate provides method to update the field of the record

func (*STableSpec) UpdateBatch added in v1.1.2

func (ts *STableSpec) UpdateBatch(data map[string]interface{}, filter map[string]interface{}) error

func (*STableSpec) UpdateFields

func (ts *STableSpec) UpdateFields(dt interface{}, fields map[string]interface{}) error

UpdateFields update a record with the values provided by fields stringmap params dt: model struct, fileds: {struct-field-name-string: update-value}

type STripleCondition

type STripleCondition struct {
	STupleCondition
	// contains filtered or unexported fields
}

STripleCondition represents a base condition that composed of THREE fields

func NewTripleCondition

func NewTripleCondition(l IQueryField, r interface{}, r2 interface{}) STripleCondition

NewTripleCondition return an instance of STripleCondition

func (*STripleCondition) Variables

func (t *STripleCondition) Variables() []interface{}

Variables implementation of STripleCondition for ICondition

type STrueCondition

type STrueCondition struct{}

STrueCondition represents a dummy condition that is always true

func (*STrueCondition) Variables

func (t *STrueCondition) Variables() []interface{}

Variables implementation of STrueCondition for ICondition

func (*STrueCondition) WhereClause

func (t *STrueCondition) WhereClause() string

WhereClause implementation of STrueCondition for ICondition

type STupleCondition

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

STupleCondition is a base condition that composed of two fields

func NewTupleCondition

func NewTupleCondition(l IQueryField, r interface{}) STupleCondition

NewTupleCondition returns an instance of tuple condition

func (*STupleCondition) GetLeft added in v1.1.2

func (t *STupleCondition) GetLeft() IQueryField

func (*STupleCondition) GetRight added in v1.1.2

func (t *STupleCondition) GetRight() interface{}

func (*STupleCondition) Variables

func (t *STupleCondition) Variables() []interface{}

Variables implementation of STupleCondition for ICondition

type SUnion

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

SUnion is the struct to store state of a Union query, which implementation the interface of IQuerySource

func Union

func Union(query ...IQuery) *SUnion

Union method returns union query of several queries. Require the fields of all queries should exactly match deprecated

func UnionAllWithError added in v1.1.0

func UnionAllWithError(query ...IQuery) (*SUnion, error)

func UnionWithError

func UnionWithError(query ...IQuery) (*SUnion, error)

UnionWithError constructs union query of several Queries Require the fields of all queries should exactly match

func (*SUnion) Alias

func (uq *SUnion) Alias() string

Alias implementation of SUnion for IQuerySource

func (*SUnion) Expression

func (uq *SUnion) Expression() string

Expression implementation of SUnion for IQuerySource

func (*SUnion) Field

func (uq *SUnion) Field(name string, alias ...string) IQueryField

Field implementation of SUnion for IQuerySource

func (*SUnion) Fields

func (uq *SUnion) Fields() []IQueryField

Fields implementation of SUnion for IQuerySource

func (*SUnion) Query

func (uq *SUnion) Query(f ...IQueryField) *SQuery

Query of SUnion returns a SQuery of a union query

func (*SUnion) Variables

func (uq *SUnion) Variables() []interface{}

Variables implementation of SUnion for IQuerySource

type SUnionQueryField

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

SUnionQueryField represents a field of a union query

func (*SUnionQueryField) Expression

func (sqf *SUnionQueryField) Expression() string

Expression implementation of SUnionQueryField for IQueryField

func (*SUnionQueryField) Label

func (sqf *SUnionQueryField) Label(label string) IQueryField

Label implementation of SUnionQueryField for IQueryField

func (*SUnionQueryField) Name

func (sqf *SUnionQueryField) Name() string

Name implementation of SUnionQueryField for IQueryField

func (*SUnionQueryField) Reference

func (sqf *SUnionQueryField) Reference() string

Reference implementation of SUnionQueryField for IQueryField

func (*SUnionQueryField) Variables

func (sqf *SUnionQueryField) Variables() []interface{}

Variables implementation of SUnionQueryField for IQueryField

type SUpdateColumnSpec added in v1.1.0

type SUpdateColumnSpec struct {
	OldCol IColumnSpec
	NewCol IColumnSpec
}

type SUpdateDiff

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

SUpdateDiff is a struct to store the differences for an update of a column

func (*SUpdateDiff) String

func (ud *SUpdateDiff) String() string

String of SUpdateDiff returns the string representation of a SUpdateDiff

type SUpdateSQLResult added in v1.1.2

type SUpdateSQLResult struct {
	Sql  string
	Vars []interface{}
	// contains filtered or unexported fields
}

type SUpdateSession

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

SUpdateSession is a struct to store the state of a update session

func (*SUpdateSession) SaveUpdateSql added in v1.1.2

func (us *SUpdateSession) SaveUpdateSql(dt interface{}) (*SUpdateSQLResult, error)

type TColumnNames added in v1.1.0

type TColumnNames []string

func (TColumnNames) Len added in v1.1.0

func (cols TColumnNames) Len() int

func (TColumnNames) Less added in v1.1.0

func (cols TColumnNames) Less(i, j int) bool

func (TColumnNames) Swap added in v1.1.0

func (cols TColumnNames) Swap(i, j int)

type UpdateDiffs

type UpdateDiffs map[string]SUpdateDiff

UpdateDiffs is a map of SUpdateDiff whose key is the column name

func (UpdateDiffs) String

func (uds UpdateDiffs) String() string

String of UpdateDiffs returns the string representation of UpdateDiffs

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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