Any ORM or library is supported in Kratos project for data accessing. Please refer to the examples for integration.

Ent is an easy-to-use ORM which developed by Facebook. Here is a brief guide to use this library.

Install Ent

  1. go get entgo.io/ent/cmd/ent

Create Schema

  1. ent init User

This command will generate schema in project/ent/schema/ directory.

  1. // <project>/ent/schema/user.go
  2. package schema
  3. import "entgo.io/ent"
  4. // User holds the schema definition for the User entity.
  5. type User struct {
  6. ent.Schema
  7. }
  8. // Fields of the User.
  9. func (User) Fields() []ent.Field {
  10. return nil
  11. }
  12. // Edges of the User.
  13. func (User) Edges() []ent.Edge {
  14. return nil
  15. }

Add two fields name、age to User table.

  1. package schema
  2. import (
  3. "entgo.io/ent"
  4. "entgo.io/ent/schema/field"
  5. )
  6. // Fields of the User.
  7. func (User) Fields() []ent.Field {
  8. return []ent.Field{
  9. field.Int("age").
  10. Positive(),
  11. field.String("name").
  12. Default("unknown"),
  13. }
  14. }

Run go generate:

  1. go generate ./ent

Create DB Connection Client

First, create a new ent.Client. We use SQLite3 here for demonstration.

  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "<project>/ent"
  6. _ "github.com/mattn/go-sqlite3"
  7. )
  8. func main() {
  9. client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
  10. if err != nil {
  11. log.Fatalf("failed opening connection to sqlite: %v", err)
  12. }
  13. defer client.Close()
  14. // Run the auto migration tool.
  15. if err := client.Schema.Create(context.Background()); err != nil {
  16. log.Fatalf("failed creating schema resources: %v", err)
  17. }
  18. }

To create a User in table.

  1. func CreateUser(ctx context.Context, client *ent.Client) (*ent.User, error) {
  2. u, err := client.User.
  3. Create().
  4. SetAge(30).
  5. SetName("a8m").
  6. Save(ctx)
  7. if err != nil {
  8. return nil, fmt.Errorf("failed creating user: %v", err)
  9. }
  10. log.Println("user was created: ", u)
  11. return u, nil
  12. }

References