everytab/pipeline/05_bundle_gen/db.go

48 lines
1.5 KiB
Go

package main
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
type HostRow struct {
ID int64
Hostname string
Protocol string
HtmlTitle string
IframeAllowed bool
BestIconHash string
RandomOrder float64
IconDownloadedAt *time.Time
}
// fetchHostsPage gets a page of hosts with titles, ordered by icon_downloaded_at for disk locality.
// Icons written to disk at similar times are physically adjacent — reading in write order
// maximizes OS readahead cache hits. Hosts without icons come last (no disk reads needed).
// random_order is included for bundle bucket assignment (randomized bundles).
func fetchHostsPage(ctx context.Context, pool *pgxpool.Pool, lastDownloaded *time.Time, lastID int64, limit int) ([]HostRow, error) {
rows, err := pool.Query(ctx, `
SELECT id, hostname, protocol, html_title, COALESCE(iframe_allowed, true), COALESCE(best_icon_hash, ''), random_order, icon_downloaded_at
FROM hosts
WHERE html_title IS NOT NULL
AND (icon_downloaded_at, id) > ($1, $2)
ORDER BY icon_downloaded_at NULLS LAST, id
LIMIT $3
`, lastDownloaded, lastID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var hosts []HostRow
for rows.Next() {
var h HostRow
if err := rows.Scan(&h.ID, &h.Hostname, &h.Protocol, &h.HtmlTitle, &h.IframeAllowed, &h.BestIconHash, &h.RandomOrder, &h.IconDownloadedAt); err != nil {
return nil, err
}
hosts = append(hosts, h)
}
return hosts, rows.Err()
}