Grab a timestamp and WAL segment name after the end of the backup: this is a point in time to which
        we must be able to recover to, and the last WAL segment that is required for the backup to be
        consistent.

        Note that pg_switch_xlog()/pg_switch_wal() is a superuser-only function, but since pg_start_backup() and
        pg_stop_backup() cause an WAL switch we'll call them instead.  The downside is an unnecessary
        checkpoint.

def get_backup_end_segment_and_time(self, db_conn, backup_mode):
        """Grab a timestamp and WAL segment name after the end of the backup: this is a point in time to which
        we must be able to recover to, and the last WAL segment that is required for the backup to be
        consistent.

        Note that pg_switch_xlog()/pg_switch_wal() is a superuser-only function, but since pg_start_backup() and
        pg_stop_backup() cause an WAL switch we'll call them instead.  The downside is an unnecessary
        checkpoint.
        """
        cursor = db_conn.cursor()

        # Get backup end time and end segment and forcibly register a transaction in the current segment
        # Note that we can't call pg_walfile_name() or pg_current_wal_lsn() in recovery
        cursor.execute("SELECT now(), pg_is_in_recovery()")
        backup_end_time, in_recovery = cursor.fetchone()
        if in_recovery:
            db_conn.commit()
            return None, backup_end_time

        if self.pg_version_server >= 100000:
            cursor.execute("SELECT pg_walfile_name(pg_current_wal_lsn()), txid_current()")
        else:
            cursor.execute("SELECT pg_xlogfile_name(pg_current_xlog_location()), txid_current()")
        backup_end_wal_segment, _ = cursor.fetchone()
        db_conn.commit()

        # Now force switch of the WAL segment to make sure we have archived a segment with a known
        # timestamp after pg_stop_backup() was called.
        backup_end_name = "pghoard_end_of_backup"
        if backup_mode == "non-exclusive":
            cursor.execute("SELECT pg_start_backup(%s, true, false)", [backup_end_name])
            cursor.execute("SELECT pg_stop_backup(false)")
        elif backup_mode == "pgespresso":
            cursor.execute("SELECT pgespresso_start_backup(%s, false)", [backup_end_name])
            backup_label = cursor.fetchone()[0]
            cursor.execute("SELECT pgespresso_stop_backup(%s)", [backup_label])
        else:
            cursor.execute("SELECT pg_start_backup(%s)", [backup_end_name])
            cursor.execute("SELECT pg_stop_backup()")
        db_conn.commit()

        return backup_end_wal_segment, backup_end_time