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.

    1. go get -d entgo.io/ent/cmd/ent
    1. 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:

    1. package schema
    2. import "entgo.io/ent"
    3. // Todo holds the schema definition for the Todo entity.
    4. type Todo struct {
    5. ent.Schema
    6. }
    7. func (Todo) Fields() []ent.Field {
    8. }
    9. // Edges of the Todo.
    10. func (Todo) Edges() []ent.Edge {
    11. return nil
    12. }
    1. 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).

    1. package todo
    2. import (
    3. "context"
    4. "log"
    5. "todo/ent"
    6. "entgo.io/ent/dialect"
    7. )
    8. func Example_Todo() {
    9. // Create an ent.Client with in-memory SQLite database.
    10. client, err := ent.Open(dialect.SQLite, "file:ent?mode=memory&cache=shared&_fk=1")
    11. if err != nil {
    12. log.Fatalf("failed opening connection to sqlite: %v", err)
    13. }
    14. defer client.Close()
    15. ctx := context.Background()
    16. // Run the automatic migration tool to create all schema resources.
    17. if err := client.Schema.Create(ctx); err != nil {
    18. log.Fatalf("failed creating schema resources: %v", err)
    19. }
    20. // Output:
    21. }
    1. go test

    After setting up our project, we’re ready to create our Todo list.