Skip to content

Instantly share code, notes, and snippets.

@greenrobot
Created January 12, 2022 08:00
Show Gist options
  • Save greenrobot/552f560a92737ec045b0efdc2122fd62 to your computer and use it in GitHub Desktop.
Save greenrobot/552f560a92737ec045b0efdc2122fd62 to your computer and use it in GitHub Desktop.
Example of how to put, query and remove many-to-many database relations using ObjectBox C API
TEST_CASE("C-Box-relations", "") {
CTestEnv env;
env.enableManyEntity();
obx_schema_id test_id = obx_store_entity_id(env.store(), "TestEntityCpp");
obx_id ta_id = env.putTestEntity(0, "ta");
obx_id tb_id = env.putTestEntity(0, "tb");
obx_id tc_id = env.putTestEntity(0, "tc");
REQUIRE(ta_id == 1);
obx_schema_id many_id = obx_store_entity_id(env.store(), "ManyEntityCpp");
OBX_box* manyBox = obx_box(env.store(), many_id);
// skip the first 3 so that the IDs don't overlap
// NOTE rel_put doesn't validate if the src/target ID exists now but it may in the future
// so having distinct IDs would help ensure the tests are good
env.putManyEntity(0, "");
env.putManyEntity(0, "");
env.putManyEntity(0, "");
env.txSuccess();
REQUIRE_OBX_OK(obx_box_remove_all(manyBox, nullptr));
obx_id ma_id = env.putManyEntity(0, "ma");
obx_id mb_id = env.putManyEntity(0, "mb");
obx_id mc_id = env.putManyEntity(0, "mc");
env.txSuccess();
REQUIRE(ma_id == 4);
// Put relations: 3 from "ma", and from "mb" to "tb"
REQUIRE(obx_box_rel_put(manyBox, 1, ma_id, ta_id) == OBX_SUCCESS);
REQUIRE(obx_box_rel_put(manyBox, 1, ma_id, tb_id) == OBX_SUCCESS);
REQUIRE(obx_box_rel_put(manyBox, 1, ma_id, tc_id) == OBX_SUCCESS);
REQUIRE(obx_box_rel_put(manyBox, 1, mb_id, tb_id) == OBX_SUCCESS);
// Verify regular direction from "ma"
OBX_id_array* data0 = obx_box_rel_get_ids(env.box(), env.manyRelationId(), ma_id);
REQUIRE(data0);
REQUIRE(data0->count == 3);
REQUIRE(data0->ids[0] == ta_id);
REQUIRE(data0->ids[1] == tb_id);
REQUIRE(data0->ids[2] == tc_id);
obx_id_array_free(data0);
// Verify backlink direction from "tb"
OBX_id_array* dataBack = obx_box_rel_get_backlink_ids(manyBox, env.manyRelationId(), tb_id);
REQUIRE(dataBack);
REQUIRE(dataBack->count == 2);
REQUIRE(dataBack->ids[0] == ma_id);
REQUIRE(dataBack->ids[1] == mb_id);
obx_id_array_free(dataBack);
// Remove one relation (from "ma" to "tb") and test updated regular results from "ma"
obx_box_rel_remove(manyBox, 1, ma_id, tb_id);
OBX_id_array* data1 = obx_box_rel_get_ids(env.box(), env.manyRelationId(), ma_id);
REQUIRE(data1);
REQUIRE(data1->count == 2);
REQUIRE(data1->ids[0] == ta_id);
REQUIRE(data1->ids[1] == tc_id);
obx_id_array_free(data1);
// Verify updated backlink direction from "tb" to "mb"
dataBack = obx_box_rel_get_backlink_ids(manyBox, env.manyRelationId(), tb_id);
REQUIRE(dataBack);
REQUIRE(dataBack->count == 1);
REQUIRE(dataBack->ids[0] == mb_id);
obx_id_array_free(dataBack);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment