str is null. Is there any particular reason for this di" /> str is null. Is there any particular reason for this di" /> str is null. Is there any particular reason for this di"/>

hiredis C API : reply for HMSET vs HSET

398 Views Asked by At

When I execute HMSET the reply contains string "OK" in success case. However with HSET, reply->str is null. Is there any particular reason for this difference?

In case of error, both seems to give error string in reply.

I wanted to confirm what are the checks to be done to ensure command was successfully executed. Is below correct?

  • HMSET:
    • reply should not be null.
    • reply->str should be 'OK'.
  • HSET:
    • reply should not be null.
    • reply->str should be null.

Output:

# gcc redis.c -lhiredis
# ./a.out
Connected to redis localhost
Correct commands:
[HMSET] Reply: OK
[HSET] Reply: (null)

Wrong commands:
[HMSET] Reply: ERR wrong number of arguments for 'hmset' command
[HSET] Reply: ERR wrong number of arguments for 'hset' command
#

Code:

# cat redis.c
#include <stdio.h>
#include <hiredis/hiredis.h>

void main(int argc, char **argv)
{
    redisContext *c;
    redisReply *reply;
    const char *hostname = "localhost";
    struct timeval timeout = { 1, 500000 };

    c = redisConnectWithTimeout(hostname, 6379, timeout);
    if (c == NULL || c->err) {
        if (c) {
            printf("Connection error: %s\n", c->errstr);
            redisFree(c);
        } else {
            printf("Connection error: can't allocate redis context\n");
        }
        return;
    }
    printf("Connected to redis %s\n", hostname);

    /* Correct commands */
    printf("Correct commands:\n");
    reply = redisCommand(c,"HMSET testKey name value");
    printf("[HMSET] Reply: %s\n", reply->str);
    freeReplyObject(reply);

    reply = redisCommand(c,"HSET testKey name value");
    printf("[HSET] Reply: %s\n", reply->str);
    freeReplyObject(reply);

    /* Wrong commands */
    printf("\nWrong commands:\n");
    reply = redisCommand(c,"HMSET testKey name");
    printf("[HMSET] Reply: %s\n", reply->str);
    freeReplyObject(reply);

    reply = redisCommand(c,"HSET testKey name");
    printf("[HSET] Reply: %s\n", reply->str);
    freeReplyObject(reply);
}
1

There are 1 best solutions below

0
Frank Yellin On

The documentation for HSET says that it returns the integer number of fields that were added. If you are modifying a field rather than adding a field, it will return 0. You should not be looking at it as a string.

The documentation for HMSET says that it returns "OK" or an error message