【转】数据库无关的GO语言ORM - hood

简介: 项目地址:https://github.com/eaigner/hood这是一个极具美感的ORM库。特性链式的api事务支持迁移和名字空间生成模型变量模型时间数据库方言接口没有含糊的字段干净可测试的代码打开数据库如果方言已经注册可以直接打开数据库hd, err := hood.

项目地址:https://github.com/eaigner/hood

这是一个极具美感的ORM库。

特性

  • 链式的api
  • 事务支持
  • 迁移和名字空间生成
  • 模型变量
  • 模型时间
  • 数据库方言接口
  • 没有含糊的字段
  • 干净可测试的代码

打开数据库

如果方言已经注册可以直接打开数据库

hd, err := hood.Open("postgres", "user=<username> dbname=<database>")

你也可以打开数据库时候指定方言

    
hd := hood.New(db, NewPostgres())

Schemas

你可以这样声明

type Person struct {
  
// Auto-incrementing int field 'id'
  Id hood.Id
 
  
// Custom primary key field 'first_name', with presence validation
  FirstName string `sql:"pk" validate:"presence"`
 
  
// string field 'last_name' with size 128, NOT NULL
  LastName string `sql:"size(128),notnull"`
 
  
// string field 'tag' with size 255, default value 'customer'
  Tag string `sql:"size(255),default('customer')"`
 
  
// You can also combine tags, default value 'orange'
  CombinedTags string `sql:"size(128),default('orange')"`
  Birthday     time.Time   
// timestamp field 'birthday'
  Data         []byte      
// data field 'data'
  IsAdmin      bool        
// boolean field 'is_admin'
  Notes        string      
// text field 'notes'
 
  
// You can alternatively define a var char as a string field by setting a size
  Nick  string  `sql:"size(128)"`
 
  
// Validates number range
  Balance int `validate:"range(10:20)"`
 
  
// These fields are auto updated on save
  Created hood.Created
  Updated hood.Updated
 
  
// ... and other built in types (int, uint, float...)
}
 
// Indexes are defined via the Indexed interface to avoid
// polluting the table fields.
 
func (table *Person) Indexes(indexes *hood.Indexes) {
  indexes.Add("tag_index", "tag")
// params: indexName, unique, columns...
  indexes.AddUnique("name_index", "first_name", "last_name")
}

数据迁移

你要先安装hood tool ,然后运行

go get github.com/eaigner/hood
cd $GOPATH/src/github.com/eaigner/hood
./install.sh<

例子

下面是一个使用例子

package main
 
import (
    "hood"
)
 
func main() {
    
// Open a DB connection, use New() alternatively for unregistered dialects
    hd, err := hood.Open("postgres", "user=hood dbname=hood_test sslmode=disable")
    if err != nil {
        panic(err)
    }
 
    
// Create a table
    type Fruit struct {
        Id    hood.Id
        Name  string `validate:"presence"`
        Color string
    }
 
    err = hd.CreateTable(&Fruit{})
    if err != nil {
        panic(err)
    }
 
    fruits := []Fruit{
        Fruit{Name: "banana", Color: "yellow"},
        Fruit{Name: "apple", Color: "red"},
        Fruit{Name: "grapefruit", Color: "yellow"},
        Fruit{Name: "grape", Color: "green"},
        Fruit{Name: "pear", Color: "yellow"},
    }
 
    
// Start a transaction
    tx := hd.Begin()
 
    ids, err := tx.SaveAll(&fruits)
    if err != nil {
        panic(err)
    }
 
    fmt.Println("inserted ids:", ids)
// [1 2 3 4 5]
 
    
// Commit changes
    err = tx.Commit()
    if err != nil {
        panic(err)
    }
 
    
// Ids are automatically updated
    if fruits[0].Id != 1 || fruits[1].Id != 2 || fruits[2].Id != 3 {
        panic("id not set")
    }
 
    
// If an id is already set, a call to save will result in an update
    fruits[0].Color = "green"
 
    ids, err = hd.SaveAll(&fruits)
    if err != nil {
        panic(err)
    }
 
    fmt.Println("updated ids:", ids)
// [1 2 3 4 5]
 
    if fruits[0].Id != 1 || fruits[1].Id != 2 || fruits[2].Id != 3 {
        panic("id not set")
    }
 
    
// Let's try to save a row that does not satisfy the required validations
    _, err = hd.Save(&Fruit{})
    if err == nil || err.Error() != "value not set" {
        panic("does not satisfy validations, should not save")
    }
 
    
// Find
    
//
    
// The markers are db agnostic, so you can always use '?'
    
// e.g. in Postgres they are replaced with $1, $2, ...
    var results []Fruit
    err = hd.Where("color", "=", "green").OrderBy("name").Limit(1).Find(&results)
    if err != nil {
        panic(err)
    }
 
    fmt.Println("results:", results)
// [{1 banana green}]
 
    
// Delete
    ids, err = hd.DeleteAll(&results)
    if err != nil {
        panic(err)
    }
 
    fmt.Println("deleted ids:", ids)
// [1]
 
    results = nil
    err = hd.Find(&results)
    if err != nil {
        panic(err)
    }
 
    fmt.Println("results:", results)
// [{2 apple red} {3 grapefruit yellow} {4 grape green} {5 pear yellow}]
 
    
// Drop
    hd.DropTable(&Fruit{})
}
目录
相关文章
|
20小时前
|
Go 开发者
探索Go语言的并发编程模型
通过实例详细介绍了Go语言中的并发编程模型,包括goroutine、channel的基本使用和最佳实践。深入剖析如何利用Go的并发特性提高程序性能和效率,适用于初学者和有一定经验的开发者。
|
2天前
|
Go Python
go语言调用python脚本
go语言调用python脚本
6 0
|
5天前
|
负载均衡 算法 Java
【面试宝藏】Go语言运行时机制面试题
探索Go语言运行时,了解goroutine的轻量级并发及GMP模型,包括G(协程)、M(线程)和P(处理器)。GMP调度涉及Work Stealing和Hand Off机制,实现负载均衡。文章还讨论了从协作到基于信号的抢占式调度,以及GC的三色标记算法和写屏障技术。理解这些概念有助于优化Go程序性能。
23 4
|
5天前
|
JSON Go 数据格式
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】(4)
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】
|
5天前
|
Java 编译器 Go
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】(3)
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】
|
5天前
|
存储 安全 Go
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】(2)
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】
|
5天前
|
Java Go 索引
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】(1)
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】
|
6天前
|
安全 Go 开发者
Go语言中的空值与零值有什么区别?
在Go语言中,`nil`和零值有显著区别。`nil`用于表示指针、通道等类型的“无”或“不存在”,而零值是类型的默认值,如数字的0,字符串的`&#39;&#39;`。`nil`常用于未初始化的变量或错误处理,零值用于提供初始值和避免未初始化的使用。理解两者差异能提升代码质量和稳定性。
|
7天前
|
Go
如何理解Go语言中的值接收者和指针接收者?
Go语言中,函数和方法可使用值或指针接收者。值接收者是参数副本,内部修改不影响原值,如示例中`ChangeValue`无法改变`MyStruct`的`Value`。指针接收者则允许修改原值,因为传递的是内存地址。选择接收者类型应基于是否需要修改参数,值接收者用于防止修改,指针接收者用于允许修改。理解这一区别对编写高效Go代码至关重要。
|
8天前
|
缓存 Java Go
如何用Go语言构建高性能服务
【6月更文挑战第8天】Go语言凭借其并发能力和简洁语法,成为构建高性能服务的首选。本文关注使用Go语言的关键设计原则(简洁、并发、错误处理和资源管理)、性能优化技巧(减少内存分配、使用缓存、避免锁竞争、优化数据结构和利用并发模式)以及代码示例,展示如何构建HTTP服务器。通过遵循这些原则和技巧,可创建出稳定、高效的Go服务。

热门文章

最新文章