Gorose, most like Laravel's eloquent's Go database Operation Orm, the coquettish chain call, let you deep into extricate oneself

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Gorose (Go ORM), a small and powerful Go language database operation Orm, inspired by the Laravel database operation Orm, that is, eloquent, PHP, Python, ruby developers, will like this ORM operation mode, Mainly chain-operated more coquettish

    • 中文版 Document
    • Chinese documents

Installation

    • Installing Gorose
go get github.com/gohouse/gorose
    • To install the Function toolkit used in Gorose
go get github.com/gohouse/utils

Configuration and examples

    • Multiple Database connection Configurations
import "github.com/gohouse/gorose"var dbConfig = map[string]map[string]string {    "mysql": {        "host":     "localhost",        "username": "root",        "password": "",        "port":     "3306",        "database": "test",        "charset":  "utf8",        "protocol": "tcp",    },    "mysql_dev": {        "host":     "localhost",        "username": "root",        "password": "",        "port":     "3306",        "database": "gorose",        "charset":  "utf8",        "protocol": "tcp",    },}gorose.Open(dbConfig, "mysql")var db gorose.Databasefunc main() {    res := db.Table("users").First()        fmt.Println(res)}
    • Simple but database configuration
gorose.Open(map[string]string {                "host":     "localhost",                "username": "root",                "password": "",                "port":     "3306",                "database": "test",                "charset":  "utf8",                "protocol": "tcp",            })

Usage examples

Inquire

Native SQL statement Query

db.Query("select * from user where id = 1")

Chained call Query

db.Table("user").    Field("id, name").  // field    Where("id",">",1).  // simple where    Where(map[string]interface{}{"name":"fizzday", "age":18}).  // where object    Where([]map[string]interface{}{{"website", "like", "fizz"}, {"job", "it"}}).    // multi where    Where("head = 3 or rate is not null").  // where string    OrWhere("cash", "1000000"). // or where ...    OrWhere("score", "between", []string{50, 80}).  // between    OrWhere("role", "not in", []string{"admin", "read"}).   // in     Group("job").   // group    Order("age asc").   // order     Limit(10).  // limit    Offset(1).  // offset    Get()   // fetch multi rows

Get SQL Results:

select id,name from user     where (id>1)     and (name='fizzday' and age='18')     and ((website like '%fizz%') and (job='it'))    and (head =3 or rate is not null)    or (cash = '100000')     or (score between '50' and '100')     or (role not in ('admin', 'read'))    group by job     order by age asc     limit 10 offset 1

More chained query examples

    • Get User Table Object
User := db.Table("user")
    • Query A
User.First()// 或者db.Fisrt()

Parse SQL Result:select * from user limit 1

    • Count statistics
User.Count("*")// 或(下同) db.Count("*")

The final SQL executed is:select count(*) as count from user

    • Max
User.Max("age")

The final SQL executed is:select max(age) as max from user

    • Min
User.Min("age")

The final SQL executed is:select min(age) as min from user

    • Avg
User.Avg("age")

The final SQL executed is:select avg(age) as avg from user

    • Distinct
User.Fields("id, name").Distinct()

The final SQL executed is:select distinct id,name from user

nested where queries (where nested)

db.Table("user").Where("id", ">", 1).Where(func() {        db.Where("name", "fizz").OrWhere(func() {            db.Where("name", "fizz2").Where(func() {                db.Where("name", "fizz3").OrWhere("website", "fizzday")            })        })    }).Where("job", "it").First()

The final SQL executed is:

SELECT  * FROM user      WHERE  id > '1'         and ( name = 'fizz'             or ( name = 'fizz2'                 and ( name = 'fizz3' or website like '%fizzday%')                )            )     and job = 'it' LIMIT 1

Transaction

    • Standard usage
db.Begin()res := db.Table("user").Where("id", 1).Data(map[string]interface{}{"age":18}).Update()if (res == 0) {    db.Rollback()}res2 := db.Table("user").Data(map[string]interface{}{"age":18}).Insert()if (res2 == 0) {    db.Rollback()}db.Commit()
    • Simple usage, implemented with closures, automatically starts transactions, rolls back or commits transactions
db.Transaction(func() {    db.Execute("update area set job='sadf' where id=14")    db.Table("area").Data(map[string]interface{}{"names": "fizz3", "age": 3}).Insert()    db.Table("area").Data(map[string]interface{}{"names": "fizz3", "age": 3}).Where("id",10).Update()})

Adding and removing changes operation

Native SQL string

db.Execute("update user set job='it2' where id=3")

Chained calls

db.Table("user").    Data(map[string]interface{}{"age":17, "job":"it3"}).    Where("id", 1).    OrWhere("age",">",30).    Update()

The final SQL executed is:update user set age=17, job='ite3' where (id=1) or (age>30)

More use of additions and deletions

    • Insert
User.Data(map[string]interface{}{"age":17, "job":"it3"}).Insert()User.Data([]map[string]interface{}{{"age":17, "job":"it3"},{"age":17, "job":"it4"}).Insert()

The final SQL executed is:

insert into user (age, job) values (17, 'it3')insert into user (age, job) values (17, 'it3') (17, 'it4')
    • Delete
User.Where("id", 5).Delete()

The final SQL executed is:delete from user where id=5

Switch database connections

// 连接最开始配置的第二个链接(mysql_dev是key)db.Connect("mysql_dev").Table().First()// 或者直接输入连接配置db.Connect(map[string]string {                "host":     "localhost",                "username": "root",                "password": "",                "port":     "3306",                "database": "test",                "charset":  "utf8",                "protocol": "tcp",            }).Table().First()

Click to view the latest update news

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.