diff --git a/collector/pg_stat_archiver_lag.go b/collector/pg_stat_archiver_lag.go index 7cc489479..d74a4c10e 100644 --- a/collector/pg_stat_archiver_lag.go +++ b/collector/pg_stat_archiver_lag.go @@ -46,7 +46,7 @@ var ( statArchiverLagQuery = ` SELECT last_archived_wal, - pg_current_wal_lsn() AS current_lsn + CASE WHEN pg_is_in_recovery() THEN NULL ELSE pg_current_wal_lsn() END AS current_lsn FROM pg_stat_archiver WHERE last_archived_wal IS NOT NULL AND last_archived_wal != '' diff --git a/collector/pg_stat_archiver_lag_test.go b/collector/pg_stat_archiver_lag_test.go index e80d7d141..ff3cba116 100644 --- a/collector/pg_stat_archiver_lag_test.go +++ b/collector/pg_stat_archiver_lag_test.go @@ -263,3 +263,43 @@ func TestBytesBetweenLSN(t *testing.T) { }) } } + +func TestPGStatArchiverLagCollectorReplica(t *testing.T) { + db, mock, err := sqlmock.New() + if err != nil { + t.Fatalf("Error opening a stub db connection: %s", err) + } + defer db.Close() + + inst := &Instance{db: db} + + columns := []string{"last_archived_wal", "current_lsn"} + // Simulate replica where current_lsn is NULL (which is what the query returns when in recovery) + rows := sqlmock.NewRows(columns). + AddRow("000000010000000000000001", nil) + mock.ExpectQuery(sanitizeQuery(statArchiverLagQuery)).WillReturnRows(rows) + + ch := make(chan prometheus.Metric) + go func() { + defer close(ch) + c := PGStatArchiverLagCollector{} + + if err := c.Update(context.Background(), inst, ch); err != nil { + t.Errorf("Error calling PGStatArchiverLagCollector.Update: %s", err) + } + }() + + expected := []MetricResult{ + {labels: labelMap{}, value: 0, metricType: dto.MetricType_GAUGE}, + } + + convey.Convey("Metrics comparison", t, func() { + for _, expect := range expected { + m := readMetric(<-ch) + convey.So(expect, convey.ShouldResemble, m) + } + }) + if err := mock.ExpectationsWereMet(); err != nil { + t.Errorf("there were unfulfilled exceptions: %s", err) + } +}