Queryx: 开源一个支持数据库自动管理的 Go ORM

查看 40|回复 1
作者:adjusted   
话不多说直接上地址: https://github.com/swiftcarrot/queryx
一键安装:
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:[email protected]: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 的版本。我们希望在后续版本中继续提升开发体验。

err, post, queryx, hcl

Mo3et   
不错不错 帮顶! 周末研究下
您需要登录后才可以回帖 登录 | 立即注册

返回顶部