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

123 阅读1分钟

话不多说直接上地址: github.com/swiftcarrot…

一键安装:

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 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 

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