diff --git a/quota/mysqlqm/mysql_quota.go b/quota/mysqlqm/mysql_quota.go index 1e288b5009..e2cade5d6e 100644 --- a/quota/mysqlqm/mysql_quota.go +++ b/quota/mysqlqm/mysql_quota.go @@ -19,6 +19,8 @@ import ( "context" "database/sql" "errors" + "fmt" + "strconv" "github.com/google/trillian/quota" ) @@ -97,6 +99,10 @@ func (m *QuotaManager) countUnsequenced(ctx context.Context) (int, error) { } func countFromInformationSchema(ctx context.Context, db *sql.DB) (int, error) { + // turn off statistics caching for MySQL 8 + if err := turnOffInformationSchemaCache(ctx, db); err != nil { + return 0, err + } // information_schema.tables doesn't have an explicit PK, so let's play it safe and ensure // the cursor returns a single row. rows, err := db.QueryContext(ctx, countFromInformationSchemaQuery, "Unsequenced", "BASE TABLE") @@ -124,3 +130,29 @@ func countFromTable(ctx context.Context, db *sql.DB) (int, error) { } return count, nil } + +// turnOffInformationSchemaCache turn off statistics caching for MySQL 8 +// To always retrieve the latest statistics directly from the storage engine and bypass cached values, set information_schema_stats_expiry to 0. +// See https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_information_schema_stats_expiry +func turnOffInformationSchemaCache(ctx context.Context, db *sql.DB) error { + opt := "information_schema_stats_expiry" + res := db.QueryRowContext(ctx, "SHOW VARIABLES LIKE '%"+opt+"%'") + var none, expiry string + err := res.Scan(&none, &expiry) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil + } + + return fmt.Errorf("Failed to get variable %q: %v", opt, err) + } + + exp, err := strconv.Atoi(expiry) + if err != nil || exp != 0 { + if _, err := db.ExecContext(ctx, "SET SESSION "+opt+"=0"); err != nil { + return fmt.Errorf("Failed to set variable %q: %v", opt, err) + } + } + + return nil +}