【转】数据库无关的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 ...
随机推荐
- 每天一个linux命令(55):traceroute命令
通过traceroute我们可以知道信息从你的计算机到互联网另一端的主机是走的什么路径.当然每次数据包由某一同样的出发点(source)到达某一同样的目的地(destination)走的路径可能会不 ...
- 每天一个linux命令(60):scp命令
scp是secure copy的简写,用于在Linux下进行远程拷贝文件的命令,和它类似的命令有cp,不过cp只是在本机进行拷贝不能跨服务器,而且scp传输是加密的.可能会稍微影响一下速度.当你服务器 ...
- Redis教程(十一):虚拟内存介绍:
转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/138.html 一.简介: 和大多NoSQL数据库一样,Redis同样遵循 ...
- Redis教程(十三):管线详解
转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/141.html 一.请求应答协议和RTT: Redis是一种典型的基于C/ ...
- 我心中的核心组件(可插拔的AOP)~第十三回 实现AOP的拦截组件Unity.Interception
回到目录 说在前 本节主要说一下Unity家族里的拦截组件,对于方法拦截有很多组件提供,基本上每个Ioc组件都有对它的实现,如autofac,它主要用在orchard项目里,而castle也有以拦截的 ...
- .NetCore~框架版本号不同引起dotnet不能run它
对于.netCore来说,今年已经推出了正式版,这要求使用vs2015的开发者需要升级到beta3版,而如果使用老版VS开始的.netCore应用程序,它的架构版本将为是测试版"versio ...
- Atitit main函数的ast分析 数组参数调用的ast astview解析
Atitit main函数的ast分析 数组参数调用的ast astview解析 1.1. Xxcls.main(new String[]{"","bb"}) ...
- iOS----单例模式(Singleton)
单例的意思就是只有一个实例.单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例.这个类称为单例类. 1.单例模式的要点: 显然单例模式的要点有三个:一是某个类只能有一个实例:二是 ...
- 安装指定版本的cordova
安装指定版本的cordova 刚接触cordova看到教程肯定是直接 npm install -g cordova 然后下载个集成的adt 以为万事大吉,开始hello world 玩玩没有想到最新的 ...
- linux安装locust
linux安装locust 1. 安装epel扩展源(目的是为了在安装Pip时不出现一堆乱七八糟的错误信息) EPEL(http://fedoraproject.org/wiki/EPEL) 是由 F ...