标签 Go ORM 下的文章

  1. 最近同事为 ZimaOS 项目写了一个极简的 SQLite ORM:zorm,主打一个 简单、够快、好维护。​
  2. 只支持 sqlite,一个文件搞定嵌入式存储,适合小型服务、边缘设备、单机工具这类场景。​
  3. API 尽量贴近原生 SQL,没有复杂的魔法,熟悉 database/sql 的同学几分钟就能上手。​
  4. 内置自 mock 能力,做单元测试不再纠结怎么 stub 掉数据库调用。​
  5. 当前已经在 Zima 系列内部项目中吃自己狗粮,稳定性和性能还不错。​
  6. GitHub 地址:GitHub - IceWhaleTech/zorm: Zima ORM library (just sqlite) that is simple, ultra-fast and self-mockable for Go ,欢迎佬友拍砖、提 issue、提 PR。​
  7. 如果你也在用 Go+SQLite 写小工具或边缘服务,欢迎试用看看,顺手点个 star 支持一下。​

📌 转载信息
原作者:
linkliang
转载时间:
2026/1/16 18:48:38

一键安装:

curl -sf https://raw.githubusercontent.com/swiftcarrot/queryx/main/install.sh  | sh

schema.hcl

Queryx 使用 schema.hcl 来描述数据库,在以下例子中定义了数据库环境以及数据库模型。

database "db" {
  adapter = "postgresql"

  config "development" {
    url = "postgres://postgres:postgres@localhost:5432/blog_development?sslmode=disable"
  }

  config "production" {
    url = env("DATABASE_URL")
  }

  generator "client-golang" {}

  model "Post" {
    column "title" {
      type = string
    }
    column "content" {
      type = text
    }
  }
}

运行 queryx db:create 命令创建 postgres 数据库,然后运行 queryx db:migrate,就可以自动创建对应的 migration 文件和数据库结构。

CRUD

运行 queryx g 在 db 目录下会生成对应的 ORM 代码, 生成的代码根据数据库生成对应的 Go 类型。生成的代码除了 driver 之外没有其他第三方依赖,我们也希望自动生成的代码简洁可读。

下面是一些 CRUD 操作的示例代码:

// 创建
newPost := c.ChangePost().SetTitle("post title")
post, err := c.QueryPost().Create(newPost)

// 查询
post, err := c.QueryPost().Find(1)
posts, err := c.QueryPost().Where(c.PostTitle.EQ("post title")).All()

// 更新
updatePost := c.ChangePost().SetTitle("new post title")
err := post.Update(updatePost)
updated, err := c.QueryPost().Where(c.PostTitle.EQ("post title")).UpdateAll(updatePost)

// 删除
err := post.Delete()
deleted, err := c.QueryPost().Where(c.PostTitle.EQ("post title")).DeleteAll()

关系

在 schema.hcl 也可以声明各个 model 之间的关系,包括 belongs_to, has_one, has_many,例如:

model "User" {
  belongs_to "group" {}

  column "name" {
    type = string
  }
}

model "Group" {
  has_many "users" {}

  column "name" {
    type = string
  }
}

声明关系之后,你可以使用生成的 preload方法来避免 n+1 查询,比如:

users, err := c.QueryUser().PreloadGroup().All()
// users[0].Groups

groups, err := c.QueryGroup().PreloadUsers().All()
// groups[0].User

如果你熟悉 Rails ,就会发现 Queryx 参考了很多 ActiveRecord 的设计,我们希望能够复制 ActiveRecord 的开发体验。更多操作请参阅 README 文档,并欢迎在 issue, discussion 以及回复中交流。Queryx 目前仍处于测试阶段,许多功能仍在开发中,比如 TypeScript 的版本。我们希望在后续版本中继续提升开发体验。

地址: https://github.com/swiftcarrot/queryx