dtncv04228 2019-07-11 11:39
浏览 38

控制SQLX中的查询结果流(延迟/渴望)

I'm implementing a messages table with postgres (aws-rds) and I'm using golang as a backend to query the table.

CREATE TABLE:

CREATE TABLE IF NOT EXISTS msg.Messages(
    id SERIAL PRIMARY KEY,
    content BYTEA,
    timestamp DATE
);

Here is the INSERT query:

INSERT INTO msg.Messages (content,timestamp) VALUES ('blob', 'date')
RETURNING id;

Now I want to be able to fetch a specific message, like this:

specific SELECT query:

SELECT id, content,timestamp
FROM msg.Messages
WHERE id = $1

Now let's say the user was offline for a long time and he needs to get a lot of messages from this table, let's say 10M messages, I don't want to return all results because it might explode the app memory.

each user saves his last message.id that he fetched, so the query will be:

SELECT id, content, timestamp
FROM msg.Messages
WHERE id > $1

Implementing paging in this query is feeling like inventing the wheel again, there must be out of the box solution for that.

I'm using sqlx, here is a rough example of my code:

query := `
        SELECT id, content, timestamp
        FROM msg.Messages
        WHERE id > $0
    `

args = 5
query = ado.db.Rebind(query)
rows, err := ado.db.Queryx(query, args...)
var res []Message

for rows.Next() {
    msg := Message{}
    err = rows.StructScan(&msg)
    if err != nil {
        return nil, err
    }
    res = append(res, msg)
}

return res, nil

How can I convert this code to be with lazy loading, that only on rows.next() will fetch the next item (and not loading all items in advance), and what about the garbage collector, will it release the memory on each iteration of the row.next()??

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 基于卷积神经网络的声纹识别
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
    • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
    • ¥15 CSAPPattacklab
    • ¥15 一直显示正在等待HID—ISP
    • ¥15 Python turtle 画图
    • ¥15 stm32开发clion时遇到的编译问题