Setting Up
המדריך הזה מיועד למשתמשים חדשים המעוניינים בהוראות איך להגדיר פרויקט אנט חדש מאפס. לפני שאנחנו מתחילים, יש לוודא שהדרישות המוקדמות מותקנות אצלכם על המחשב.
דרישות מוקדמות
- Go
- Docker (אופציונלי)
לאחר התקנת התלויות הנ״ל, צרו תיקיה חדשה בשביל הפרויקט ואתחלו מודול Go חדש:
mkdir todo
cd $_
go mod init todo
התקנה
הריצו את פקודות הGo הבאות על מנת להתקין את Ent ולאתחל את מבנה הפרויקט עם סכימה בשם Todo
.
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
The ent
directory holds the generated assets (see the next section), and the ent/schema
directory contains your entity schemas.
Code Generation
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
}
As you can see, initially, the schema has no fields or edges defined. Let's run the command for generating assets to interact with the Todo
entity:
go generate ./ent
Create a Test Case
Running go generate ./ent
invoked Ent's automatic code generation tool, which uses the schemas we define in our schema
package to generate the actual Go code which we will now use to interact with a database. At this stage, you can find under ./ent/client.go
, client code that is capable of querying and mutating the Todo
entities. Let's create a testable example to use this. We'll use SQLite in this test-case for testing Ent.
go get github.com/mattn/go-sqlite3
touch example_test.go
Paste the following code in example_test.go
that instantiates an ent.Client
and automatically creates all schema resources in the database (tables, columns, etc).
package todo
import (
"context"
"log"
"todo/ent"
"entgo.io/ent/dialect"
_ "github.com/mattn/go-sqlite3"
)
func Example_Todo() {
// Create an ent.Client with in-memory SQLite database.
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()
// Run the automatic migration tool to create all schema resources.
if err := client.Schema.Create(ctx); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
// Output:
}
Then, run go test
to verify that everything works as expected.
go test
After setting up our project, we're ready to create our Todo list.