登录
首页 >  Golang >  Go问答

如何正确处理数据库查询中的空值

来源:stackoverflow

时间:2024-03-26 11:06:44 344浏览 收藏

在处理数据库查询中的空值时,本文介绍了两种方法。第一种方法使用 pgtype 库,但其实现笨重且存在错误。第二种方法建议使用表视图中的 coalesce 函数或实现自定义的 sql.scanner,后者允许在扫描时直接设置模型字段。这提供了更简洁和更惯用的解决方案,避免了处理空值的复杂性。

问题内容

我正在 go 中处理多对多关系。为此,我使用 pgx postgresql 驱动程序。

为了使这个问题尽可能简单,我们假设一篇可以包含一些标签的简单博客文章:

create table if not exists tag (
    id bigint generated by default as identity primary key,
    tagname varchar(255) unique not null,
);

create table if not exists post (
    id bigint generated by default as identity primary key,
    title varchar(255) not null,
    description varchar(255),
);

create table if not exists post_tag (
    post_id bigint references post (id) on update cascade on delete cascade,
    tag_id bigint references tag (id) on update cascade on delete cascade,
    constraint post_tag_pkey primary key (post_id, tag_id)
);

为了检索帖子及其标签,我使用类似以下查询的内容(在 go 中轻松查询的视图中):

select p.id as post_id, p.title, p.description, t.id as tag_id, t.tagname as tag_name
    from post p 
    left join post_tag pt
    on p.id = pt.post_id
    left join tag t 
    on t.id = pt.tag_id;

此查询可能会返回一些 tag_idtag_name 为空的行。我目前处理此问题的方式如下(为了简单起见,删除了错误处理):

func ReadPosts() ([]*model.Post, error) {
    var posts []*model.Post
    var postWithTags = make(map[uint64]*model.Post)

    statement := `SELECT *
                    FROM post_with_tag` // pgsql view with joins to get tags

    rows, _ := db.Query(
        context.Background(),
        statement,
    )

    for rows.Next() {
        var (
            post     model.Post
            tag      model.Tag
            tagID    pgtype.Numeric
            tagName  pgtype.Varchar
            tagValid bool
        )

        _ = rows.Scan(
            &post.ID,
            &post.Title,
            &post.Description,
            &tagID,
            &tagName,
        )

        if tagID.Status == pgtype.Present {
            tag.ID = tagID.Int.Uint64()
            tag.Name = tagName.String
            tagValid = true
        } else {
            tagValid = false
        }

        if _, ok := postWithTags[post.ID]; ok {
            if tagValid {
                postWithTags[post.ID].Tags = append(postWithTags[post.ID].Tags, &tag)
            }
        } else {
            post.Tags = []*model.Tag{}

            if tagValid {
                post.Tags = []*model.Tag{
                    &tag,
                }
            }

            postWithTags[post.ID] = &post
        }
    }

    for _, v := range postWithTags {
        posts = append(posts, v)
    }

    return posts, nil
}

如您所见,我使用 pgtype 来处理潜在的空值。我应该提到这个解决方案有效。但是,我有两个问题:

  1. 这个解决方案看起来相当笨重和混乱;读起来很复杂(至少对我来说)。 是否有更好、更惯用的 go 方式来做到这一点?
  2. 当调用 tagid.int.uint64() 时,我总是返回 0 作为标签 id,这是不正确的。 我在这里做错了什么吗?(我使用 pgtype.numeric 因为数据库中的标签 id 是 pgsql bigint)。

解决方案


如果您使用的是表视图,并且不需要按 null 进行过滤(例如 where col is [not] null),那么您可能只想在视图中使用 coalesce ,这样您可以节省一些时间go 端头疼。如果您直接处理表,您仍然可以在您在 go 中构建的 sql statement 字符串中使用 coalesce,但是如果您选择这样做,您将无法将其与 select * 一起使用,而是您必须明确列出列。

如果您不喜欢 coalesce 方法,您可以实现自己的 sql.scanner ,它没有值字段,而是有一个指针字段,然后允许您在同一行通过间接设置模型字段您正在扫描列的那个。

_ = rows.scan(
    &post.id,
    &post.title,
    &post.description,
    mynullnumeric{&tag.id},
    mynullstring{&tag.name},
)

mynullxxx 可能如下所示:

type MyNullString struct {
    Ptr *string
}

func (ns MyNullString) Scan(src interface{}) error {
    switch v := src.(type) {
    case string:
        *ns.Ptr = v
    case []byte:
        *ns.Ptr = string(v)
    case nil:
        // nothing
    default:
        // maybe nothing or error, up to you
    }
    return nil
}

今天关于《如何正确处理数据库查询中的空值》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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