ent orm笔记2---schema使用(上)

全面揭秘 Go 语言超强 ORM 框架 Ent:高效构建数据库的终极武器! 阅读详情

在上一篇关于快速使用ent orm的笔记中,我们在最开始使用entc init User 创建schema,在ent orm 中的schema 其实就是数据库模型,在schema中我们可以通过Fields 定义数据库中表的字段信息;通过Edges 定义表之间的关系信息;通过Index 定义字段的索引信息等等,这篇文章会整理一下关于ent orm 中如何使用这些。

备注:文章中的所有代码在github.com/peanut-cc/ent_orm_notes

Fileds

当我们执行 entc init User 之后,会在当前目录下生成一个ent目录,在该目录下有一个schema目录,默认情况下schema/user.go文件如下:

package schema

import "github.com/facebook/ent"

// User holds the schema definition for the User entity.
type User struct {
 ent.Schema
}

// Fields of the User.
func (User) Fields() []ent.Field {
 return nil
}

// Edges of the User.
func (User) Edges() []ent.Edge {
 return nil
}

如果要对user 这表添加字段,需要在Fileds方法中添加如下所示:

// Fields of the User.
func (User) Fields() []ent.Field {
 return []ent.Field{
  field.Int("age"),
  field.String("username").
   Unique(),
  field.Time("created_at").
   Default(time.Now),
  field.Float32("salary").
   Optional(),
 }
}

「注意:默认情况下,所有字段都是必填字段,可以使用Optional方法将其设置为optional。」

数据类型

下面的数据类型都是支持的:

  • All Go numeric types. Like int, uint8, float64, etc.

  • bool

  • string

  • time.Time

  • []byte (only supported by SQL dialects).

  • JSON (only supported by SQL dialects).

  • Enum (only supported by SQL dialects).

// Fields of the User.
func (User) Fields() []ent.Field {
 return []ent.Field{
  field.Int("age"),
  field.String("username").
   Unique(),
  field.Time("created_at").
   Default(time.Now),
  field.Float32("salary").
   Optional(),
  field.Bool("active").
   Default(false),
  field.JSON("strings", []string{}).
   Optional(),
  field.Enum("state").
   Values("on", "off").
   Optional(),
 }
}

ID字段

数据库表的id字段,默认是内置的,不需要单独添加,其类型默认为int, 并在数据库中自动递增,

为了将id配置为在所有表中唯一,需要在schema migration的时候使用WithGlobalUniqueID

如果需要对id字段进行其他配置,或者想要使用UUID格式存id,则需要覆盖id的配置。

// Fields of the User.
func (User) Fields() []ent.Field {
 return []ent.Field{
  field.Int("id").
   StructTag(`json:"oid,omitempty"`),
 }
}
// Fields of the User.
func (User) Fields() []ent.Field {
 return []ent.Field{
  field.UUID("id", uuid.UUID{}),
 }
}
// Fields of the User.
func (User) Fields() []ent.Field {
 return []ent.Field{
  field.String("id").
   MaxLen(25).
   NotEmpty().
   Unique().
   Immutable(),
 }
}

数据库类型

每个数据库都有自己的从go的数据类型到数据库类型的映射,例如,Mysql 在数据库中将float64字段创建为双精度的。ent orm 有一个选项参数可以使用SchemaType 方法覆盖默认行为

// Fields of the Card.
func (Card) Fields() []ent.Field {
 return []ent.Field{
  field.Float("amount").
   SchemaType(map[string]string{
    dialect.MySQL:    "decimal(6,2)", // Override MySQL.
    dialect.Postgres: "numeric",      // Override Postgres.
   }),
 }
}

GO Type

字段的默认类型是基本的Go数据类型,例如,对于字符串字段,类型为string, 对于时间字段,类型为time.Time

GoType 方法提供了一个选项,可以使用自定义类型替换默认的ent类型。但自定义类型必须是可以转换为Go的基本类型的类型,或者实现了ValueScanner接口的类型

// Fields of the Card.
func (Card) Fields() []ent.Field {
 return []ent.Field{
  field.Float("amount").
   GoType(Amount(0)),
  field.String("name").
   Optional().
            // A ValueScanner type.
   GoType(&sql.NullString{}),
 }
}

Default Values 默认值

Non-unique 的字段可以通过Default 和 UpdateDefault方法设置默认值

// Fields of the Group.
func (Group) Fields() []ent.Field {
 return []ent.Field{
  field.Time("created_at").
   Default(time.Now),
  field.Time("updated_at").
   Default(time.Now).
   UpdateDefault(time.Now),
 }
}

Validators

关于字段的validator是通过 func(T) error 函数,该函数使用Validate方法在schema中定义,并在创建或更新schema的时候应用于字段的校验

字段的validator支持的类型有string 和所有的数字类型

// Fields of the Group.
func (Group) Fields() []ent.Field {
 return []ent.Field{
  field.String("name").
   Match(regexp.MustCompile("[a-zA-Z_]+$")).
   Validate(func(s string) error {
    if strings.ToLower(s) == s {
     return errors.New("group name must begin with uppercase")
    }
    return nil
   }),
 }
}

内置的 Validators

ent orm 提供了一些内置的validators, 如下:

  • Numeric types: Positive() - Positive adds a minimum value validator with the value of 1 Negative() - Negative adds a maximum value validator with the value of -1 NonNegative() - NonNegative adds a minimum value validator with the value of 0 Min(i) - Validate that the given value is > i. Max(i) - Validate that the given value is < i. Range(i, j) - Validate that the given value is within the range [i, j].

  • string:

    MinLen(i) MaxLen(i) Match(regexp.Regexp)

Optional 可选字段

可选字段是在创建的时候不是必传的字段,并将在数据库设置为可为空的字段 默认情况下,字段都是必填字段

Nillable

有时候你可能希望区分字段的零值和nil,如数据库的某列包含0 或者NULL,Nillable选项正是为此而存在的.

如果有一个类型为T的字段设置为Nillable ,在通过go generate 生成代码的时候的时候生成的struct 中改字段的类型是*T, 如果数据库中该字段是NULL, 那么在ent orm的查询结果中就是nil, 否则对于没有设置Nillable的字段,如果数据库中字段的值是NULl,返回的则是改字段的零值

// Fields of the User.
func (User) Fields() []ent.Field {
 return []ent.Field{
  field.String("required_name"),
  field.String("optional_name").Optional(),
  field.String("nilable_name").Optional().Nillable(),
  field.String("nilable_name2").Optional().Nillable(),
  field.Int("age").Optional(),
  field.Int("age2").Optional().Nillable(),
 }
}

我们通过如下代码进行数据的创建和查询,这里分别创建了两条数据,第一条数据的设置SetOptionalName,SetNilableName 的字段都没有设置内容,第二次的时候都设置了内容

package main

import (
 "context"
 "log"

 "github.com/peanut-cc/ent_orm_notes/schema_notes/ent/user"

 _ "github.com/go-sql-driver/mysql"
 "github.com/peanut-cc/ent_orm_notes/schema_notes/ent"
)

func main() {
 client, err := ent.Open("mysql", "root:123456@tcp(10.211.55.3:3306)/schema_notes?parseTime=True")
 if err != nil {
  log.Fatal(err)
 }
 defer client.Close()
 ctx := context.Background()
 // run the auto migration tool
 if err := client.Schema.Create(ctx); err != nil {
  log.Fatalf("failed creating schema resources:%v", err)
 }
 client.User.Create().SetRequiredName("peanut").Save(ctx)
 client.User.Create().SetRequiredName("syncd").
  SetOptionalName("option_name").
  SetNilableName("nil_name").
  SetNilableName2("nil_name2").
  SetAge(18).
  SetAge2(20).
  SaveX(ctx)
 u := client.User.Query().Where(user.RequiredNameEQ("peanut")).OnlyX(ctx)
 log.Printf("required_name is:%v option_name is:%v nil_name is:%v nil_name2 is:%v age is :%v age2 is:%v\n", u.RequiredName,
  u.OptionalName, u.NilableName, u.NilableName2, u.Age, u.Age2)
 u2 := client.User.Query().Where(user.RequiredNameEQ("syncd")).OnlyX(ctx)
 log.Printf("required_name is:%v option_name is:%v nil_name is:%v nil_name2 is:%v age is :%v age2 is:%v\n", u2.RequiredName,
  u2.OptionalName, u2.NilableName, u2.NilableName2, u2.Age, u2.Age2)
}

下面是数据的打印结果:

2020/08/26 20:39:47 required_name is:peanut option_name is: nil_name is:<nil> nil_name2 is:<nil> age is :0 age2 is:<nil>
2020/08/26 20:39:47 required_name is:syncd option_name is:option_name nil_name is:0xc000200580 nil_name2 is:0xc000200590 age is :18 age2 is:0xc00020c4d8

Immutable 不可变字段

不可变字段,是只能在创建的时候设置值

// Fields of the user.
func (User) Fields() []ent.Field {
    return []ent.Field{
        field.String("name"),
        field.Time("created_at").
            Default(time.Now).
            Immutable(),
    }
}

Uniqueness 唯一索引

可以使用Unique方法给字段设置唯一索引。注意:唯一所以字段不能具有默认值

// Fields of the user.
func (User) Fields() []ent.Field {
    return []ent.Field{
        field.String("name"),
        field.String("nickname").
            Unique(),
    }
}

Storage Key

可以使用StorageKey方法配置自定义存储名称。在SQL中映射为列名

// Fields of the user.
func (User) Fields() []ent.Field {
    return []ent.Field{
        field.String("name").
            StorageKey(`old_name"`),
    }
}

Indexes 索引

可以在多个字段和一些关系表中创建索引

Struct Tags

可以使用StructTag方法将自定义struct tag添加到生成的实体中。请注意,如果未提供此选项,或者提供的该选项不包含json标记,则默认json标记将与字段名称一起添加。

// Fields of the user.
func (User) Fields() []ent.Field {
    return []ent.Field{
        field.String("name").
            StructTag(`gqlgen:"gql_name"`),
    }
}

Sensitive Fields

可以使用Sensitive方法将字符串字段定义为Sensitive Fields。Sensitive Fields不会被打印,并且在编码时将被忽略。请注意,Sensitive Fields不能具有struct标记。

// Fields of the user.
func (User) Fields() []ent.Field {
    return []ent.Field{
        field.String("password").
            Sensitive(),
    }
}

Annotations

在代码生成中,Annotations用于将任意元数据附加到字段对象。模板扩展可以检索这个元数据并在它们的模板中使用它。注意,元数据对象必须可序列化为 JSON 原始值(例如,struct、 map 或 slice)。

// Fields of the user.
func (User) Fields() []ent.Field {
    return []ent.Field{
        field.Time("creation_date").
            Annotations(entgql.Annotation{
                OrderField: "CREATED_AT",
            }),
    }
}

Edges

快速使用

Edges 也理解为表之间的association,通常指的我们表之间的一对多,多对多关系等。


ent/schema/pet.go

package schema

import (
 "github.com/facebook/ent"
 "github.com/facebook/ent/schema/edge"
 "github.com/facebook/ent/schema/field"
)

// Pet holds the schema definition for the Pet entity.
type Pet struct {
 ent.Schema
}

// Fields of the Pet.
func (Pet) Fields() []ent.Field {
 return []ent.Field{
  field.String("name"),
 }
}

// Edges of the Pet.
func (Pet) Edges() []ent.Edge {
 return []ent.Edge{
  edge.From("owner", User.Type).
   Ref("pets").
   Unique(),
 }
}

ent/schema/user.go

package schema

import (
 "github.com/facebook/ent"
 "github.com/facebook/ent/schema/edge"
 "github.com/facebook/ent/schema/field"
)

// User holds the schema definition for the User entity.
type User struct {
 ent.Schema
}

// Fields of the User.
func (User) Fields() []ent.Field {
 return []ent.Field{
  field.String("name"),
  field.Int("age"),
 }
}

// Edges of the User.
func (User) Edges() []ent.Edge {
 return []ent.Edge{
  edge.To("pets", Pet.Type),
  edge.From("groups", Group.Type).Ref("users"),
 }
}

ent/schema/group.go

package schema

import (
 "github.com/facebook/ent"
 "github.com/facebook/ent/schema/edge"
 "github.com/facebook/ent/schema/field"
)

// Group holds the schema definition for the Group entity.
type Group struct {
 ent.Schema
}

// Fields of the Group.
func (Group) Fields() []ent.Field {
 return []ent.Field{
  field.String("name"),
 }
}

// Edges of the Group.
func (Group) Edges() []ent.Edge {
 return []ent.Edge{
  edge.To("users", User.Type),
 }
}

在上面的关系中,一个用户可以有多个宠物,但是一个宠物值只能属于一个用户。所以这里对于宠物来说是一对一的关系,对于用户来说是多对一关系。

我们查看一下创建的pets表的信息:

CREATE TABLE `pets` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_bin NOT NULL,
  `user_pets` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `pets_users_pets` (`user_pets`),
  CONSTRAINT `pets_users_pets` FOREIGN KEY (`user_pets`) REFERENCES `users` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin

因为在上述关系中:用户和宠物之间是一对多关系,所以这里使用的edge.To;

而对宠物来说是一对一的关系,所以这里使用edge.From的Ref

edge.To和edge.From 是创建表关系的两个方法

一对一关系

在这个例子中,设定一个用户只能有一张信用卡,而一个信用卡也只能属于一个用户。

ent/schema/user.go

package schema

import (
   "github.com/facebook/ent"
   "github.com/facebook/ent/schema/edge"
   "github.com/facebook/ent/schema/field"
)

// User holds the schema definition for the User entity.
type User struct {
   ent.Schema
}

// Fields of the User.
func (User) Fields() []ent.Field {
   return []ent.Field{
      field.String("name"),
      field.Int("age"),
   }
}

// Edges of the User.
func (User) Edges() []ent.Edge {
   return []ent.Edge{
      edge.To("card", Card.Type).Unique(),
   }
}

ent/schema/card.go

package schema

import (
   "github.com/facebook/ent"
   "github.com/facebook/ent/schema/edge"
   "github.com/facebook/ent/schema/field"
)

// Card holds the schema definition for the Card entity.
type Card struct {
   ent.Schema
}

// Fields of the Card.
func (Card) Fields() []ent.Field {
   return []ent.Field{
      field.String("number"),
      field.Time("expired"),
   }
}

// Edges of the Card.
func (Card) Edges() []ent.Edge {
   return []ent.Edge{
      edge.From("owner", User.Type).
         Ref("card").
         Unique().
         // We add the "Required" method to the builder
         // to make this edge required on entity creation.
         // i.e. Card cannot be created without its owner.
         Required(),
   }
}

一对多关系


在这个例子中用户和宠物之间是一对多关系,每个用户可以有多个宠物,一个宠物只有一个主人

ent/schema/user.go

package schema

import (
   "github.com/facebook/ent"
   "github.com/facebook/ent/schema/edge"
   "github.com/facebook/ent/schema/field"
)

// User holds the schema definition for the User entity.
type User struct {
   ent.Schema
}

// Fields of the User.
func (User) Fields() []ent.Field {
   return []ent.Field{
      field.String("name"),
   }
}

// Edges of the User.
func (User) Edges() []ent.Edge {
   return []ent.Edge{
      edge.To("pets", Pet.Type),
   }
}

ent/schema/pet.go

package schema

import (
   "github.com/facebook/ent"
   "github.com/facebook/ent/schema/edge"
   "github.com/facebook/ent/schema/field"
)

// Pet holds the schema definition for the Pet entity.
type Pet struct {
   ent.Schema
}

// Fields of the Pet.
func (Pet) Fields() []ent.Field {
   return []ent.Field{
      field.String("name"),
   }
}

// Edges of the Pet.
func (Pet) Edges() []ent.Edge {
   return []ent.Edge{
      edge.From("owner", User.Type).
         Ref("pets").
         Unique(),
   }
}

相关的查询如下代码:

package main

import (
   "context"
   "fmt"
   "log"

   _ "github.com/go-sql-driver/mysql"

   "github.com/peanut-cc/ent_orm_notes/one_to_many/ent"
)

func main() {
   client, err := ent.Open("mysql", "root:123456@tcp(192.168.1.100:3306)/one_to_one?parseTime=True")
   if err != nil {
      log.Fatal(err)
   }
   defer client.Close()
   ctx := context.Background()
   // run the auto migration tool
   if err := client.Schema.Create(ctx); err != nil {
      log.Fatalf("failed creating schema resources:%v", err)
   }
   Do(ctx, client)
}

func Do(ctx context.Context, client *ent.Client) error {
   // Create the 2 pets.
   pedro, err := client.Pet.
      Create().
      SetName("pedro").
      Save(ctx)
   if err != nil {
      return fmt.Errorf("creating pet: %v", err)
   }
   lola, err := client.Pet.
      Create().
      SetName("lola").
      Save(ctx)
   if err != nil {
      return fmt.Errorf("creating pet: %v", err)
   }
   // Create the user, and add its pets on the creation.
   // 创建用户,并添加用户和宠物的关系
   a8m, err := client.User.
      Create().
      SetName("a8m").
      AddPets(pedro, lola).
      Save(ctx)
   if err != nil {
      return fmt.Errorf("creating user: %v", err)
   }
   fmt.Println("User created:", a8m)shell
   // Output: User(id=1, age=30, name=a8m)

   // Query the owner. Unlike `Only`, `OnlyX` panics if an error occurs.
   // 根据宠物反向查询所属的用户
   owner := pedro.QueryOwner().OnlyX(ctx)
   fmt.Println(owner.Name)
   // Output: a8m

   // Traverse the sub-graph. Unlike `Count`, `CountX` panics if an error occurs.
   // 根据宠物反向查询用户,并查询该用户有多少宠物
   count := pedro.
      QueryOwner(). // a8m
      QueryPets().  // pedro, lola
      CountX(ctx)   // count
   fmt.Println(count)
   // Output: 2
   return nil
}

多对多关系


在这个例子中,用户和组之间是多对多关系,每个组有多个用户,每个用户也可以加入多个组

ent/schema/group.go

package schema

import (
   "github.com/facebook/ent"
   "github.com/facebook/ent/schema/edge"
   "github.com/facebook/ent/schema/field"
)

// Group holds the schema definition for the Group entity.
type Group struct {
   ent.Schema
}

// Fields of the Group.
func (Group) Fields() []ent.Field {
   return []ent.Field{
      field.String("name"),
   }
}

// Edges of the Group.
func (Group) Edges() []ent.Edge {
   return []ent.Edge{
      edge.To("users", User.Type),
   }
}

ent/schema/user.go

package schema

import (
   "github.com/facebook/ent"
   "github.com/facebook/ent/schema/edge"
   "github.com/facebook/ent/schema/field"
)

// User holds the schema definition for the User entity.
type User struct {
   ent.Schema
}

// Fields of the User.
func (User) Fields() []ent.Field {
   return []ent.Field{
      field.String("name"),
   }
}

// Edges of the User.
func (User) Edges() []ent.Edge {
   return []ent.Edge{
      edge.From("groups", Group.Type).Ref("users"),
   }
}

这个时候,会生成第三张表,group_users表,查看表的信息如下:

CREATE TABLE `group_users` (
  `group_id` bigint(20) NOT NULL,
  `user_id` bigint(20) NOT NULL,
  PRIMARY KEY (`group_id`,`user_id`),
  KEY `group_users_user_id` (`user_id`),
  CONSTRAINT `group_users_group_id` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`) ON DELETE CASCADE,
  CONSTRAINT `group_users_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin

常用的查询方法:

package schema

import (
   "github.com/facebook/ent"
   "github.com/facebook/ent/schema/edge"
   "github.com/facebook/ent/schema/field"
)

// User holds the schema definition for the User entity.
type User struct {
   ent.Schema
}

// Fields of the User.
func (User) Fields() []ent.Field {
   return []ent.Field{
      field.String("name"),
   }
}

// Edges of the User.
func (User) Edges() []ent.Edge {
   return []ent.Edge{
      edge.From("groups", Group.Type).Ref("users"),
   }
}

多对多(单张表)


这种关系其实也挺常见的,如我们微博账户,不同账户之间可以相关关注

package schema

import (
   "github.com/facebook/ent"
   "github.com/facebook/ent/schema/edge"
   "github.com/facebook/ent/schema/field"
)

// User holds the schema definition for the User entity.
type User struct {
   ent.Schema
}

// Fields of the User.
func (User) Fields() []ent.package schema

import (
 "github.com/facebook/ent"
 "github.com/facebook/ent/schema/edge"
 "github.com/facebook/ent/schema/field"
)

// User holds the schema definition for the User entity.
type User struct {
 ent.Schema
}

// Fields of the User.
func (User) Fields() []ent.Field {
 return []ent.Field{
  field.String("name"),
 }
}

// Edges of the User.
func (User) Edges() []ent.Edge {
 return []ent.Edge{
  edge.To("following", User.Type).
   From("followers"),
 }
}
Field {
   return []ent.Field{
      field.String("name"),
   }
}

// Edges of the User.
func (User) Edges() []ent.Edge {
   return []ent.Edge{
      edge.To("following", User.Type).
         From("followers"),
   }
}

这样会生成一个user_following表,表信息为:

CREATE TABLE `user_following` (
  `user_id` bigint(20) NOT NULL,
  `follower_id` bigint(20) NOT NULL,
  PRIMARY KEY (`user_id`,`follower_id`),
  KEY `user_following_follower_id` (`follower_id`),
  CONSTRAINT `user_following_follower_id` FOREIGN KEY (`follower_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
  CONSTRAINT `user_following_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin

其他

在这里和在Fields中同样也有Required   StorageKey  Indexes Annotations 用法基本一样,这里不再说明

延伸阅读

  • https://entgo.io/

【golang-ent】go-zero框架 整合 ent orm框架实现一对一 一对多 多种姿势查询方式 阅读详情

相关推荐

保姆级教程:用QSTEM和DrProbe搞定你的第一张STEM模拟图(附Fe3O4实例文件)

本文提供了一份详细的STEM模拟图像生成教程,涵盖从晶体结构获取到最终图像模拟的全过程。通过QSTEM和DrProbe软件的操作指南,帮助材料科学研究者快速掌握STEM模拟技术,特别适合初学者。教程包含Fe3O4实例文件,详细解析参数设置、计算优化和结果分析等关键步骤。

weixin_33730836的博客 523

Golang-Ent ORM框架

面向对象编程和关系型数据库,都是目前最流行的技术,但是它们的模型是不一样的。面向对象编程把所有实体看成对象(object),关系型数据库则是采用实体之间的关系(relation)连接数据。很早就有人提出,关系也可以用对象表达,这样的话,就能使用面向对象编程,来操作关系型数据库。简单说,ORM 就是通过实例对象的语法,完成关系型数据库的操作的技术,是"对象-关系映射"(Object/Relational Mapping) 的缩写。ORM 把数据库映射成对象。

Ch3nnn的博客 2932

AGM Supra软件从零到一:国产CPLD工程创建全流程拆解

本文详细拆解了AGM Supra软件从零开始创建国产CPLD工程的全流程,包括开发环境配置、工程创建、Quartus项目转换、TCL脚本执行与编译等关键步骤。特别强调了中文路径避坑、器件型号选择等实用技巧,帮助开发者高效完成CPLD开发任务。

weixin_29158413的博客 410

go语言ORM框架ent使用教程

ent是什么 ent是一个简单而又功能强大的Go语言实体框架,ent易于构建和维护应用程序与大数据模型。 简而言之,ent是一款便于操作的orm框架 installation go get entgo.io/ent/cmd/ent 使用 创建schema 在连接ent之前,我们首先需要创建schema,创建schema的作用类似django创建model,规定数据表字段,定义表名等 cli创建model模板命令 ent init --target <target dirpath> <Mod

爱吃回锅肉的胖子 1万+

Xshell 连接 kali 虚拟机教程

启动ssh服务,启动后重新查看ssh服务状态,如下图active(running)正常。至此便可以直接使用Xshell登录kali系统了。至此虚拟机已经可以上网。-查看ssh服务状态。

qq_40726937的博客 2219

BBR算法原理与实现深度解析

BBR算法通过重新定义拥塞控制的基本范式,为现代网络应用提供了突破性的解决方案。随着QUIC协议的普及和智能网卡技术的发展,BBR类算法将在边缘计算、云游戏、工业物联网等领域发挥更重要的作用。

程序猿老樊的博客 2418

ent orm笔记1---快速尝鲜

前几天看到消息Facebook孵化的ORM ent转为正式项目,出去好奇,简单体验了一下,使用上自己感觉比GORM好用,于是打算把官方的文档进行整理,也算是学习一下如何使用。安装ent ...

后场技术 1404

YOLO26改进策略【Neck】| 关键点检测:SDFM 表层细节融合模块,利用通道-空间注意力机制,实现深层与浅层特征融合,抑制噪声干扰

本文记录的是利用SDFM 模块改进 YOLO26 的颈部融合部分,专门用于关键点检测。SDFM模块(Surface Detail Fusion Module,表层细节融合模块) 通过在特征提取网络的浅层引入通道-空间注意力机制,动态生成深层与浅层特征融合权重。该模块可自适应保留不同模态中的独特信息,抑制背景噪声与光照干扰,实现低层细节的精准对齐与互补增强,为后续检测提供高保真度的底层特征表示,从而提升模型在复杂场景下的目标检测鲁棒性与定位准确性。Rethinking the necessity of ima

Limiiiing的博客 176

ent schema edge 表关联

关于边界。

peter_hqq的博客 437

0.1 ROCm rocr-libhsakmt实现深度剖析专栏介绍

本专栏深入解析AMD ROCm生态核心组件rocrruntime,从底层硬件交互到上层封装实现。重点剖析libhsakmt驱动层的七大核心模块设计,包括拓扑管理、队列调度、事件同步等关键机制;详解C++接口封装策略与工程实践,如资源管理、多线程优化等。通过"硬件-驱动-应用"全链路技术拆解,帮助开发者深入理解ROCm运行时机制,解决性能调优、调试等实际问题,为HPC/AI应用开发提供底层技术支撑。

图形/计算GPU的驱动与虚拟化技术分享园地 5976

【DRAM存储器四十七】LPDDR5介绍--LPDDR5的低功耗技术之DVFS

讲述LPDDR5的DVFSC和DVFSQ的工作原理和要求

highman110的博客 900

golang:ent实体框架

好烦,我就想自己使用自定义除了id字段以外的字段作为主键名!

OceanStar的博客 940

Allegro如何进行四层板板层设计

板层的设计

weixin_42499230的博客 3189

ent orm笔记2---schema使用(下)

Indexes 索引在前两篇的文章中,其实对于索引也有一些使用, 这里来详细看一下关于索引的使用Indexes方法可以在一个或者多个字段上设置索引,以提高数据检索的速度或者定义数据的唯一...

后场技术 769

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

搞懂常见Go ORM系列-Ent框架详解

Ent 是一个用于 Go 语言的 ORM(对象关系映射)框架它的最大特点是通过代码生成的方式,提供类型安全的数据库访问能力在使用 Ent 时,首先需要定义 schema,然后通过工具生成数据库访问代码,这样不仅提高了开发效率,还能避免常见的运行时错误Ent 支持多种关系型数据库,包括 MySQL、PostgreSQL、SQLite 和 Microsoft SQL Server,并且对数据库结构和关系的支持非常全面在使用 Ent 时,开发者需要先定义 schema,这是 Ent 中模型的基础。

2401_89221445的博客 2279

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

Golang微服框架Kratos与它的小伙伴系列 - ORM框架 - Ent

Golang ORM框架Ent简介 Ent是Facebook开源的一款Go语言ORM框架,通过代码生成实现数据库操作。它将数据库表映射为Schema(类),记录为对象,字段为属性,使开发者能够使用面向对象语法操作关系型数据库。 Ent核心特点: 基于代码生成实现静态类型安全 支持多种数据库(MySQL/PostgreSQL/SQLite/Gremlin) 提供Schema定义和CRUD API 可通过Mixin复用公共字段 Ent工具链包括: entc命令行工具:用于生成数据库操作代码 Schema定义:描

喵个咪的专栏 1107

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

ent4/ent比较分析:与其他ORM框架的优劣对比

在现代软件开发中,对象关系映射(ORM,Object-Relational Mapping)框架扮演着至关重要的角色,它能够简化数据访问层的开发,提高开发效率,同时减少手动编写SQL的错误。ent4/ent作为Go语言生态中一款新兴的ORM框架,以其独特的设计理念和强大的功能受到了广泛关注。本文将从多个维度对ent4/ent与其他主流ORM框架进行深入比较,分析其优势与不足,帮助开发者做出更合适的...

gitblog_00345的博客 462

go ent框架使用

一、前提提要 1、ent框架:是一个操控数据库的orm框架,类似python中的sqlalchemy来操作数据库 2、据说非常适合处理各种复杂关系(我也不知道是真是假,不过好用是真的) 3、安装:go get entgo.io/ent/cmd/entc 4、引用别人的一个概念: (1)Schema:描述一个实体的定义以及他与其他实体的关系,类似python里用sqlalchemy创建的modul,就是数据表的一个描述 (2)Edges:实体与实体之间的关系称为edge 4、常用命令: 创建一

weixin_48609908的博客 4732

Go Ent 简介

Go Ent 简介

闲余知道 1482

Golang ORM ent

ent 是一个简单而又强大的Go实体框架 简单地使用数据库结构作为图结构。 使用Go代码定义结构 基于代码生成的静态类型 容易地进行数据库查询和图遍历 容易地使用Go模板扩展和自定义 应用场景 ent非常适合处理各种复杂的关系,定义好实体和实体之间的关系,就可以快速得到各种想要的数据 核心概念 Schema: 描述一个实体的定义以及他与其他实体的关系 Edges:实体与实体之间的关系称为边 ===>edge 使用步骤 安装 go get entgo.io/ent/cmd/ent 创

qq_39297673的博客 1106

终极ent迁移指南:从其他ORM快速切换到ent的完整步骤

ent是Go语言中简单而强大的实体框架,让构建和维护大型数据模型的应用变得轻松。如果你正在使用其他ORM(如GORM、sqlx或标准库database/sql),本文将为你提供从其他ORM迁移到ent的完整指南。 ## 为什么要从其他ORM迁移到ent? 🚀 ent提供了许多其他ORM不具备的优势: - **代码即架构** - 将任何数据库架构建模为Go对象 - **轻松遍历任何图形**

gitblog_00904的博客 640

超强ent4/ent框架:代码生成驱动的静态类型ORM新范式

你还在为手写SQL、处理复杂数据关系而烦恼吗?ent4/ent框架通过代码生成和静态类型检查,让数据访问层开发效率提升10倍!本文将带你快速掌握这一革命性ORM工具的核心优势、5分钟上手流程及实战技巧,让你彻底告别重复劳动,专注业务逻辑开发。 ## 核心特性一览 ent4/ent作为Go语言生态中领先的ORM框架,凭借代码生成驱动和静态类型安全两大核心优势,彻底改变了传统ORM的开发模式。以下...

gitblog_00215的博客 703

Flash-Attention的PyTorch与CUDA版本兼容修复:从安装OOM到稳定跑通

凌晨一点,你执行 `pip install flash-attn --no-build-isolation`,进度条卡在 68%,终端滚出 `nvcc fatal: out of memory`,而下午刚升级过的 torch 又让旧装的 flash-attn 抛 `undefined symbol`。这两个报错背后是同一条依赖链:flash-attn、PyTorch、CUDA 工具链、GPU 架构

gitblog_01153的博客 551

ent 框架研究报告

• ent/generate.go 使用 go run -mod=mod entgo.io/ent/cmd/ent generate ./schema,符合。• ent/schema/shop.go 使用 uid、title、price、stock;• 本地项目文件:go.mod、ent/generate.go、ent/schema、internal/database/mysql.go、• ent 官方 Transactions 文档:https://entgo.io/docs/transactions/

zffggkhzjdt的博客 177

Ent框架实战:从表结构到订单增删改查

服务端口、MySQL 连接池、Redis 连接池、登录 token 有效期、Nacos 参数都统一放在 common/config/config.yaml,并由 common/config/config.go 接收。写一个表时,通常先在 ent/schema 下创建对应文件,再在 Fields 方法里写字段、类型、约束、默认值和备注。生成文件主要被调用,不写业务;main.go 启动后先调用 appinit.Init(ctx),这个函数把配置读取、MySQL 连接、Ent 迁移、Redis 连接串起来。

2603_95046224的博客 358

Ent项目:自动生成GraphQL过滤器指南

Ent项目:自动生成GraphQL过滤器指南 【免费下载链接】ent ent: 是一个基于 Go 语言的轻量级 ORM 库,用于处理关系型数据库。适合开发者使用 ent 进行数据库访问和操作。 项目地址: https://gitc...

gitblog_00759的博客 375
上一篇: ent orm笔记1---快速尝鲜
下一篇: ent orm笔记2---schema使用(下)
后场技术
博客等级 码龄11年 156粉丝 46原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值