sqlchemy

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 13, 2022 License: Apache-2.0 Imports: 21 Imported by: 0

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 ONLY
  • Support select, insert, update and insert or update

Quick Examples

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

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 (
	// 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_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)
	TAG_WIDTH = "width"
	// TAG_TEXT_LENGTH is a field tag that indicates the length of a text column
	TAG_TEXT_LENGTH = "length"
	// TAG_CHARSET is a field tag that indicates the charset of a text column
	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")
)

Variables

View Source
var (
	// INT_WIDTH_DEFAULT records the default width of integer type
	INT_WIDTH_DEFAULT = map[string]int{
		"TINYINT":  4,
		"SMALLINT": 6,
		"INT":      11,
		"BIGINT":   20,
	}
	// UNSIGNED_INT_WIDTH_DEFAULT records the default width of unsigned integer type
	UNSIGNED_INT_WIDTH_DEFAULT = map[string]int{
		"TINYINT":  3,
		"SMALLINT": 5,
		"INT":      10,
		"BIGINT":   20,
	}
)
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 Exec

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

Exec execute a raw SQL query

func GetDB

func GetDB() *sql.DB

GetDB get DB instance

func GetTables

func GetTables() []string

GetTables get all tables' name in database

func SetDB

func SetDB(db *sql.DB)

SetDB sets global DB instance

Types

type CompoundColumn

type CompoundColumn struct {
	STextColumn
}

CompoundColumn represents a column of compound tye, e.g. a JSON, an Array, or a struct

func NewCompoundColumn

func NewCompoundColumn(name string, tagmap map[string]string, isPointer bool) CompoundColumn

NewCompoundColumn returns an instance of CompoundColumn

func (*CompoundColumn) ConvertFromValue

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

ConvertFromValue implementation of CompoundColumn for IColumnSpec

func (*CompoundColumn) DefinitionString

func (c *CompoundColumn) DefinitionString() string

DefinitionString implementation of CompoundColumn for IColumnSpec

func (*CompoundColumn) IsZero

func (c *CompoundColumn) IsZero(val interface{}) bool

IsZero implementation of CompoundColumn for IColumnSpec

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

	// 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) string

	// 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)
}

IColumnSpec is an interface that represents a column of a table

type ICondition

type ICondition interface {
	WhereClause() string
	Variables() []interface{}
}

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 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 {
	// queryString
	String(fields ...IQueryField) string

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

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

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

	// reference to a field by name
	Field(name string) IQueryField
}

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{}
}

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 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 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 INET_ATON

func INET_ATON(field IQueryField) IQueryField

INET_ATON represents a SQL function INET_ATON

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

func TimestampAdd

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

TimestampAdd represents a SQL function TimestampAdd

type IQuerySource

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

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

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

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

	// return all the fields that this source provides
	Fields() []IQueryField
}

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

	// 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 forces synchronize the data definition and model definition of the table
	SyncSQL() []string

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

ITableSpec is the interface represents a table

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

func (c *SBaseColumn) ColType() string

ColType implementation of SBaseColumn for IColumnSpec

func (*SBaseColumn) ConvertFromString

func (c *SBaseColumn) ConvertFromString(str string) string

ConvertFromString 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) IsAscii

func (c *SBaseColumn) IsAscii() bool

IsAscii implementation of SBaseColumn for IColumnSpec

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

func (c *SBaseColumn) Name() string

Name implementation of SBaseColumn for IColumnSpec

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

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

Tags implementation of SBaseColumn 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 SBooleanColumn

type SBooleanColumn struct {
	SBaseWidthColumn
}

SBooleanColumn represents a boolean type column, which is a int(1) for mysql, with value of true or false

func NewBooleanColumn

func NewBooleanColumn(name string, tagmap map[string]string, isPointer bool) SBooleanColumn

NewBooleanColumn return an instance of SBooleanColumn

func (*SBooleanColumn) ConvertFromString

func (c *SBooleanColumn) ConvertFromString(str string) string

ConvertFromString implementation of SBooleanColumn for IColumnSpec

func (*SBooleanColumn) DefinitionString

func (c *SBooleanColumn) DefinitionString() string

DefinitionString implementation of SBooleanColumn for IColumnSpec

func (*SBooleanColumn) IsZero

func (c *SBooleanColumn) IsZero(val interface{}) bool

IsZero implementation of SBooleanColumn for IColumnSpec

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 SDateTimeColumn

type SDateTimeColumn struct {
	STimeTypeColumn

	// Is this column a 'created_at' field, whichi records the time of create this record
	IsCreatedAt bool

	// Is this column a 'updated_at' field, whichi records the time when this record was updated
	IsUpdatedAt bool
}

SDateTimeColumn represents a DateTime type of column

func NewDateTimeColumn

func NewDateTimeColumn(name string, tagmap map[string]string, isPointer bool) SDateTimeColumn

NewDateTimeColumn returns an instance of DateTime column

type SDecimalColumn

type SDecimalColumn struct {
	SBaseWidthColumn
	Precision int
}

SDecimalColumn represents a DECIMAL type of column, i.e. a float with fixed width of digits

func NewDecimalColumn

func NewDecimalColumn(name string, tagmap map[string]string, isPointer bool) SDecimalColumn

NewDecimalColumn returns an instance of SDecimalColumn

func (*SDecimalColumn) ColType

func (c *SDecimalColumn) ColType() string

ColType implementation of SDecimalColumn for IColumnSpec

func (*SDecimalColumn) DefinitionString

func (c *SDecimalColumn) DefinitionString() string

DefinitionString implementation of SDecimalColumn for IColumnSpec

func (*SDecimalColumn) IsNumeric

func (c *SDecimalColumn) IsNumeric() bool

IsNumeric implementation of SDecimalColumn for IColumnSpec

func (*SDecimalColumn) IsZero

func (c *SDecimalColumn) IsZero(val interface{}) bool

IsZero implementation of SDecimalColumn for IColumnSpec

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 SFloatColumn

type SFloatColumn struct {
	SBaseColumn
}

SFloatColumn represents a float type column, e.g. float32 or float64

func NewFloatColumn

func NewFloatColumn(name string, sqlType string, tagmap map[string]string, isPointer bool) SFloatColumn

NewFloatColumn returns an instance of SFloatColumn

func (*SFloatColumn) DefinitionString

func (c *SFloatColumn) DefinitionString() string

DefinitionString implementation of SFloatColumn for IColumnSpec

func (*SFloatColumn) IsNumeric

func (c *SFloatColumn) IsNumeric() bool

IsNumeric implementation of SFloatColumn for IColumnSpec

func (*SFloatColumn) IsZero

func (c *SFloatColumn) IsZero(val interface{}) bool

IsZero implementation of SFloatColumn for IColumnSpec

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 SIntegerColumn

type SIntegerColumn struct {
	SBaseWidthColumn

	// Is this column an autoincrement colmn
	IsAutoIncrement bool

	// Is this column is a version column for this records
	IsAutoVersion bool

	// Is this column a unsigned integer?
	IsUnsigned bool

	// If this column is an autoincrement column, AutoIncrementOffset records the initial offset
	AutoIncrementOffset int64
}

SIntegerColumn represents an integer type of column, with value of integer

func NewIntegerColumn

func NewIntegerColumn(name string, sqltype string, unsigned bool, tagmap map[string]string, isPointer bool) SIntegerColumn

NewIntegerColumn return an instance of SIntegerColumn

func (*SIntegerColumn) ColType

func (c *SIntegerColumn) ColType() string

ColType implementation of SIntegerColumn for IColumnSpec

func (*SIntegerColumn) DefinitionString

func (c *SIntegerColumn) DefinitionString() string

DefinitionString implementation of SIntegerColumn for IColumnSpec

func (*SIntegerColumn) ExtraDefs

func (c *SIntegerColumn) ExtraDefs() string

ExtraDefs implementation of SIntegerColumn for IColumnSpec

func (*SIntegerColumn) IsNumeric

func (c *SIntegerColumn) IsNumeric() bool

IsNumeric implementation of SIntegerColumn for IColumnSpec

func (*SIntegerColumn) IsZero

func (c *SIntegerColumn) IsZero(val interface{}) bool

IsZero implementation of SIntegerColumn for IColumnSpec

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

func (tq *SQuery) Count() int

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

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

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

SStringField is a query field of a string constant

func NewStringField

func NewStringField(name 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 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 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 (*STableSpec) AddIndex

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

AddIndex adds a SQL index over multiple columns for a Table param unique: indicates a unique index cols: name of columns

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

func (ts *STableSpec) CreateSQL() string

CreateSQL returns the SQL for creating this table

func (*STableSpec) DataType

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

DataType implementation of STableSpec for ITableSpec

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

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

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

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

type STextColumn struct {
	SBaseWidthColumn
	Charset string
}

STextColumn represents a text type of column

func NewTextColumn

func NewTextColumn(name string, tagmap map[string]string, isPointer bool) STextColumn

NewTextColumn return an instance of STextColumn

func (*STextColumn) ColType

func (c *STextColumn) ColType() string

ColType implementation of STextColumn for IColumnSpec

func (*STextColumn) DefinitionString

func (c *STextColumn) DefinitionString() string

DefinitionString implementation of STextColumn for IColumnSpec

func (*STextColumn) IsAscii

func (c *STextColumn) IsAscii() bool

IsAscii implementation of STextColumn for IColumnSpec

func (*STextColumn) IsSearchable

func (c *STextColumn) IsSearchable() bool

IsSearchable implementation of STextColumn for IColumnSpec

func (*STextColumn) IsSupportDefault

func (c *STextColumn) IsSupportDefault() bool

IsSupportDefault implementation of STextColumn for IColumnSpec

func (*STextColumn) IsText

func (c *STextColumn) IsText() bool

IsText implementation of STextColumn for IColumnSpec

func (*STextColumn) IsZero

func (c *STextColumn) IsZero(val interface{}) bool

IsZero implementation of STextColumn for IColumnSpec

type STimeTypeColumn

type STimeTypeColumn struct {
	SBaseColumn
}

STimeTypeColumn represents a Detetime type of column, e.g. DateTime

func NewTimeTypeColumn

func NewTimeTypeColumn(name string, typeStr string, tagmap map[string]string, isPointer bool) STimeTypeColumn

NewTimeTypeColumn return an instance of STimeTypeColumn

func (*STimeTypeColumn) DefinitionString

func (c *STimeTypeColumn) DefinitionString() string

DefinitionString implementation of STimeTypeColumn for IColumnSpec

func (*STimeTypeColumn) IsText

func (c *STimeTypeColumn) IsText() bool

IsText implementation of STimeTypeColumn for IColumnSpec

func (*STimeTypeColumn) IsZero

func (c *STimeTypeColumn) IsZero(val interface{}) bool

IsZero implementation of STimeTypeColumn for IColumnSpec

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 STristateColumn

type STristateColumn struct {
	SBaseWidthColumn
}

STristateColumn represents a tristate type column, with value of true, false or none

func NewTristateColumn

func NewTristateColumn(name string, tagmap map[string]string, isPointer bool) STristateColumn

NewTristateColumn return an instance of STristateColumn

func (*STristateColumn) ConvertFromString

func (c *STristateColumn) ConvertFromString(str string) string

ConvertFromString implementation of STristateColumn for IColumnSpec

func (*STristateColumn) ConvertFromValue

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

ConvertFromValue implementation of STristateColumn for IColumnSpec

func (*STristateColumn) DefinitionString

func (c *STristateColumn) DefinitionString() string

DefinitionString implementation of STristateColumn for IColumnSpec

func (*STristateColumn) IsZero

func (c *STristateColumn) IsZero(val interface{}) bool

IsZero implementation of STristateColumn for IColumnSpec

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

func (uq *SUnion) Limit(limit int) *SUnion

Limit adds limit to a union query

func (*SUnion) Offset

func (uq *SUnion) Offset(offset int) *SUnion

Offset adds offset to a union query

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 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 SUpdateSession

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

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

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