增删改查 API

正如 介绍 部分所述,对 schemas 运行 ent 命令, 将生成以下资源:

  • ClientTx 对象用于与图的交互。
  • 每个schema对应的增删改查生成器, 查看 CRUD 了解更多信息。
  • 每个schema的实体对象(Go结构体)。
  • 含常量和查询条件的包,用于与生成器交互。
  • 用于数据迁移的migrate包. 查看 迁移 获取更多信息。

创建新的客户端

MySQL

  1. package main
  2. import (
  3. "log"
  4. "<project>/ent"
  5. _ "github.com/go-sql-driver/mysql"
  6. )
  7. func main() {
  8. client, err := ent.Open("mysql", "<user>:<pass>@tcp(<host>:<port>)/<database>?parseTime=True")
  9. if err != nil {
  10. log.Fatal(err)
  11. }
  12. defer client.Close()
  13. }

PostgreSQL

  1. package main
  2. import (
  3. "log"
  4. "<project>/ent"
  5. _ "github.com/lib/pq"
  6. )
  7. func main() {
  8. client, err := ent.Open("postgres","host=<host> port=<port> user=<user> dbname=<database> password=<pass>")
  9. if err != nil {
  10. log.Fatal(err)
  11. }
  12. defer client.Close()
  13. }

SQLite

  1. package main
  2. import (
  3. "log"
  4. "<project>/ent"
  5. _ "github.com/mattn/go-sqlite3"
  6. )
  7. func main() {
  8. client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1")
  9. if err != nil {
  10. log.Fatal(err)
  11. }
  12. defer client.Close()
  13. }

Gremlin (AWS Neptune)

  1. package main
  2. import (
  3. "log"
  4. "<project>/ent"
  5. )
  6. func main() {
  7. client, err := ent.Open("gremlin", "http://localhost:8182")
  8. if err != nil {
  9. log.Fatal(err)
  10. }
  11. }

创建一个实体

通过 Save 保存一个用户.

  1. a8m, err := client.User. // UserClient.
  2. Create(). // 用户创建构造器
  3. SetName("a8m"). // 设置字段的值
  4. SetNillableAge(age). // 忽略nil检查
  5. AddGroups(g1, g2). // 添加多个边
  6. SetSpouse(nati). // 设置单个边
  7. Save(ctx) // 创建并返回

通过 SaveX 保存一个宠物; 和 Save 不一样, SaveX 在出错时 panic。

  1. pedro := client.Pet. // PetClient.
  2. Create(). // 宠物创建构造器
  3. SetName("pedro"). // 设置字段的值
  4. SetOwner(a8m). // 设置主人 (唯一的边)
  5. SaveX(ctx) // 创建并返回

批量创建

通过 Save 批量保存宠物。

  1. names := []string{"pedro", "xabi", "layla"}
  2. bulk := make([]*ent.PetCreate, len(names))
  3. for i, name := range names {
  4. bulk[i] = client.Pet.Create().SetName(name).SetOwner(a8m)
  5. }
  6. pets, err := client.Pet.CreateBulk(bulk...).Save(ctx)

更新单个实体

更新一个从数据库内的实体。

  1. a8m, err = a8m.Update(). // 用户更新构造器
  2. RemoveGroup(g2). // 移除特定的边
  3. ClearCard(). // 清空唯一的边
  4. SetAge(30). // 设置字段的值
  5. Save(ctx) // 保存并返回

通过ID更新

  1. pedro, err := client.Pet. // PetClient.
  2. UpdateOneID(id). // 宠物更新构造器
  3. SetName("pedro"). // 设置名字字段
  4. SetOwnerID(owner). // 通过ID设置唯一的边
  5. Save(ctx) // 保存并返回

批量更新

通过断言筛选。

  1. n, err := client.User. // UserClient.
  2. Update(). // 宠物更新构造器
  3. Where( //
  4. user.Or( // (age >= 30 OR name = "bar")
  5. user.AgeGT(30), //
  6. user.Name("bar"), // AND
  7. ), //
  8. user.HasFollowers(), // UserHasFollowers()
  9. ). //
  10. SetName("foo"). // 设置名字字段
  11. Save(ctx) // 执行并返回

通过边上的断言筛选。

  1. n, err := client.User. // UserClient.
  2. Update(). // 宠物更新构造器
  3. Where( //
  4. user.HasFriendsWith( // UserHasFriendsWith (
  5. user.Or( // age = 20
  6. user.Age(20), // OR
  7. user.Age(30), // age = 30
  8. ) // )
  9. ), //
  10. ). //
  11. SetName("a8m"). // 设置名字字段
  12. Save(ctx) // 执行并返回

合并单个实体

Ent 支持 合并) 记录,使用 sql/upsert 功能标识。

  1. err := client.User.
  2. Create().
  3. SetAge(30).
  4. SetName("Ariel").
  5. OnConflict().
  6. // 使用新设定的新值。
  7. UpdateNewValues().
  8. Exec(ctx)
  9. id, err := client.User
  10. Create().
  11. SetAge(30).
  12. SetName("Ariel").
  13. OnConflict().
  14. // 使用创建时设定的“age”。
  15. UpdateAge().
  16. // 在发生冲突的情况下设置不同的“name”。
  17. SetName("Mashraki").
  18. ID(ctx)
  19. // Customize the UPDATE clause.
  20. err := client.User.
  21. Create().
  22. SetAge(30).
  23. SetName("Ariel").
  24. OnConflict().
  25. UpdateNewValues().
  26. // Override some of the fields with a custom update.
  27. Update(func(u *ent.UserUpsert) {
  28. u.SetAddress("localhost")
  29. u.AddCount(1)
  30. u.ClearPhone()
  31. }).
  32. Exec(ctx)

在 PostgreSQL 中,需要设置 冲突目标

  1. // Setting the column names using the fluent API.
  2. err := client.User.
  3. Create().
  4. SetName("Ariel").
  5. OnConflictColumns(user.FieldName).
  6. UpdateNewValues().
  7. Exec(ctx)
  8. // Setting the column names using the SQL API.
  9. err := client.User.
  10. Create().
  11. SetName("Ariel").
  12. OnConflict(
  13. sql.ConflictColumns(user.FieldName),
  14. ).
  15. UpdateNewValues().
  16. Exec(ctx)
  17. // Setting the constraint name using the SQL API.
  18. err := client.User.
  19. Create().
  20. SetName("Ariel").
  21. OnConflict(
  22. sql.ConflictConstraint(constraint),
  23. ).
  24. UpdateNewValues().
  25. Exec(ctx)

In order to customize the executed statement, use the SQL API:

  1. id, err := client.User.
  2. Create().
  3. OnConflict(
  4. sql.ConflictColumns(...),
  5. sql.ConflictWhere(...),
  6. sql.UpdateWhere(...),
  7. ).
  8. Update(func(u *ent.UserUpsert) {
  9. u.SetAge(30)
  10. u.UpadteName()
  11. }).
  12. ID(ctx)
  13. // INSERT INTO "users" (...) VALUES (...) ON CONFLICT WHERE ... DO UPDATE SET ... WHERE ...
Since the upsert API is implemented using the ON CONFLICT clause (and ON DUPLICATE KEY in MySQL), Ent executes only one statement to the database, and therefore, only create hooks are applied for such operations. :::" class="reference-link">增删改查 API - 图2Since the upsert API is implemented using the ON CONFLICT clause (and ON DUPLICATE KEY in MySQL), Ent executes only one statement to the database, and therefore, only create hooks are applied for such operations. :::

合并多个实体

  1. err := client.User. // UserClient
  2. CreateBulk(builders...). // User bulk create.
  3. OnConflict(). // User bulk upsert.
  4. UpdateNewValues(). // Use the values that were set on create in case of conflict.
  5. Exec(ctx) // Execute the statement.

在图中查询

Get all users with followers.

  1. users, err := client.User. // UserClient.
  2. Query(). // User query builder.
  3. Where(user.HasFollowers()). // filter only users with followers.
  4. All(ctx) // query and return.

Get all followers of a specific user; Start the traversal from a node in the graph.

  1. users, err := a8m.
  2. QueryFollowers().
  3. All(ctx)

Get all pets of the followers of a user.

  1. users, err := a8m.
  2. QueryFollowers().
  3. QueryPets().
  4. All(ctx)

More advance traversals can be found in the next section.

字段选择

获取所有宠物的名字。

  1. names, err := client.Pet.
  2. Query().
  3. Select(pet.FieldName).
  4. Strings(ctx)

Get all unique pet names.

  1. names, err := client.Pet.
  2. Query().
  3. Unique(true).
  4. Select(pet.FieldName).
  5. Strings(ctx)

Select partial objects and partial associations.gs Get all pets and their owners, but select and fill only the ID and Name fields.

  1. pets, err := client.Pet.
  2. Query().
  3. Select(pet.FieldName).
  4. WithOwner(func (q *ent.UserQuery) {
  5. q.Select(user.FieldName)
  6. }).
  7. All(ctx)

Scan all pet names and ages to custom struct.

  1. var v []struct {
  2. Age int `json:"age"`
  3. Name string `json:"name"`
  4. }
  5. err := client.Pet.
  6. Query().
  7. Select(pet.FieldAge, pet.FieldName).
  8. Scan(ctx, &v)
  9. if err != nil {
  10. log.Fatal(err)
  11. }

Update an entity and return a partial of it.

  1. pedro, err := client.Pet.
  2. UpdateOneID(id).
  3. SetAge(9).
  4. SetName("pedro").
  5. // Select allows selecting one or more fields (columns) of the returned entity.
  6. // The default is selecting all fields defined in the entity schema.
  7. Select(pet.FieldName).
  8. Save(ctx)

删除一个

删除一个实体。

  1. err := client.User.
  2. DeleteOne(a8m).
  3. Exec(ctx)

根据ID进行删除。

  1. err := client.User.
  2. DeleteOneID(id).
  3. Exec(ctx)

批量删除

Delete using predicates.

  1. _, err := client.File.
  2. Delete().
  3. Where(file.UpdatedAtLT(date)).
  4. Exec(ctx)

更变

Each generated node type has its own type of mutation. For example, all User builders, share the same generated UserMutation object. However, all builder types implement the generic ent.Mutation interface.

For example, in order to write a generic code that apply a set of methods on both ent.UserCreate and ent.UserUpdate, use the UserMutation object:

  1. func Do() {
  2. creator := client.User.Create()
  3. SetAgeName(creator.Mutation())
  4. updater := client.User.UpdateOneID(id)
  5. SetAgeName(updater.Mutation())
  6. }
  7. // SetAgeName sets the age and the name for any mutation.
  8. func SetAgeName(m *ent.UserMutation) {
  9. m.SetAge(32)
  10. m.SetName("Ariel")
  11. }

In some cases, you want to apply a set of methods on multiple types. For cases like this, either use the generic ent.Mutation interface, or create your own interface.

  1. func Do() {
  2. creator1 := client.User.Create()
  3. SetName(creator1.Mutation(), "a8m")
  4. creator2 := client.Pet.Create()
  5. SetName(creator2.Mutation(), "pedro")
  6. }
  7. // SetNamer wraps the 2 methods for getting
  8. // and setting the "name" field in mutations.
  9. type SetNamer interface {
  10. SetName(string)
  11. Name() (string, bool)
  12. }
  13. func SetName(m SetNamer, name string) {
  14. if _, exist := m.Name(); !exist {
  15. m.SetName(name)
  16. }
  17. }