Prepared statements in C++ libneo4j_client?

307 views Asked by At

The neo4j_run API allows you to enter a map, but I don't know the syntax of the query. In python, this is a simple {x}. I cannot find an example of the neo4j_map syntax.

const char *q = "MATCH (p:Person) WHERE p.age > {age} RETURN p.name AS name, p.age as AGE";
neo4j_run(session, q, my_map)

How should I (a) construct my_map and (b) indicate the fields in the query?

UPDATE: For the first part, this test shows how to construct the map. Copied here for clarity:

START_TEST (invalid_map_value)
{
    neo4j_map_entry_t map_entries[] =
        { { .key = neo4j_string("bernie"), .value = neo4j_int(1) },
          { .key = neo4j_int(1), .value = neo4j_int(2) } };
    neo4j_value_t value = neo4j_map(map_entries, 2);
    ck_assert(neo4j_is_null(value));
    ck_assert_int_eq(errno, NEO4J_INVALID_MAP_KEY_TYPE);
}
END_TEST
1

There are 1 answers

6
Chris Leishman On BEST ANSWER

The map passed as the third argument to neo4j_run is the parameters for the query. Constructing the map takes an array of entries and its length. If it's just a single entry map, you could pass a pointer to a single neo4j_map_entry_t. For your example:

const char *q = "MATCH (p:Person) WHERE p.age > {age} RETURN p.name AS name, p.age as AGE";
neo4j_map_entry_t map_entry = neo4j_map_entry("age", 28);
neo4j_value_t params = neo4j_map(&map_entry, 1);

neo4j_run(session, q, params);

If there are multiple parameters, build an array of map entries, e.g.:

const char *q = "MATCH (p:Person) WHERE {min_age} < p.age < {max_age} RETURN p.name AS name, p.age as AGE";
neo4j_map_entry_t map_entries[2];
map_entries[0] = neo4j_map_entry("min_age", 28);
map_entries[1] = neo4j_map_entry("max_age", 30);
neo4j_value_t params = neo4j_map(map_entries, 2);

neo4j_run(session, q, params);

You can also build the map_entry_t using an initializer, as in the example test you copied. But it's usually clearer to use the neo4j_map_entry constructor.