diff --git a/CHANGELOG.md b/CHANGELOG.md index 8698e8fb7d8..7e02a59cd4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ ### Enhancements -* None. +* Added `Table::get_link_type()` as a helper method for getting the link type from link columns. PR [#2987](https://github.com/realm/realm-core/pull/2987). ----------- diff --git a/src/realm/data_type.hpp b/src/realm/data_type.hpp index 0ba78c8bdc5..081c459992f 100644 --- a/src/realm/data_type.hpp +++ b/src/realm/data_type.hpp @@ -19,6 +19,8 @@ #ifndef REALM_DATA_TYPE_HPP #define REALM_DATA_TYPE_HPP +#include + namespace realm { class StringData; diff --git a/src/realm/table.cpp b/src/realm/table.cpp index bd008c8c20c..99d5633af1e 100644 --- a/src/realm/table.cpp +++ b/src/realm/table.cpp @@ -1841,6 +1841,18 @@ bool Table::is_nullable(size_t col_ndx) const m_spec->get_column_type(col_ndx) == col_type_Link; } +LinkType Table::get_link_type(size_t col_ndx) const +{ + if (!is_attached()) { + throw LogicError{LogicError::detached_accessor}; + } + if (!(m_spec->get_column_type(col_ndx) == col_type_Link) && !(m_spec->get_column_type(col_ndx) == col_type_LinkList)) { + throw LogicError{LogicError::illegal_type}; + } + REALM_ASSERT_DEBUG(col_ndx < m_spec->get_column_count()); + return (m_spec->get_column_attr(col_ndx) & col_attr_StrongLinks) ? LinkType::link_Strong : LinkType::link_Weak; +} + const ColumnBase& Table::get_column_base(size_t ndx) const noexcept { REALM_ASSERT_DEBUG(ndx < m_spec->get_column_count()); diff --git a/src/realm/table.hpp b/src/realm/table.hpp index 5f92a9db9c4..c85fec1918f 100644 --- a/src/realm/table.hpp +++ b/src/realm/table.hpp @@ -164,6 +164,10 @@ class Table { // Whether or not elements can be null. bool is_nullable(size_t col_ndx) const; + // Returns the link type for the given column. + // Throws an LogicError if target column is not a link column. + LinkType get_link_type(size_t col_ndx) const; + //@{ /// Conventience functions for inspecting the dynamic table type. /// diff --git a/test/test_table.cpp b/test/test_table.cpp index fe0413b4702..52a95c9bdfa 100644 --- a/test/test_table.cpp +++ b/test/test_table.cpp @@ -8363,4 +8363,26 @@ TEST(Table_KeyRow) CHECK_EQUAL(i, 1); } +TEST(Table_getLinkType) +{ + Group g; + TableRef table = g.add_table("table"); + + table->add_column(type_Int, "int"); + table->add_column_link(type_Link, "weak_link", *table); + table->add_column_link(type_Link, "strong_link", *table, link_Strong); + table->add_column_link(type_LinkList, "weak_list", *table); + table->add_column_link(type_LinkList, "strong_list", *table, link_Strong); + + CHECK(link_Weak == table->get_link_type(1)); + CHECK(link_Strong == table->get_link_type(2)); + CHECK(link_Weak == table->get_link_type(3)); + CHECK(link_Strong == table->get_link_type(4)); + + CHECK_THROW(table->get_link_type(0), LogicError); + + g.remove_table("table"); + CHECK_THROW(table->get_link_type(1), LogicError); +} + #endif // TEST_TABLE