登录
首页 >  Golang >  Go问答

将SQL语句转换为Go对象

来源:stackoverflow

时间:2024-03-19 20:54:32 478浏览 收藏

在使用 pgx 与 PostgreSQL 交互时,将数据库中的行转换为聚合结构可能是一个挑战。特别是当涉及到使用值对象时,导出字段并不是一个理想的做法。为了解决这一问题,可以使用一种方法,其中使用 Scan() 函数将行的列值提取到临时变量中,然后使用这些变量来创建聚合结构的实例。这可以确保值对象的私有值不会被直接暴露,同时仍然允许将行数据转换为所需的格式。

问题内容

您好,我正在使用 pgx 来使用我的 postgres,我对如何将数据库中的行转换为聚合有疑问

我正在使用实体和值对象 没有值对象,使用元帅似乎很容易,但是使用值对象我认为导出字段不是一个好主意,然后我的问题出现了,如何将我的行转换为聚合的结构

我的汇总:

type email struct {
    address string
}

type password struct {
    value string
}

type name struct {
    firstname string
    lastname  string
}

type person struct {
    id       string
    name     valueobject.name
    email    valueobject.email
    password valueobject.password
    created  time.time
    updated  time.time
}

func newperson(name valueobject.name, email valueobject.email, password valueobject.password) *person {
    id := uuid.new()
    return &person{
        id:       id.string(),
        name:     name,
        email:    email,
        password: password,
        created:  time.now(),
        updated:  time.now(),
    }
}

我所有的值对象都有一个通过模拟 get 的函数来获取私有值的方法,我没有放置值对象的其余代码,这样它就不会变大

从表中获取所有行的函数:

func (r *personRepository) GetAll() (persons []*entities.Person, err error) {
    qry := `select id, first_name, last_name, email, password created_at, updated_at from persons`
    rows, err := r.conn.Query(context.Background(), qry)

    return nil, fmt.Errorf("err")
}

如果有人可以让我了解如何使用此值对象将这一行从银行传递到我的聚合结构


正确答案


您可以使用这样的东西(尚未测试,需要优化):

func (r *personRepository) GetAll() (persons []*entities.Person, err error) {
    qry := `select id, first_name, last_name, email, password, created_at, updated_at from persons`
    rows, err := r.conn.Query(context.Background(), qry)

  var items []*entities.Person
  if err != nil {
    // No result found with the query.
    if err == pgx.ErrNoRows {
        return items, nil
    }
    
    // Error happened
    log.Printf("can't get list person: %v\n", err)
    return items, err
  }

  defer rows.Close()

  for rows.Next() {
    // Build item Person for earch row.
    // must be the same with the query column position.

    var id, firstName, lastName, email, password string
    var createdAt, updatedAt time.Time
    
    err = rows.Scan(&id, &firstName, &lastName, &email,
                    &createdAt, updatedAt)
    if err != nil {
        log.Printf("Failed to build item: %v\n", err)
        return items, err
    }

    item := &entities.Person{
      Id: id,
      FirstName: firstName,
      // fill other value
    }

    // Add item to the list.
    items = append(items, item)
  }

  return items, nil
}

不要忘记在查询中的文本 password 后面添加逗号。

我正在使用没有值对象的实体和值对象,使用 marshal、 似乎很容易

抱歉,我不知道您问题中的值对象。

好了,本文到此结束,带大家了解了《将SQL语句转换为Go对象》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>