Skip to content

Commit

Permalink
crdb: stats should use follower reads
Browse files Browse the repository at this point in the history
  • Loading branch information
ecordell committed Jul 7, 2023
1 parent 9903c5e commit 5c43850
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions internal/datastore/crdb/stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,37 +26,42 @@ const (

var (
queryReadUniqueID = psql.Select(colUniqueID).From(tableMetadata)
queryRelationshipEstimate = fmt.Sprintf("SELECT COALESCE(SUM(%s), 0) FROM %s", colCount, tableCounters)
queryRelationshipEstimate = fmt.Sprintf("SELECT COALESCE(SUM(%s), 0) FROM %s AS OF SYSTEM TIME follower_read_timestamp()", colCount, tableCounters)

upsertCounterQuery = psql.Insert(tableCounters).Columns(
colID,
colCount,
).Suffix(fmt.Sprintf("ON CONFLICT (%[1]s) DO UPDATE SET %[2]s = %[3]s.%[2]s + EXCLUDED.%[2]s RETURNING cluster_logical_timestamp()", colID, colCount, tableCounters))

rng = rand.NewSource(time.Now().UnixNano())

uniqueID string
)

func (cds *crdbDatastore) Statistics(ctx context.Context) (datastore.Stats, error) {
sql, args, err := queryReadUniqueID.ToSql()
if err != nil {
return datastore.Stats{}, fmt.Errorf("unable to prepare unique ID sql: %w", err)
if len(uniqueID) == 0 {
sql, args, err := queryReadUniqueID.ToSql()
if err != nil {
return datastore.Stats{}, fmt.Errorf("unable to prepare unique ID sql: %w", err)
}
if err := cds.readPool.QueryRowFunc(ctx, func(ctx context.Context, row pgx.Row) error {
return row.Scan(&uniqueID)
}, sql, args...); err != nil {
return datastore.Stats{}, fmt.Errorf("unable to query unique ID: %w", err)
}
}

var uniqueID string
var nsDefs []datastore.RevisionedNamespace
var relCount uint64

if err := cds.readPool.BeginTxFunc(ctx, pgx.TxOptions{AccessMode: pgx.ReadOnly}, func(tx pgx.Tx) error {
if err := tx.QueryRow(ctx, sql, args...).Scan(&uniqueID); err != nil {
return fmt.Errorf("unable to query unique ID: %w", err)
}

if err := tx.QueryRow(ctx, queryRelationshipEstimate).Scan(&relCount); err != nil {
return fmt.Errorf("unable to read relationship count: %w", err)
}

var err error
nsDefs, err = loadAllNamespaces(ctx, pgxcommon.QuerierFuncsFor(tx), func(sb squirrel.SelectBuilder, fromStr string) squirrel.SelectBuilder {
return sb.From(fromStr)
return sb.From(fromStr + "AS OF SYSTEM TIME follower_read_timestamp()")
})
if err != nil {
return fmt.Errorf("unable to read namespaces: %w", err)
Expand Down

0 comments on commit 5c43850

Please sign in to comment.