开源Golang ORM框架Queryx:支持自动Schema管理
开源Golang ORM框架Queryx:支持自动Schema管理 Github 链接:GitHub - swiftcarrot/queryx: 面向 Golang 和 TypeScript 的 Schema-first 和类型安全的 ORM
安装:
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 命令来创建 PostgreSQL 数据库,然后运行 queryx db:migrate 来自动创建数据库迁移文件和数据库结构。Queryx 的数据库模式管理建立在 Atlas 之上。
CRUD
运行 queryx g 会在 db 目录中生成相应的 ORM 代码。生成的代码基于数据库模式生成 Go 类型,除了 lib/pq 驱动外没有其他第三方依赖。我们希望自动生成的代码简洁且可读。
以下是一些 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()
关系
模型之间的关系,包括 belongs_to、has_one 和 has_many,也可以在 schema.hcl 中声明。例如:
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 的开发体验。有关 queryx 的更多用法,请参阅 README 文档,并欢迎在 issue、讨论和回复中交流。Queryx 目前处于测试阶段(v0),许多功能仍在开发中,例如 MySQL 支持。我们希望在未来的版本中持续改进开发体验。
更多关于开源Golang ORM框架Queryx:支持自动Schema管理的实战教程也可以访问 https://www.itying.com/category-94-b0.html


