项目地址: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{})
}

【转】数据库无关的GO语言ORM - hood的更多相关文章

  1. Python与数据库[2] -> 关系对象映射/ORM[0] -> ORM 与 sqlalchemy 模块

    ORM 与 sqlalchemy 1 关于ORM / About ORM 1.1 ORM定义 / Definition of ORM ORM(Object Relational Mapping),即对 ...

  2. Python与数据库[2] -> 关系对象映射/ORM[1] -> sqlalchemy 的基本使用示例

    sqlalchemy 的基本使用示例 下面的例子中将利用sqlalchemy进行数据库的连接,通过orm方式利用类实例属性操作的方式对数据库进行相应操作,同时应用一些常用的函数. 完整代码如下: fr ...

  3. python第一百零五天 ---Django 基础 路由系统 URL 模板语言 ORM 操作

    一 路由系统 URL 1 url(r'^index/',views.index) url(r'^home/', views.Home.as_view()) 2 url(r'^detail-(\d+). ...

  4. C#.NET 大型企业信息化系统集成快速开发平台 4.2 版本 - 基于数据库资源的多语言实现

    以前的开发平台里,是用xml语言包实现了多语言功能,现在新的平台里进行了调整,把多语言包资源放在数据库表里实现了. 我们系统预留了多语言的配置全局变量.可以通过配置这个参数达到切换多语言的目的 我们在 ...

  5. MySQL数据库定义与操作语言

    文章为作者原创,未经许可,禁止转载.    -Sun Yat-sen University 冯兴伟 实验1.1 数据库定义 (1)实验目的 理解和掌握数据库DDL语言,能够熟练地使用SQL DDL语句 ...

  6. SQL Server数据库(SQL Sever语言 CRUD)

    使用SQL Sever语言进行数据库的操作 常用关键字identity 自增长primary key 主键unique 唯一键not null 非空references 外键(引用) 在使用查询操作数 ...

  7. Linux下安装MySQL数据库以及用C语言编程存取数据库

    ubuntu下安装软件相当简单,一条简单的 apt-get install 就可以解决,相比源码安装方式唯一的缺点就是,你无法自定义软件的安装目录.不过这也不是什么太大的缺点.下面我们就用 apt-g ...

  8. 数据库的四种语言(DDL、DML、DCL、TCL)

    1.DDL (Data Definition Language )数据库定义语言 statements are used to define the database structure or sch ...

  9. Java虚拟机的平台无关性与语言无关性

    平台无关性 不同平台的不同java虚拟机,都执行同一种字节码文件,即Class文件 语言无关性 Java虚拟机不止能执行java程序,还有Clojure.Groovy.JRuby.Jython.Sca ...

随机推荐

  1. iOS xcode6 设置多语言

    1,首先新建一个文件,选中ios模块下Rescource的Strings File 类型.eg:文件 2,选中该文件,右边栏选该文件属性,选中Localizable模块,选中localiz,这时会弹出 ...

  2. Redis操作命令总结

    转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/118.html?1455860089 一.key pattern 查询相应 ...

  3. Jquery 选择器 详解

    在线文档地址:http://tool.oschina.net/apidocs/apidoc?api=jquery 各种在线工具地址:http://www.ostools.net/ 一.基本选择器 $( ...

  4. KnockoutJS 3.X API 第三章 计算监控属性(1) 使用计算监控属性

    计算监控属性(Computed Observables) 如果你有一个监控属性firstName,和另一个lastName,你要显示的全名?可以使用计算监控属性来实现-它依赖于一个或多个其他监控属性, ...

  5. Unity5.x在WP8.1中无法使用Reflection API的解决方法

    下班前随便写点,虽然花了不少时间但是最终得到的解决方法还是比较简单的. 第一种方法:使用WinRTLegacy.dll中的类.这个dll在生成的WP project中是自带的无需在unity工程中添加 ...

  6. redis + 主从 + 持久化 + 分片 + 集群 + spring集成

    Redis是一个基于内存的数据库,其不仅读写速度快,每秒可以执行大约110000的写操作,81000的读取操作,而且其支持存储字符串,哈希结构,链表,集合丰富的数据类型.所以得到很多开发者的青睐.加之 ...

  7. Sort the Array

    /* 思路: 找到单调下降串的起始位置[l, r] 如果左边 0...l-1中的最大值 > l...r中的最小值 或者 r+1...n中的最小值 < l...r中的最大值 都是不能实现排序 ...

  8. Supplemental Logging

    Supplemental Logging分为两种:Database-Level Supplemental Logging和Table-Level Supplemental Logging,即数据库级别 ...

  9. 邻接矩阵无向图(三)之 Java详解

    前面分别介绍了邻接矩阵无向图的C和C++实现,本文通过Java实现邻接矩阵无向图. 目录 1. 邻接矩阵无向图的介绍 2. 邻接矩阵无向图的代码说明 3. 邻接矩阵无向图的完整源码 转载请注明出处:h ...

  10. Spring Annotation Processing: How It Works--转

    找的好辛苦呀 原文地址:https://dzone.com/articles/spring-annotation-processing-how-it-works If you see an annot ...