Ent
快速开始 创建第一个模式 1 go run -mod=mod entgo.io/ent/cmd/ent init User 执行后会引入Ent并创建User的schema 1 2 3 4 5 6 7 8 9 10 11 12 13 14 // User在User实体中组合了ent默认的数据库模式定义 type User struct { ent.Schema } // User的字段 func (User) Fields() []ent.Field { return nil } // User的边 func (User) Edges() []ent.Edge { return nil } 添加字段 1 2 3 4 5 6 7 8 9 // User的字段 func (User) Fields() []ent.Field { return []ent.Field{ field.Int("age"). Positive(), field.String("name"). Default("unknown"), } } 生成代码 1 go generate ./ent 创建连接 postgres 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 package main import ( "context" "log" "<project>/ent" _ "github.com/lib/pq" ) func main() { client, err := ent.Open("postgres", "host=<host> port=<port> user=<user> dbname=<database> password=<pass>") if err != nil { log.Fatalf("failed opening connection to postgres: %v", err) } defer client.Close() // 运行自动迁移工具。 if err := client.Schema.Create(context.Background()); err != nil { log.Fatalf("failed creating schema resources: %v", err) } } sqlite3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 package main import ( "context" "log" "<project>/ent" _ "github.com/mattn/go-sqlite3" ) func main() { client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1") if err != nil { log.Fatalf("failed opening connection to sqlite: %v", err) } defer client.Close() // 运行自动迁移工具。 if err := client.Schema.Create(context.Background()); err != nil { log.Fatalf("failed creating schema resources: %v", err) } } mysql 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 package main import ( "context" "log" "<project>/ent" _ "github.com/go-sql-driver/mysql" ) func main() { client, err := ent.Open("mysql", "<user>:<pass>@tcp(<host>:<port>)/<database>?parseTime=True") if err != nil { log.Fatalf("failed opening connection to mysql: %v", err) } defer client.Close() // 运行自动迁移工具。 if err := client.Schema.Create(context.Background()); err != nil { log.Fatalf("failed creating schema resources: %v", err) } } 创建实体 1 2 3 4 5 6 7 8 9 10 11 12 func CreateUser(ctx context.Context, client *ent.Client) (*ent.User, error) { u, err := client.User. Create(). SetAge(30). SetName("a8m"). Save(ctx) if err != nil { return nil, fmt.Errorf("failed creating user: %w", err) } log.Println("user was created: ", u) return u, nil } 查询实体 1 2 3 4 5 6 7 8 9 10 11 12 13 func QueryUser(ctx context.Context, client *ent.Client) (*ent.User, error) { u, err := client.User. Query(). Where(user.Name("a8m")). // `Only` 如果没有发现用户则报错, // 否则正常返回。 Only(ctx) if err != nil { return nil, fmt.Errorf("failed querying user: %w", err) } log.Println("user returned: ", u) return u, nil }