Setting Up
- Go
- (optional)
After installing these dependencies, create a directory for the project and initialize a Go module:
Run the following Go commands to install Ent, and tell it to initialize the project structure along with a schema.
go get -d entgo.io/ent/cmd/ent
go run entgo.io/ent/cmd/ent init Todo
The ent
directory holds the generated assets (see the next section), and the ent/schema
directory contains your entity schemas.
When we ran ent init 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
}
func (Todo) Fields() []ent.Field {
}
// Edges of the Todo.
func (Todo) Edges() []ent.Edge {
return nil
}
go generate ./ent
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 in this test-case for testing Ent.
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"
)
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:
}
go test
After setting up our project, we’re ready to create our Todo list.