跳到主要内容

项目创建

本指南针对的是首次需要说明如何从零开始创建项目的用户。 在我们开始之前,请确保您的机器上满足了以下前提条件。

前提条件

在安装这些依赖后,创建项目目录并初始化Go模块:

mkdir todo
cd $_
go mod init todo

安装

运行以下的 Go 命令来安装 Ent,初始化带有一个 Todo 结构(Schema) 的项目。

go get -d entgo.io/ent/cmd/ent
go run -mod=mod entgo.io/ent/cmd/ent new Todo

After installing Ent and running ent new, your project directory should look like this:

.
├── ent
│ ├── generate.go
│ └── schema
│ └── todo.go
├── go.mod
└── go.sum

ent 目录包含生成的资源(见下一节), ent/schema 目录包含你的实体结构。

代码生成

When we ran ent new Todo above, a schema named Todo was created in the todo.go file under thetodo/ent/schema/ directory:

package schema

import "entgo.io/ent"

// Todo holds the schema definition for the Todo entity.
type Todo struct {
ent.Schema
}

// Fields of the Todo.
func (Todo) Fields() []ent.Field {
return nil
}

// Edges of the Todo.
func (Todo) Edges() []ent.Edge {
return nil
}

如你所见,初始的Schema没有定义任何字段和边。 让我们运行生成资源的命令,以便与 Todo 实体交互:

go generate ./ent

创建测试案例

运行go generate ./ent调用了Ent的自动代码生成工具,它使用我们在schema包中定义的Schema来生成实际的Go代码,我们现在将使用这些代码与数据库进行交互。 在这个阶段,您可以在./ent/client.go下找到能够查询和更变Todo实体的客户端代码。 Let's create a testable example to use this. 在这个测试案例中,我们将使用 SQLite 来测试Ent。

go get github.com/mattn/go-sqlite3
touch example_test.go

example_test.go中粘贴以下代码,实例化一个ent.Client并自动创建数据库中的所有Schema的相关资源 (数据表、列等)。

package todo

import (
"context"
"log"
"todo/ent"

"entgo.io/ent/dialect"
_ "github.com/mattn/go-sqlite3"
)

func Example_Todo() {
// 使用内存中SQLite数据库来创建 ent.Client
client, err := ent.Open(dialect.SQLite, "file:ent?mode=memory&cache=shared&_fk=1")
if err != nil {
log.Fatalf("failed opening connection to sqlite: %v", err)
}
defer client.Close()
ctx := context.Background()
// 运行自动迁移工具来创建所有Schema资源
if err := client.Schema.Create(ctx); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
// 输出:
}

然后,运行go test来验证一切工作是否符合预期。

go test

设置好项目后,我们就可以创建我们的Todo列表了。