Queryx类型安全 Go ORM

联合创作 · 2023-10-01

Queryx 是 Schema 优先且类型安全的 Go ORM。

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

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 gdb目录下会生成对应的 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

浏览 1
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报