【转】数据库无关的GO语言ORM - 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{})
}
【转】数据库无关的GO语言ORM - hood的更多相关文章
- Python与数据库[2] -> 关系对象映射/ORM[0] -> ORM 与 sqlalchemy 模块
ORM 与 sqlalchemy 1 关于ORM / About ORM 1.1 ORM定义 / Definition of ORM ORM(Object Relational Mapping),即对 ...
- Python与数据库[2] -> 关系对象映射/ORM[1] -> sqlalchemy 的基本使用示例
sqlalchemy 的基本使用示例 下面的例子中将利用sqlalchemy进行数据库的连接,通过orm方式利用类实例属性操作的方式对数据库进行相应操作,同时应用一些常用的函数. 完整代码如下: fr ...
- python第一百零五天 ---Django 基础 路由系统 URL 模板语言 ORM 操作
一 路由系统 URL 1 url(r'^index/',views.index) url(r'^home/', views.Home.as_view()) 2 url(r'^detail-(\d+). ...
- C#.NET 大型企业信息化系统集成快速开发平台 4.2 版本 - 基于数据库资源的多语言实现
以前的开发平台里,是用xml语言包实现了多语言功能,现在新的平台里进行了调整,把多语言包资源放在数据库表里实现了. 我们系统预留了多语言的配置全局变量.可以通过配置这个参数达到切换多语言的目的 我们在 ...
- MySQL数据库定义与操作语言
文章为作者原创,未经许可,禁止转载. -Sun Yat-sen University 冯兴伟 实验1.1 数据库定义 (1)实验目的 理解和掌握数据库DDL语言,能够熟练地使用SQL DDL语句 ...
- SQL Server数据库(SQL Sever语言 CRUD)
使用SQL Sever语言进行数据库的操作 常用关键字identity 自增长primary key 主键unique 唯一键not null 非空references 外键(引用) 在使用查询操作数 ...
- Linux下安装MySQL数据库以及用C语言编程存取数据库
ubuntu下安装软件相当简单,一条简单的 apt-get install 就可以解决,相比源码安装方式唯一的缺点就是,你无法自定义软件的安装目录.不过这也不是什么太大的缺点.下面我们就用 apt-g ...
- 数据库的四种语言(DDL、DML、DCL、TCL)
1.DDL (Data Definition Language )数据库定义语言 statements are used to define the database structure or sch ...
- Java虚拟机的平台无关性与语言无关性
平台无关性 不同平台的不同java虚拟机,都执行同一种字节码文件,即Class文件 语言无关性 Java虚拟机不止能执行java程序,还有Clojure.Groovy.JRuby.Jython.Sca ...
随机推荐
- EF架构~为IEnumerable接口添加增删查等操作,原因是IEnumerable导航属性更放心
回到目录 对EF开发来说,导航属性肯定都用过,事实上,它是由VS IDE工具根据你的数据库关系结构自动生成的外键属性,在类视图中可以看到相关属性,它是以外键表名来标识的,如果是一对多的关系,那么,它会 ...
- Liferay7 BPM门户开发之40: Form表单的Action到Render的数据传递
在Form提交后的变量,很多情况是要展现在jsp页面中,这时Action到Render的变量传递就非常有用. 例如,您在数据库中添加了学生的详细信息. 为了实现这一需求,先创建Form表单(学生的细节 ...
- Spring Cloud 配置服务
Spring Cloud 配置服务 1. 配置服务简介 产生背景: 传统开发中,我们通常是将系统的业务无关配置(数据库,缓存服务器)在properties中配置,在这个文件中不会经常改变,但随着系统规 ...
- sql server 链接到本地实例出错
我在使用VS2010测试package的时候,突然发现sql server 链接到本地实例出错,出错信息如下: “ A network-related or instance-specific err ...
- Android属性动画之ObjectAnimator控制
Android为我们提供了大量的动画效果,如何通过这些动画来达到我们需要的效果呢?今天就为大家总结一下ObjectAnimator动画控制事件. 该项目的的布局文件只有两个控件:ImageView和B ...
- c++中关于初始化型参列表的一些问题
/* 1.成员是按照他们在类中出现的顺序进行初始化的,而不是按照他们在初始化列表出现的顺序初始化的! 一个好的习惯是,按照成员定义的顺序进行初始化. 2.数组成员在初始化型参列表中不正确 */ #in ...
- 10034 - Freckles 克鲁斯克尔最小生成树!~
/* 10034 - Freckles 克鲁斯克尔最小生成树!- */ #include<iostream> #include<cstdio> #include<cmat ...
- Linux的学习--使用PuTTY
交代一下背景,在笔记本上装虚拟机,在虚拟机里装了Ubuntu系统,但用着一直感觉很卡.刚好同学有旧的不用的笔记本,就拿来装了一个Ubuntu. 想要从我的笔记本上控制Ubuntu系统,于是就找到了pu ...
- Unity 游戏存档 PlayerPrefs类的用法
unity3d提供了一个用于本地持久化保存与读取的类--PlayerPrefs.工作原理非常简单,以键值对的形式将数据保存在文件中,然后程序可以根据这个名称取出上次保存的数值. PlayerPr ...
- Spring定时器,定时执行(quartz)
这个定时器与继承了timertask的定时器不同的是,这个定时器是更强大的,可以指定每分的第n秒,每天的第n时,每周的.每年的.来定时运行这个定时器.那么下面来讲诉如何使用quartz定时器. spr ...