项目地址: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. jq源码立即执行函数的undefined参数

    函数参数是undefined,那这个undefined是个变量标识符还是值呢? <JS权威指南>函数一章讲过,未给函数形参传值的时候,该形参的值是undefined.所以形参undefin ...

  2. NodeJS系列~第四个小例子,NodeJs处理Get请求和Post请求

    返回目录 说在前 对于HTTP请求来说,我们通常使用的是Get和Post,除此之外还有put,delete等,而对于get来说,比较lightweight,只是对字符串的传输,它会被添加到URL地址里 ...

  3. java基础 数组15

    15.找出如下数组中最大的元素和最小的元素, a[][]={{3,2,6},{6,8,2,10},{5},{12,3,23}}

  4. [Maven]Eclipse插件之Maven配置及问题解析.

    前言:今天在自己环境装了Maven环境, 并且安装了Eclipse插件, 在查找插件过程中确实遇到一些问题, 好不容易找到一个  却又有问题.装好了插件之后, 用Eclipse创建Maven项目却出现 ...

  5. Atitit ACID解决方案2PC(两阶段提交)  跨越多个数据库实例的ACID保证

    Atitit ACID解决方案2PC(两阶段提交)  跨越多个数据库实例的ACID保证 1.1. ACID解决方案1 1.2. 数据库厂商在很久以前就认识到数据库分区的必要性,并引入了一种称为2PC( ...

  6. java连接数据库的模糊查询

    1:模糊查询是比较常见的一种查询方式,例如在订单表中,包含有订单的具体日期.如果要查询某年某月的订单信息,最好的方式就是使用模糊查询.进行模糊查询需要使用关键字LIKE.在使用LIKE关键字进行模糊查 ...

  7. CCNA网络工程师学习进程(1)网络的基本概述

        在互联网快速发展的今天,了解互联网成为一项必须的技能,因此在学习编程之余学习如何配置网络还是很有必要的. 本系列博客计划分为三个部分,包括思科CCNA.CCNP和华为的网络工程师认证有关的知识 ...

  8. Python中的字符串与字符编码

    本节内容: 前言 相关概念 Python中的默认编码 Python2与Python3中对字符串的支持 字符编码转换 一.前言 Python中的字符编码是个老生常谈的话题,同行们都写过很多这方面的文章. ...

  9. java中有关线程的题目

    1,看一下下面程序错误发生在哪一行! class Test implements Runnable{ public void run(Thread t){ } } 2,输出结果是什么? class T ...

  10. Windows Azure Virtual Machine (30) 修改Azure VM 的Subnet

    <Windows Azure Platform 系列文章目录> 我在使用Azure Virtual Machine虚拟机的时候,常常会结合Virtual Network虚拟网络一起使用. ...