Creating a New Schema
Workflow for generating a new schema and its CRUD resolvers. Read the code generation ordering gotcha first; it will save you a failed first run.
Create a New Schema File
task db:newschema -- MyNewSchema
Update the Templated Schema
The file will be located in internal/ent/schema/, the file name matching the schema name. Work through the template:
- Keep the
IDMixinand the standard annotations included in the template; removingIDMixincauses ID type conflicts with the rest of the graph - Add fields to the schema
- Add edges for 1:1, 1:m, or m:m relationships with other objects
- Add indexes where needed
- Review and update the annotations on the templated schema
- Add hooks for mutations and interceptors for queries; see Hooks and Interceptors
- Review and update the privacy policy on the templated schema
Example
A common index pattern in our codebase allows soft-deleted names to be reused even when the name must be unique:
index.Fields("name").
Unique().Annotations(entsql.IndexWhere("deleted_at is NULL")),
Generate the CRUD Resolvers
task generate
This will take a few minutes the first time. The main tools that run:
| Tool | Generates |
|---|---|
entc | ORM code for the schema: field getters and setters, create/update/delete operations against the database |
gqlgen | GraphQL resolvers and basic query generation |
gqlgenc | The Go API client, from the queries in internal/graphapi/query |
gencmd | Base CRUD operations for CLI commands |
Generate the Migrations
Generate the goose and atlas migrations based on the ent schema changes:
task db:create
Stub Out the CRUD CLI Commands
task cli:generate
info
The cli flags for create and update, along with field output (in root.go), will need to be manually updated