Queryx類型安全 Go ORM
Queryx 是 Schema 優(yōu)先且類型安全的 Go ORM。
Queryx 使用schema.hcl來描述數(shù)據(jù)庫,在以下例子中定義了數(shù)據(jù)庫環(huán)境以及數(shù)據(jù)庫模型。
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命令創(chuàng)建 postgres 數(shù)據(jù)庫,然后運行queryx db:migrate,就可以自動創(chuàng)建對應的 migration 文件和數(shù)據(jù)庫結構。
CRUD
運行queryx g在db目錄下會生成對應的 ORM 代碼,生成的代碼根據(jù)數(shù)據(jù)庫生成對應的 Go 類型。生成的代碼除了 driver 之外沒有其他第三方依賴。
下面是一些 CRUD 操作的示例代碼:
// 創(chuàng)建
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
評論
圖片
表情
