项目地址: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. Java-数组练习4

    16.按要求编写Java应用程序.编写一个名为Test的主类,类中只有一个主方法: 在主方法中定义一个大小为50的一维整型数组,数组名为x,数组中存放着{1, 3,5,…,99}输出这个数组中的所有元 ...

  2. Atitit vod click event design flow  视频点播系统点击事件文档

    Atitit vod click event design flow  视频点播系统点击事件文档 重构规划1 Click cate1 Click  mov4 重构规划 事件注册,与事件分发管理器分开 ...

  3. Atiti  attilax主要成果与解决方案与案例rsm版

    Atiti  attilax主要成果与解决方案与案例rsm版 1. ##----------主要成果与解决方案与 参与项目1 ###开发流程系列1 ###架构系列 (au1 ###编程语言系列与架构系 ...

  4. angularjs学习曲线

    angularjs学习曲线 刚开始学Augular觉得开发应用需要有相当的编程基础. 不得不说这确实是一款了不起的开发框架,它要求开发人员设计低耦合和可维护的应用. 使用AngularJS 的复杂度就 ...

  5. unity生成的WP8.1工程的Title本地化实现

    不同于WP本身工程的实现,unity的工程在package.appxmanifest文件中已经定义了 <Resources> <Resource Language="x-g ...

  6. 为什么SQL语句Where 1=1 and在SQL Server中不影响性能

        最近一个朋友和我探讨关于Where 1=1 and这种形式的语句会不会影响性能.最后结论是不影响.     虽然结论正确,但对问题的认识却远远没有解决问题的根本.实际上在T-SQL语句的书写过 ...

  7. java中多线程模拟(多生产,多消费,Lock实现同步锁,替代synchronized同步代码块)

    import java.util.concurrent.locks.*; class DuckMsg{ int size;//烤鸭的大小 String id;//烤鸭的厂家和标号 DuckMsg(){ ...

  8. 一个在ASP.NET中利用服务器控件GridView实现数据增删改查的例子

    备注:这是我辅导的一个项目开发组的一个例子,用文章的方式分享出来,给更多的朋友参考.其实我们这几年的项目中,都不怎么使用服务器控件的形式了,而是更多的采用MVC这种开发模式.但是,如果项目的历史背景是 ...

  9. Cocos2d-x 3.2 学习笔记(十)Joystick 搖杆控件

    最近想做格鬥遊戲,那麼就要有搖杆控件,不想去看別人的代碼就自己寫了個搖杆控件,實現起來很簡單. 話不多說,看代碼: #ifndef __Joystick__ #define __Joystick__ ...

  10. 邻接表有向图(一)之 C语言详解

    本章介绍邻接表有向图.在"图的理论基础"中已经对图进行了理论介绍,这里就不再对图的概念进行重复说明了.和以往一样,本文会先给出C语言的实现:后续再分别给出C++和Java版本的实现 ...