Categoryyunion.io/x/sqlchemy
modulepackage
1.1.2
Repository: https://github.com/yunionio/sqlchemy.git
Documentation: pkg.go.dev

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

# Packages

No description provided by the author
No description provided by the author
No description provided by the author

# Functions

No description provided by the author
AND method that combines many conditions with AND operator.
AND_Val represents a SQL function that does binary & operation on a field.
Between SQL operator.
CAST represents a SQL function cast types.
CloseDB close DB connection.
CONCAT represents a SQL function CONCAT.
Contains method is a shortcut of LIKE method, Contains represents the condtion that a field contains a substring.
ContainsAny is a OR combination of serveral Contains conditions.
COUNT represents the SQL function COUNT.
DATE_FORMAT represents a SQL function DATE_FORMAT.
No description provided by the author
No description provided by the author
DISTINCT represents the SQL function DISTINCT.
No description provided by the author
DoQuery returns a SQuery instance that query specified fields from a query source.
Endswith method is a shortcut of LIKE condition, Endswith represents that condition that field endswith a substring.
Equals method represents equal of two fields.
Exec execute a raw SQL query for the default db instance Deprecated.
No description provided by the author
GE method represetns operation of Greate Than Or Equal to, e.g.
GetDB get DB instance Deprecated.
GetDBWithName returns the db instance with given name.
GetDefaultDB get the DB instance set by default.
No description provided by the author
GetTables get all tables' name in default database Deprecated.
GROUP_CONCAT represents the SQL function GROUP_CONCAT.
GROUP_CONCAT2 represents the SQL function GROUP_CONCAT.
GT method represents operation of Great Than, e.g.
In SQL operator.
INET_ATON represents a SQL function INET_ATON.
IsEmpty method that justifies where a text field is empty, e.g.
IsFalse method justifies a boolean is false.
IsNotEmpty method justifies a field is not empty.
IsNotNull methods that justifies a field is not null.
IsNull methods that justifies a field is null.
IsNullOrEmpty is the ethod justifies a field is null or empty, e.g.
IsTrue method that justifies a field is true, e.g.
LE method represents operation of Less Than Or Equal to, e.q.
LENGTH represents a SQL function of LENGTH.
Like SQL operator.
LOWER represents the SQL function SUM.
LT method represents operation of Less Than, e.g.
MAX represents the SQL function MAX.
MIN represents the SQL function MIN.
No description provided by the author
NewBaseColumn returns an instance of SBaseColumn.
NewBaseWidthColumn return an instance of SBaseWidthColumn.
NewCase creates a case..
NewConstField returns an instance of SConstField.
NewFunction creates a field with SQL function for example: SUM(count) as total.
NewFunctionField returns an instance of query field by calling a SQL embedded function.
NewRawQuery returns an instance of SQuery with raw SQL query.
NewSingleCondition returns an instance of SSingleCondition.
NewStringField returns an instance of SStringField.
No description provided by the author
No description provided by the author
NewTableInstance return an new table instance from an ITableSpec.
NewTableSpecFromStruct generates STableSpec based on the information of a struct model.
No description provided by the author
NewTripleCondition return an instance of STripleCondition.
NewTupleCondition returns an instance of tuple condition.
NoEarlierThan justifies a field is no earlier than current time.
NoLaterThan method justifies a DATETIME field is before current time.
NOT method that makes negative operator on a condition.
NotEquals method represents not equal of two fields.
NotIn SQL operator.
OR method that combines many conditions with OR operator.
OR_Val represents a SQL function that does binary | operation on a field.
Regexp SQL operator.
RegisterBackend registers a backend.
REPLACE represents the SQL function REPLACE.
No description provided by the author
Deprecated SetDB sets global DB instance.
SetDBWithName sets a DB instance with given name param: name DBName.
SetDefaultDB save default global DB instance.
No description provided by the author
Startswith method is a shortcut of LIKE method, Startswith represents the condition that field starts with a substring.
No description provided by the author
SubStr represents a SQL function SUBSTR Deprecated.
SUBSTR represents a SQL function SUBSTR.
SUM represents the SQL function SUM.
TimestampAdd represents a SQL function TimestampAdd.
TIMESTAMPADD represents a SQL function TimestampAdd.
Union method returns union query of several queries.
No description provided by the author
UnionWithError constructs union query of several Queries Require the fields of all queries should exactly match.
UPPER represents the SQL function SUM.
No description provided by the author

# Constants

Clickhouse is the backend name of Clickhouse.
DefaultDB is the name for the default database instance.
ErrDuplicateEntry is an Error constant: duplicate entry.
ErrEmptyPrimaryKey is an Error constant: no primary key.
ErrEmptyQuery is an Error constant: empty query.
ErrNeedsArray is an Error constant: input should be an Array or Slice.
ErrNeedsPointer is an Error constant: input should be a pointer.
ErrNoDataToUpdate is an Error constant: no data to update.
ErrNotSupported is an Error constant: method not supported yet.
ErrReadOnly is an Error constant: database is read-only.
ErrTableNotExists is an Error constant: table not exists.
ErrUnexpectRowCount is an Error constant: the number of rows impacted by modification unexpected.
ErrUnionDatabasesNotMatch is an Error constant: backend database of union queries not match.
ErrUnionFieldsNotMatch is an Error constant: fields of union queries not match.
No description provided by the author
INNERJOIN represents innerjoin.
LEFTJOIN represents left join.
MySQL is the backend name for MySQL/MariaDB.
RIGHTJOIN represents right-join.
SQL_OP_AND represents AND operator.
SQL_OP_BETWEEN represents BETWEEN operator.
SQL_OP_EQUAL represents EQUAL operator.
SQL_OP_GE represents >= operator.
SQL_OP_GT represents > operator.
SQL_OP_IN represents IN operator.
SQL_OP_LE represents <= operator.
SQL_OP_LIKE represents LIKE operator.
SQL_OP_LT represents < operator.
SQL_OP_NOT represents NOT operator.
SQL_OP_NOTEQUAL represents NOT EQUAL operator.
SQL_OP_NOTIN represents NOT IN operator.
SQL_OP_OR represents OR operator.
SQL_OP_REGEXP represents REGEXP operator.
SQL_ORDER_ASC represents Ascending order.
SQL_ORDER_DESC represents Descending order.
SQLiteBackend is the backend name of Sqlite3.
TAG_ALLOW_ZERO is a field tag that indicates whether the column allow zero value.
TAG_AUTOINCREMENT is a field tag that indicates the integer column is auto_increment, the column should must be primary.
TAG_AUTOVERSION is a field tag that indicates the integer column is used to records the update version of a record.
TAG_CHARSET is a field tag that indicates the charset of a text column Supported by: mysql.
TAG_CREATE_TIMESTAMP is a field tag that indicates the datetime column is the created_at timestamp.
TAG_DEFAULT is a field tag that indicates the default value of a column.
TAG_IGNORE is a field tag that indicates the field is ignored, not represents a table column.
TAG_INDEX is a field tag that indicates the column is a indexable column.
TAG_NAME is a field tag that indicates the column name of this field.
TAG_NULLABLE is a field tag that indicates the column is nullable.
TAG_PRECISION is a field tag that indicates the precision of a float column.
TAG_PRIMARY is a field tag that indicates the column is part of primary key.
TAG_TEXT_LENGTH is a field tag that indicates the length of a text column Supported by: mysql.
TAG_UNIQUE is a field tag that indicates the column value is unique.
TAG_UPDATE_TIMESTAMP is a field tag that indicates the datetime column is the updated_at timestamp.
TAG_WIDTH is a field tag that indicates the width of the column, like VARCHAR(15) Supported by: mysql.

# Variables

DEBUG_SQLCHEMY is a global constant that indicates turn on SQL debug.

# Structs

No description provided by the author
SAndConditions represents the AND condition, which is a SCompoundConditions.
No description provided by the author
SBaseColumn is the base structure represents a column.
No description provided by the author
SBaseWidthColumn represents a type of column that with width attribute, such as VARCHAR(20), INT(10).
SBetweenCondition represents BETWEEN operator, e.g.
SCaseFunction represents function of case ..
SCompoundConditions is a Compound condition represents AND or OR boolean operation Compound condition also follows the ICondition interface.
SConstField is a query field of a constant.
SDatabase represents a SQL database.
SEqualsCondition represents equal operation between two fields.
SFalseCondition is a dummy condition that is always false.
SFunctionFieldBase is a query field that is the result of a SQL embedded function, e.g.
SGreatEqualCondition represents >= operation on two fields.
SGreatThanCondition represetns > operation on two fields.
SInCondition represents a IN operation in SQL query.
SIsEmptyCondition is a condition representing the empty status of a field.
SIsFalseCondition represents a boolean is false.
SIsNotEmptyCondition represents a condition that represents a field is not empty.
SIsNotNullCondition is a condition represents a comparison with not null, e.g.
SIsNullCondition is a condition representing a comparison with null, e.g.
SIsNullOrEmptyCondition is a condition that justifies a field is null or empty.
SIsTrueCondition represents a boolean field (TINYINT) is true, e.g.
SLessEqualCondition represents <= operation on two fields.
SLessThanCondition represents < operation on two fields.
SLikeCondition represents LIKE operation in a SQL query.
SNoEarlierThanCondition compares a field with current time and ensure the field is no earlier than NOW, e.g.
SNoLaterThanCondition coompares a DATETIME field with current time and ensure the field is no later than now, e.g.
SNotCondition represents the NOT condition, which is a boolean operator.
SNotEqualsCondition is the opposite of equal condition.
SOrConditions represents the OR condition, which is a SCompoundConditions.
SQuery is a data structure represents a SQL query in the form of SELECT ..
SRawQueryField is a struct represents a field of a raw SQL query a raw query is a query that not follow standard SELECT ..
SRegexpConition represents REGEXP operation in a SQL query.
SSingleCondition represents a kind of condition that composed of one query field.
No description provided by the author
SStringField is a query field of a string constant.
SSubQuery represents a subquery.
SSubQueryField represents a field of subquery, which implements IQueryField.
STable is an instance of table for query, system will automatically give a alias to this table.
No description provided by the author
No description provided by the author
STableField represents a field in a table, implements IQueryField.
No description provided by the author
STableSpec defines the table specification, which implements ITableSpec.
STripleCondition represents a base condition that composed of THREE fields.
STrueCondition represents a dummy condition that is always true.
STupleCondition is a base condition that composed of two fields.
SUnion is the struct to store state of a Union query, which implementation the interface of IQuerySource.
SUnionQueryField represents a field of a union query.
No description provided by the author
SUpdateDiff is a struct to store the differences for an update of a column.
SUpdateSession is a struct to store the state of a update session.
No description provided by the author

# Interfaces

IBackend is the interface for all kinds of sql backends, e.g.
IColumnSpec is an interface that represents a column of a table.
ICondition is the interface representing a condition for SQL query e.g.
IFunction is the interface for a SQL embedded function, such as MIN, MAX, NOW, etc.
IQuery is an interface that reprsents a SQL query, e.g.
IQueryField is an interface that represents a select field in a SQL query.
IQuerySource is an interface that represents a data source of a SQL query.
IRowScanner is an interface for sql data fetching.
ITableSpec is the interface represents a table.

# Type aliases

No description provided by the author
DBName is a type of string for name of database.
QueryJoinType is the Join type of SQL query, namely, innerjoin, leftjoin and rightjoin.
QueryOrderType indicates the query order type, either ASC or DESC.
No description provided by the author
UpdateDiffs is a map of SUpdateDiff whose key is the column name.