add src/ikarus subdir and make names unique for objects per scope

Signed-off-by: Folling <mail@folling.io>
This commit is contained in:
folling 2024-01-30 09:31:08 +01:00 committed by Folling
parent ced123b628
commit 9f943cc6a2
Signed by: folling
SSH key fingerprint: SHA256:S9qEx5WCFFLK49tE/LKnKuJYM5sw+++Dn6qJbbyxnCY
51 changed files with 590 additions and 735 deletions

49
src/ikarus/errors.cpp Normal file
View file

@ -0,0 +1,49 @@
#include "ikarus/errors.h"
#include <string.h>
#include <ranges>
#include <fmt/format.h>
#include <cppbase/functional.hpp>
char const * get_error_info_name(IkarusErrorInfo info) {
switch (info) {
case IkarusErrorInfo_None: return "None";
case IkarusErrorInfo_Client_Misuse: return "Client::Misuse";
case IkarusErrorInfo_Client_InvalidInput: return "Client::InvalidInput";
case IkarusErrorInfo_Client_InvalidFormat: return "Client::InvalidFormat";
case IkarusErrorInfo_Client_ConstraintViolated: return "Client::ConstraintViolated";
case IkarusErrorInfo_Filesystem_NotFound: return "Filesystem::NotFound";
case IkarusErrorInfo_Filesystem_AlreadyExists: return "Filesystem::AlreadyExists";
case IkarusErrorInfo_Filesystem_MissingPermissions: return "Filesystem::MissingPermissions";
case IkarusErrorInfo_Filesystem_InsufficientSpace: return "Filesystem::InsufficientSpace";
case IkarusErrorInfo_Filesystem_InvalidPath: return "Filesystem::InvalidPath";
case IkarusErrorInfo_Database_ConnectionFailed: return "Database::ConnectionFailed";
case IkarusErrorInfo_Database_QueryFailed: return "Database::QueryFailed";
case IkarusErrorInfo_Database_MigrationFailed: return "Database::MigrationFailed";
case IkarusErrorInfo_Database_InvalidState: return "Database::InvalidState";
case IkarusErrorInfo_OS_SystemCallFailed: return "OS::SystemCallFailed";
case IkarusErrorInfo_OS_InvalidReturnValue: return "OS::InvalidReturnValue";
case IkarusErrorInfo_OS_InsufficientMemory: return "OS::InsufficientMemory";
case IkarusErrorInfo_LibIkarus_InvalidState: return "LibIkarus::InvalidState";
case IkarusErrorInfo_LibIkarus_CannotPerformOperation: return "LibIkarus::CannotPerformOperation";
case IkarusErrorInfo_LibIkarus_Timeout: return "LibIkarus::Timeout";
default: return "Invalid";
}
}
bool ikarus_error_data_is_success(IkarusErrorData const * data) {
return data->info == IkarusErrorInfo_None;
}
bool ikarus_error_data_is_error(IkarusErrorData const * data) {
return data->info != IkarusErrorInfo_None;
}

93
src/ikarus/errors.hpp Normal file
View file

@ -0,0 +1,93 @@
#pragma once
#include <string_view>
#include <ikarus/errors.h>
inline void safe_strcpy(char * dest, std::string_view src, size_t dest_size) {
for (int i = 0; i < dest_size; ++i) {
if (src[i] == '\0') {
dest[i] = '\0';
return;
}
dest[i] = src[i];
}
}
#define IKARUS_SET_ERROR(msg, err_info) \
if (error_out != nullptr) { \
safe_strcpy(static_cast<char *>(error_out->message), msg, IKARUS_ERROR_DATA_MAX_MESSAGE_LIMIT); \
error_out->info = err_info; \
}
#define IKARUS_FAIL(ret, msg, err_info) \
IKARUS_SET_ERROR(msg, err_info); \
return ret
#define IKARUS_FAIL_IF(condition, ret, msg, err_info) \
if (condition) { \
IKARUS_SET_ERROR(msg, err_info) \
return ret; \
}
#define IKARUS_FAIL_IF_ERROR(ret) \
if (ikarus_error_data_is_error(error_out)) { \
return ret; \
}
#define IKARUS_FAIL_IF_NULL(ptr, ret) IKARUS_FAIL_IF(((ptr) == nullptr), ret, #ptr " must not be null", IkarusErrorInfo_Client_InvalidNull)
#define IKARUS_TRY_OR_FAIL_IMPL(var_name, msg, err_info, ...) \
auto var_name = __VA_ARGS__; \
if (var_name.is_error()) { \
IKARUS_SET_ERROR(fmt::format(msg, var_name.unwrap_error()), err_info); \
return var_name; \
}
#define IKARUS_TRY_OR_FAIL(msg, err_info, ...) IKARUS_TRY_OR_FAIL_IMPL(CPPBASE_UNIQUE_NAME(result), msg, err_info, __VA_ARGS__);
#define IKARUS_TRYRV_OR_FAIL_IMPL(var_name, ret, msg, err_info, ...) \
auto var_name = __VA_ARGS__; \
if (var_name.is_error()) { \
IKARUS_SET_ERROR(fmt::format(msg, var_name.unwrap_error()), err_info); \
return ret; \
}
#define IKARUS_TRYRV_OR_FAIL(ret, msg, err_info, ...) \
IKARUS_TRYRV_OR_FAIL_IMPL(CPPBASE_UNIQUE_NAME(result), ret, msg, err_info, __VA_ARGS__);
#define IKARUS_VTRY_OR_FAIL_IMPL(var_name, value, msg, err_info, ...) \
auto var_name = __VA_ARGS__; \
if (var_name.is_error()) { \
IKARUS_SET_ERROR(fmt::format(msg, var_name.unwrap_error()), err_info); \
return var_name; \
} \
value = var_name.unwrap_value()
#define IKARUS_VTRY_OR_FAIL(value, msg, err_info, ...) \
IKARUS_VTRY_OR_FAIL_IMPL(CPPBASE_UNIQUE_NAME(result), value, msg, err_info, __VA_ARGS__);
#define IKARUS_VTRYRV_OR_FAIL_IMPL(var_name, value, ret, msg, err_info, ...) \
auto var_name = __VA_ARGS__; \
if (var_name.is_error()) { \
IKARUS_SET_ERROR(fmt::format(msg, var_name.unwrap_error()), err_info); \
return ret; \
} \
value = var_name.unwrap_value()
#define IKARUS_VTRYRV_OR_FAIL(value, ret, msg, err_info, ...) \
IKARUS_VTRYRV_OR_FAIL_IMPL(CPPBASE_UNIQUE_NAME(result), value, ret, msg, err_info, __VA_ARGS__);
#define IKARUS_FAIL_IF_OBJECT_MISSING_IMPL(var_name, obj, ret) \
IKARUS_VTRYRV_OR_FAIL( \
bool const var_name, \
ret, \
"unable to check whether object exists: {}", \
IkarusErrorInfo_Database_QueryFailed, \
(obj)->project->db->template query_one<bool>("SELECT EXISTS(SELECT 1 FROM `objects` WHERE `id` = ?)", (obj)->id) \
) \
\
IKARUS_FAIL_IF(!(var_name), ret, "object does not exist", IkarusErrorInfo_Client_Misuse);
#define IKARUS_FAIL_IF_OBJECT_MISSING(obj, ret) IKARUS_FAIL_IF_OBJECT_MISSING_IMPL(CPPBASE_UNIQUE_NAME(exists), obj, ret);

7
src/ikarus/global.cpp Normal file
View file

@ -0,0 +1,7 @@
#include "ikarus/global.h"
#include <cstdlib>
void ikarus_free(void * ptr) {
std::free(ptr);
}

14
src/ikarus/id.cpp Normal file
View file

@ -0,0 +1,14 @@
#include "ikarus/id.h"
#include <ikarus/objects/object_type.h>
constexpr uint64_t IKARUS_ID_OBJECT_TYPE_BITS = 8;
constexpr uint64_t IKARUS_ID_OBJECT_RANDOM_BITS = sizeof(IkarusId) - IKARUS_ID_OBJECT_TYPE_BITS;
auto ikarus_id_from_data_and_type(int64_t data, IkarusObjectType type) -> IkarusId {
return data | (static_cast<IkarusId>(type) << IKARUS_ID_OBJECT_RANDOM_BITS);
}
auto ikarus_id_get_object_type(IkarusId id) -> IkarusObjectType {
return static_cast<IkarusObjectType>(id >> IKARUS_ID_OBJECT_RANDOM_BITS);
}

View file

@ -0,0 +1,160 @@
#include "ikarus/objects/blueprint.h"
#include <cppbase/logger.hpp>
#include <cppbase/result.hpp>
#include <cppbase/strings.hpp>
#include <ikarus/errors.hpp>
#include <ikarus/objects/blueprint.hpp>
#include <ikarus/objects/entity.hpp>
#include <ikarus/objects/properties/property.h>
#include <ikarus/objects/properties/property.hpp>
#include <ikarus/objects/util.hpp>
#include <ikarus/persistence/project.hpp>
IkarusBlueprint::IkarusBlueprint(IkarusProject * project, IkarusId id):
IkarusObject{project, id} {}
IkarusBlueprint * ikarus_blueprint_create(struct IkarusProject * project, char const * name, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(project, nullptr);
IKARUS_FAIL_IF_NAME_INVALID(name, project, nullptr, nullptr);
IKARUS_VTRYRV_OR_FAIL(
IkarusId const id,
nullptr,
"failed to create blueprint: {}",
IkarusErrorInfo_Database_QueryFailed,
project->db->transact([name](auto * db) -> cppbase::Result<IkarusId, sqlitecpp::TransactionError> {
TRY(db->execute("INSERT INTO `objects`(`type`, `name`, `information`) VALUES(?, ?, ?)", IkarusObjectType_Blueprint, name, ""));
auto id = ikarus_id_from_data_and_type(db->last_insert_rowid(), IkarusObjectType_Blueprint);
TRY(db->execute("INSERT INTO `blueprints`(`id`) VALUES(?)", id));
return cppbase::ok(id);
})
);
return project->get_blueprint(id);
}
void ikarus_blueprint_delete(IkarusBlueprint * blueprint, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(blueprint, );
IKARUS_FAIL_IF_OBJECT_MISSING(blueprint, );
IKARUS_TRYRV_OR_FAIL(
,
"unable to delete blueprint: {}",
IkarusErrorInfo_Database_QueryFailed,
blueprint->project->db->execute("DELETE FROM `objects` WHERE `id` = ?", blueprint->id)
);
blueprint->project->uncache(blueprint);
}
IkarusProject * ikarus_blueprint_get_project(IkarusBlueprint const * blueprint, IkarusErrorData * error_out) {
return ikarus::util::object_get_project(blueprint, error_out);
}
char const * ikarus_blueprint_get_name(IkarusBlueprint const * blueprint, IkarusErrorData * error_out) {
return ikarus::util::object_get_name(blueprint, error_out);
}
void ikarus_blueprint_set_name(IkarusBlueprint * blueprint, char const * name, IkarusErrorData * error_out) {
ikarus::util::object_set_name(blueprint, name, error_out);
}
void ikarus_blueprint_get_properties(
IkarusBlueprint const * blueprint,
struct IkarusProperty ** properties_out,
size_t properties_out_size,
IkarusErrorData * error_out
) {
IKARUS_FAIL_IF_NULL(blueprint, );
IKARUS_FAIL_IF_OBJECT_MISSING(blueprint, );
IKARUS_FAIL_IF_NULL(properties_out, );
if (properties_out_size == 0) {
return;
}
std::tuple<IkarusId, IkarusPropertyType> ids_and_types[properties_out_size];
IKARUS_TRYRV_OR_FAIL(
,
"unable to fetch blueprint properties from database: {}",
IkarusErrorInfo_Database_QueryFailed,
blueprint->project->db->query_many_buffered<IkarusId, IkarusPropertyType>(
"SELECT `id` FROM `properties` WHERE `source` = ?",
ids_and_types,
properties_out_size,
blueprint->id
)
)
for (size_t i = 0; i < properties_out_size; ++i) {
auto [id, type] = ids_and_types[i];
properties_out[i] = blueprint->project->get_property(id, type);
}
}
size_t ikarus_blueprint_get_property_count(IkarusBlueprint const * blueprint, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(blueprint, 0);
IKARUS_FAIL_IF_OBJECT_MISSING(blueprint, 0);
IKARUS_VTRYRV_OR_FAIL(
auto const ret,
0,
"unable to fetch blueprint property count from database: {}",
IkarusErrorInfo_Database_QueryFailed,
blueprint->project->db->query_one<int64_t>("SELECT COUNT(*) FROM `properties` WHERE `source` = ?", blueprint->id)
);
return ret;
}
void ikarus_blueprint_get_linked_entities(
IkarusBlueprint const * blueprint,
struct IkarusEntity ** entities_out,
size_t entities_out_size,
IkarusErrorData * error_out
) {
IKARUS_FAIL_IF_NULL(blueprint, );
IKARUS_FAIL_IF_OBJECT_MISSING(blueprint, );
IKARUS_FAIL_IF_NULL(entities_out, );
if (entities_out_size == 0) {
return;
}
IkarusId ids[entities_out_size];
IKARUS_TRYRV_OR_FAIL(
,
"unable to fetch blueprint linked entities from database: {}",
IkarusErrorInfo_Database_QueryFailed,
blueprint->project->db->query_many_buffered<IkarusId>(
"SELECT `entity` FROM `entity_blueprint_links` WHERE `blueprint` = ?",
ids,
entities_out_size,
blueprint->id
)
)
for (size_t i = 0; i < entities_out_size; ++i) {
entities_out[i] = blueprint->project->get_entity(ids[i]);
}
}
size_t ikarus_blueprint_get_linked_entity_count(IkarusBlueprint const * blueprint, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(blueprint, 0);
IKARUS_FAIL_IF_OBJECT_MISSING(blueprint, 0);
IKARUS_VTRYRV_OR_FAIL(
auto const ret,
0,
"unable to fetch blueprint linked entity count from database: {}",
IkarusErrorInfo_Database_QueryFailed,
blueprint->project->db->query_one<int64_t>("SELECT COUNT(*) FROM `entity_blueprint_links` WHERE `blueprint` = ?", blueprint->id)
);
return ret;
}

View file

@ -0,0 +1,21 @@
#pragma once
#include <ikarus/objects/object.hpp>
struct IkarusBlueprint : IkarusObject {
public:
IkarusBlueprint(struct IkarusProject * project, IkarusId id);
IkarusBlueprint(IkarusBlueprint const &) = default;
IkarusBlueprint(IkarusBlueprint &&) = default;
IkarusBlueprint & operator=(IkarusBlueprint const &) = default;
IkarusBlueprint & operator=(IkarusBlueprint &&) = default;
~IkarusBlueprint() override = default;
public:
inline std::string_view get_table_name() const noexcept override {
return "blueprints";
}
};

View file

@ -0,0 +1,286 @@
#include "entity.hpp"
#include <cppbase/strings.hpp>
#include <ikarus/errors.hpp>
#include <ikarus/objects/blueprint.hpp>
#include <ikarus/objects/properties/property.hpp>
#include <ikarus/objects/util.hpp>
#include <ikarus/persistence/project.hpp>
#include <ikarus/values/entity_property_value.hpp>
#include <ikarus/values/value.hpp>
IkarusEntity * ikarus_entity_create(struct IkarusProject * project, char const * name, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(project, nullptr);
IKARUS_FAIL_IF_NAME_INVALID(name, project, nullptr, nullptr);
IKARUS_VTRYRV_OR_FAIL(
IkarusId const id,
nullptr,
"failed to create entity: {}",
IkarusErrorInfo_Database_QueryFailed,
project->db->transact([name](auto * db) -> cppbase::Result<IkarusId, sqlitecpp::TransactionError> {
TRY(db->execute("INSERT INTO `objects`(`type`) VALUES(?, ?, ?)", IkarusObjectType_Entity));
auto id = ikarus_id_from_data_and_type(db->last_insert_rowid(), IkarusObjectType_Entity);
TRY(db->execute("INSERT INTO `entities`(`id`, `name`) VALUES(?)", id, name));
return cppbase::ok(id);
})
);
return project->get_entity(id);
}
void ikarus_entity_delete(IkarusEntity * entity, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(entity, );
IKARUS_FAIL_IF_OBJECT_MISSING(entity, );
IKARUS_TRYRV_OR_FAIL(
,
"unable to delete entity: {}",
IkarusErrorInfo_Database_QueryFailed,
entity->project->db->execute("DELETE FROM `objects` WHERE `id` == ?", entity->id)
);
entity->project->uncache(entity);
}
IkarusProject * ikarus_entity_get_project(IkarusEntity const * entity, IkarusErrorData * error_out) {
return ikarus::util::object_get_project(entity, error_out);
}
char const * ikarus_entity_get_name(IkarusEntity const * entity, IkarusErrorData * error_out) {
return ikarus::util::object_get_name(entity, error_out);
}
void ikarus_entity_set_name(IkarusEntity * entity, char const * name, IkarusErrorData * error_out) {
ikarus::util::object_set_name(entity, name, error_out);
}
bool ikarus_entity_is_linked_to_blueprint(
IkarusEntity const * entity,
struct IkarusBlueprint const * blueprint,
IkarusErrorData * error_out
) {
IKARUS_FAIL_IF_NULL(entity, false);
IKARUS_FAIL_IF_OBJECT_MISSING(entity, false);
IKARUS_FAIL_IF_NULL(blueprint, false);
IKARUS_FAIL_IF_OBJECT_MISSING(blueprint, false);
IKARUS_VTRYRV_OR_FAIL(
auto const ret,
false,
"unable to check whether entity is linked to blueprint",
IkarusErrorInfo_Database_QueryFailed,
entity->project->db->query_one<bool>(
"SELECT EXISTS(SELECT 1 FROM `entity_blueprint_links` WHERE `entity` = ? AND `blueprint` = ?)",
entity->id,
blueprint->id
)
)
return ret;
}
void ikarus_entity_link_to_blueprint(IkarusEntity * entity, struct IkarusBlueprint * blueprint, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(entity, );
IKARUS_FAIL_IF_OBJECT_MISSING(entity, );
IKARUS_FAIL_IF_NULL(blueprint, );
IKARUS_FAIL_IF_OBJECT_MISSING(blueprint, );
IKARUS_TRYRV_OR_FAIL(
,
"unable to link entity to blueprint: {}",
IkarusErrorInfo_Database_QueryFailed,
entity->project->db->execute(
"INSERT INTO `entity_blueprint_links`(`entity`, `blueprint`) VALUES(?, ?) ON CONFLICT(`entity`, `blueprint`) DO NOTHING",
entity->id,
blueprint->id
)
);
}
void ikarus_entity_unlink_from_blueprint(IkarusEntity * entity, struct IkarusBlueprint * blueprint, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(entity, );
IKARUS_FAIL_IF_OBJECT_MISSING(entity, );
IKARUS_FAIL_IF_NULL(blueprint, );
IKARUS_FAIL_IF_OBJECT_MISSING(blueprint, );
IKARUS_TRYRV_OR_FAIL(
,
"unable to unlink entity from blueprint: {}",
IkarusErrorInfo_Database_QueryFailed,
entity->project->db
->execute("DELETE FROM `entity_blueprint_links` WHERE `entity` = ? AND `blueprint` = ?", entity->id, blueprint->id)
);
}
void ikarus_entity_get_linked_blueprints(
IkarusEntity const * entity,
struct IkarusBlueprint ** blueprints_out,
size_t blueprints_out_size,
IkarusErrorData * error_out
) {
IKARUS_FAIL_IF_NULL(entity, );
IKARUS_FAIL_IF_OBJECT_MISSING(entity, );
IKARUS_FAIL_IF_NULL(blueprints_out, );
if (blueprints_out_size == 0) {
return;
}
IkarusId ids[blueprints_out_size];
IKARUS_TRYRV_OR_FAIL(
,
"unable to fetch entity linked blueprints from database: {}",
IkarusErrorInfo_Database_QueryFailed,
entity->project->db->query_many_buffered<IkarusId>(
"SELECT `blueprint` FROM `entity_blueprint_links` WHERE `entity` = ?",
ids,
blueprints_out_size,
entity->id
)
)
for (size_t i = 0; i < blueprints_out_size; ++i) {
blueprints_out[i] = entity->project->get_blueprint(ids[i]);
}
}
size_t ikarus_entity_get_linked_blueprint_count(IkarusEntity const * entity, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(entity, 0);
IKARUS_FAIL_IF_OBJECT_MISSING(entity, 0);
IKARUS_VTRYRV_OR_FAIL(
auto const ret,
0,
"unable to fetch entity linked blueprint count from database: {}",
IkarusErrorInfo_Database_QueryFailed,
entity->project->db->query_one<int64_t>("SELECT COUNT(*) FROM `entity_blueprint_links` WHERE `entity` = ?", entity->id)
);
return ret;
}
bool ikarus_entity_has_property(IkarusEntity const * entity, struct IkarusProperty const * property, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(entity, false);
IKARUS_FAIL_IF_OBJECT_MISSING(entity, false);
IKARUS_FAIL_IF_NULL(property, false);
IKARUS_FAIL_IF_OBJECT_MISSING(property, false);
IKARUS_VTRYRV_OR_FAIL(
auto const ret,
false,
"unable to check whether entity has property: {}",
IkarusErrorInfo_Database_QueryFailed,
entity->project->db->query_one<bool>(
"SELECT EXISTS(SELECT 1 FROM `entity_properties` WHERE `entity` = ? AND `property` = ?)",
entity->id,
property->id
)
)
return ret;
}
void ikarus_entity_get_properties(
IkarusEntity const * entity,
struct IkarusProperty ** properties_out,
size_t properties_out_size,
IkarusErrorData * error_out
) {
IKARUS_FAIL_IF_NULL(entity, );
IKARUS_FAIL_IF_OBJECT_MISSING(entity, );
IKARUS_FAIL_IF_NULL(properties_out, );
if (properties_out_size == 0) {
return;
}
std::tuple<IkarusId, IkarusPropertyType> ids_and_types[properties_out_size];
IKARUS_TRYRV_OR_FAIL(
,
"unable to fetch entity properties from database: {}",
IkarusErrorInfo_Database_QueryFailed,
entity->project->db->query_many_buffered<IkarusId, IkarusPropertyType>(
"SELECT `property`, `type` FROM `properties` WHERE `source` = ?",
ids_and_types,
properties_out_size,
entity->id
)
)
for (size_t i = 0; i < properties_out_size; ++i) {
auto [id, type] = ids_and_types[i];
properties_out[i] = entity->project->get_property(id, type);
}
}
size_t ikarus_entity_get_property_count(IkarusEntity const * entity, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(entity, 0);
IKARUS_FAIL_IF_OBJECT_MISSING(entity, 0);
IKARUS_VTRYRV_OR_FAIL(
size_t const ret,
0,
"unable to fetch entity property count from database: {}",
IkarusErrorInfo_Database_QueryFailed,
entity->project->db->query_one<int64_t>("SELECT COUNT(*) FROM `properties` WHERE `source` = ?", entity->id)
);
return ret;
}
struct IkarusEntityPropertyValue *
ikarus_entity_get_value(IkarusEntity const * entity, struct IkarusProperty const * property, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(entity, nullptr);
IKARUS_FAIL_IF_OBJECT_MISSING(entity, nullptr);
IKARUS_FAIL_IF_NULL(property, nullptr);
IKARUS_FAIL_IF_OBJECT_MISSING(property, nullptr);
auto * value = fetch_value_from_db(
entity->project,
error_out,
"SELECT IFNULL((SELECT `value` FROM `values` WHERE `entity` = ? AND `property` = ?), (SELECT `default_value` FROM `properties` WHERE `id` = ?))",
entity->id,
property->id,
property->id
);
IKARUS_FAIL_IF_ERROR(nullptr);
return new IkarusEntityPropertyValue{
.entity = entity,
.property = property,
.value = value,
};
}
void ikarus_entity_set_value(
IkarusEntity * entity,
struct IkarusProperty const * property,
struct IkarusEntityPropertyValue * value,
IkarusErrorData * error_out
) {
IKARUS_FAIL_IF_NULL(entity, );
IKARUS_FAIL_IF_OBJECT_MISSING(entity, );
IKARUS_FAIL_IF_NULL(property, );
IKARUS_FAIL_IF_OBJECT_MISSING(property, );
IKARUS_FAIL_IF_NULL(value, );
auto value_json_str = boost::json::serialize(value->value->to_json());
IKARUS_TRYRV_OR_FAIL(
,
"unable to set entity property value: {}",
IkarusErrorInfo_Database_QueryFailed,
entity->project->db->execute(
"INSERT INTO `values`(`entity`, `property`, `value`) VALUES(?, ?, ?) ON CONFLICT(`entity`, `property`) DO UPDATE SET `value` = ?",
entity->id,
property->id,
value_json_str,
value_json_str
)
);
}

View file

@ -0,0 +1,22 @@
#pragma once
#include <ikarus/objects/object.hpp>
struct IkarusEntity : IkarusObject {
public:
inline IkarusEntity(struct IkarusProject * project, IkarusId id):
IkarusObject{project, id} {}
IkarusEntity(IkarusEntity const &) = default;
IkarusEntity(IkarusEntity &&) = default;
IkarusEntity & operator=(IkarusEntity const &) = default;
IkarusEntity & operator=(IkarusEntity &&) = default;
~IkarusEntity() override = default;
public:
inline std::string_view get_table_name() const noexcept override {
return "entities";
}
};

View file

@ -0,0 +1,93 @@
#include "object.hpp"
#include <fmt/format.h>
#include <cppbase/strings.hpp>
#include <ikarus/errors.h>
#include <ikarus/errors.hpp>
#include <ikarus/objects/blueprint.hpp>
#include <ikarus/objects/entity.hpp>
#include <ikarus/objects/object.h>
#include <ikarus/objects/properties/property.hpp>
#include <ikarus/persistence/project.hpp>
IkarusObject::IkarusObject(IkarusProject * project, IkarusId id):
project{project},
id{id} {}
void ikarus_object_visit(
IkarusObject * object,
void (*blueprint_visitor)(struct IkarusBlueprint *, IkarusErrorData * error_out, void *),
void (*property_visitor)(struct IkarusProperty *, IkarusErrorData * error_out, void *),
void (*entity_visitor)(struct IkarusEntity *, IkarusErrorData * error_out, void *),
void * data,
IkarusErrorData * error_out
) {
struct Data {
void (*blueprint_visitor)(struct IkarusBlueprint *, IkarusErrorData * error_out, void *);
void (*property_visitor)(struct IkarusProperty *, IkarusErrorData * error_out, void *);
void (*entity_visitor)(struct IkarusEntity *, IkarusErrorData * error_out, void *);
void * data;
};
Data passthru_data{blueprint_visitor, property_visitor, entity_visitor, data};
ikarus_object_visit_const(
object,
[](IkarusBlueprint const * blueprint, IkarusErrorData * error_out, void * data) {
auto const * passthru_data = static_cast<Data *>(data);
passthru_data->blueprint_visitor(const_cast<IkarusBlueprint *>(blueprint), error_out, passthru_data->data);
},
[](IkarusProperty const * property, IkarusErrorData * error_out, void * data) {
auto const * passthru_data = static_cast<Data *>(data);
passthru_data->property_visitor(const_cast<IkarusProperty *>(property), error_out, passthru_data->data);
},
[](IkarusEntity const * entity, IkarusErrorData * error_out, void * data) {
auto const * passthru_data = static_cast<Data *>(data);
passthru_data->entity_visitor(const_cast<IkarusEntity *>(entity), error_out, passthru_data->data);
},
&passthru_data,
error_out
);
}
void ikarus_object_visit_const(
IkarusObject const * object,
void (*blueprint_visitor)(struct IkarusBlueprint const *, IkarusErrorData * error_out, void *),
void (*property_visitor)(struct IkarusProperty const *, IkarusErrorData * error_out, void *),
void (*entity_visitor)(struct IkarusEntity const *, IkarusErrorData * error_out, void *),
void * data,
IkarusErrorData * error_out
) {
IKARUS_FAIL_IF_NULL(object, );
IKARUS_FAIL_IF_OBJECT_MISSING(object, );
switch (ikarus_id_get_object_type(object->id)) {
case IkarusObjectType_Entity: {
auto const * entity = dynamic_cast<IkarusEntity const *>(object);
IKARUS_FAIL_IF(entity == nullptr, , "object with entity id wasn't a entity", IkarusErrorInfo_LibIkarus_InvalidState);
entity_visitor(entity, error_out, data);
}
case IkarusObjectType_Blueprint: {
auto const * blueprint = dynamic_cast<IkarusBlueprint const *>(object);
IKARUS_FAIL_IF(blueprint == nullptr, , "object with blueprint id wasn't a blueprint", IkarusErrorInfo_LibIkarus_InvalidState);
blueprint_visitor(blueprint, error_out, data);
}
case IkarusObjectType_Property: {
auto const * property = dynamic_cast<IkarusProperty const *>(object);
IKARUS_FAIL_IF(property == nullptr, , "object with property id wasn't a property", IkarusErrorInfo_LibIkarus_InvalidState);
property_visitor(property, error_out, data);
}
default: {
IKARUS_FAIL(
,
fmt::format("unknown object type: {}", ikarus_object_type_to_string(ikarus_id_get_object_type(object->id))),
IkarusErrorInfo_LibIkarus_InvalidState
);
}
}
// not needed, but a good delineation of our intention if this function gets extended
IKARUS_FAIL_IF_ERROR()
}

View file

@ -0,0 +1,25 @@
#pragma once
#include <string_view>
#include <ikarus/id.h>
struct IkarusObject {
public:
IkarusObject(struct IkarusProject * project, IkarusId id);
IkarusObject(IkarusObject const &) = default;
IkarusObject(IkarusObject &&) = default;
IkarusObject & operator=(IkarusObject const &) = default;
IkarusObject & operator=(IkarusObject &&) = default;
virtual ~IkarusObject() = default;
public:
virtual std::string_view get_table_name() const noexcept = 0;
public:
struct IkarusProject * project;
IkarusId id;
};

View file

@ -0,0 +1,12 @@
#include "ikarus/objects/object_type.h"
char const * ikarus_object_type_to_string(IkarusObjectType type) {
switch (type) {
case IkarusObjectType_None: return "none";
case IkarusObjectType_Entity: return "entity";
case IkarusObjectType_Blueprint: return "blueprint";
case IkarusObjectType_Property: return "property";
}
return "unknown";
}

View file

@ -0,0 +1,32 @@
#include "number_property.hpp"
#include <cppbase/result.hpp>
#include <ikarus/objects/properties/property.h>
#include <ikarus/objects/properties/property_scope.hpp>
#include <ikarus/objects/properties/util.hpp>
#include <ikarus/values/value.hpp>
IkarusNumberProperty::IkarusNumberProperty(IkarusProject * project, IkarusId id):
IkarusProperty{project, id, this} {}
IkarusNumberProperty * ikarus_number_property_create(
struct IkarusProject * project,
char const * name,
struct IkarusPropertyScope * property_source,
IkarusErrorData * error_out
) {
return ikarus::util::create_property<IkarusNumberProperty>(project, name, property_source, error_out);
}
IkarusNumberValue * ikarus_number_property_get_default_value(IkarusNumberProperty * property, IkarusErrorData * error_out) {
return ikarus::util::get_default_value<IkarusNumberProperty>(property, error_out);
}
void ikarus_number_property_set_default_value(
IkarusNumberProperty * property,
IkarusNumberValue * new_default_value,
IkarusErrorData * error_out
) {
ikarus::util::set_default_value<IkarusNumberProperty>(property, new_default_value, error_out);
}

View file

@ -0,0 +1,14 @@
#pragma once
#include <ikarus/objects/properties/property.hpp>
#include <ikarus/objects/properties/property_type.h>
#include <ikarus/values/number_value.hpp>
struct IkarusNumberProperty : IkarusProperty {
public:
using value_type = IkarusNumberValue;
constexpr auto static PropertyType = IkarusPropertyType_Number;
public:
IkarusNumberProperty(struct IkarusProject * project, IkarusId id);
};

View file

@ -0,0 +1,139 @@
#include "property.hpp"
#include <cppbase/logger.hpp>
#include <ikarus/errors.hpp>
#include <ikarus/objects/properties/property.h>
#include <ikarus/objects/properties/property_scope.hpp>
#include <ikarus/objects/properties/property_type.h>
#include <ikarus/objects/util.hpp>
#include <ikarus/persistence/project.hpp>
#include <ikarus/values/value.hpp>
IkarusProperty::IkarusProperty(IkarusProject * project, IkarusId id, Data data):
IkarusObject{project, id},
data{data} {}
IKA_API void ikarus_property_delete(IkarusProperty * property, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(property, );
IKARUS_FAIL_IF_OBJECT_MISSING(property, );
IKARUS_TRYRV_OR_FAIL(
,
"unable to delete property: {}",
IkarusErrorInfo_Database_QueryFailed,
property->project->db->execute("DELETE FROM `objects` WHERE `id` = ?", property->id)
);
property->project->uncache(property);
}
IkarusProject * ikarus_property_get_project(IkarusProperty const * property, IkarusErrorData * error_out) {
return ikarus::util::object_get_project(property, error_out);
}
char const * ikarus_property_get_name(IkarusProperty const * property, IkarusErrorData * error_out) {
return ikarus::util::object_get_name(property, error_out);
}
void ikarus_property_set_name(IkarusProperty * property, char const * name, IkarusErrorData * error_out) {
ikarus::util::object_set_name(property, name, error_out);
}
IkarusPropertyType ikarus_property_get_type(IkarusProperty const * property, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(property, IkarusPropertyType_Toggle);
IKARUS_FAIL_IF_OBJECT_MISSING(property, IkarusPropertyType_Toggle);
IKARUS_VTRYRV_OR_FAIL(
auto const ret,
IkarusPropertyType_Toggle,
"unable to fetch property type from database: {}",
IkarusErrorInfo_Database_QueryFailed,
property->project->db->query_one<int>("SELECT `type` FROM `properties` WHERE `id` = ?", property->id)
);
return static_cast<IkarusPropertyType>(ret);
}
IkarusPropertyScope const * ikarus_property_get_scope(IkarusProperty const * property, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(property, nullptr);
IKARUS_FAIL_IF_OBJECT_MISSING(property, nullptr);
IKARUS_VTRYRV_OR_FAIL(
auto const source,
nullptr,
"unable to fetch property source from database: {}",
IkarusErrorInfo_Database_QueryFailed,
property->project->db->query_one<IkarusId>("SELECT `source` FROM `properties` WHERE `id` = ?", property->id)
);
switch (ikarus_id_get_object_type(source)) {
case IkarusObjectType_Blueprint: return new IkarusPropertyScope{property->project->get_blueprint(source)};
case IkarusObjectType_Entity: return new IkarusPropertyScope{property->project->get_entity(source)};
default:
IKARUS_FAIL(
nullptr,
fmt::format("invalid property source type: {}", ikarus_object_type_to_string(ikarus_id_get_object_type(source))),
IkarusErrorInfo_LibIkarus_InvalidState
);
}
}
IkarusValue * ikarus_property_get_default_value(IkarusProperty const * property, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(property, nullptr);
IKARUS_FAIL_IF_OBJECT_MISSING(property, nullptr);
return fetch_value_from_db(property->project, error_out, "SELECT `default_value` FROM `properties` WHERE `id` = ?", property->id);
}
void ikarus_property_visit(
IkarusProperty * property,
void (*toggle_property_visitor)(struct IkarusToggleProperty *, void *),
void (*number_property_visitor)(struct IkarusNumberProperty *, void *),
void (*text_property_visitor)(struct IkarusTextProperty *, void *),
void * data,
IkarusErrorData * error_out
) {
IKARUS_FAIL_IF_NULL(property, );
IKARUS_FAIL_IF_OBJECT_MISSING(property, );
std::visit(
cppbase::overloaded{
[toggle_property_visitor, data](IkarusToggleProperty * property) { toggle_property_visitor(property, data); },
[number_property_visitor, data](IkarusNumberProperty * property) { number_property_visitor(property, data); },
[text_property_visitor, data](IkarusTextProperty * property) { text_property_visitor(property, data); }
},
property->data
);
}
void ikarus_property_visit_const(
IkarusProperty const * property,
void (*toggle_property_visitor)(struct IkarusToggleProperty const *, void *),
void (*number_property_visitor)(struct IkarusNumberProperty const *, void *),
void (*text_property_visitor)(struct IkarusTextProperty const *, void *),
void * data,
IkarusErrorData * error_out
) {
IKARUS_FAIL_IF_NULL(property, );
IKARUS_FAIL_IF_OBJECT_MISSING(property, );
std::visit(
cppbase::overloaded{
[toggle_property_visitor, data](IkarusToggleProperty const * property) { toggle_property_visitor(property, data); },
[number_property_visitor, data](IkarusNumberProperty const * property) { number_property_visitor(property, data); },
[text_property_visitor, data](IkarusTextProperty const * property) { text_property_visitor(property, data); }
},
property->data
);
}
// No existence checks here for performance reasons. All methods on IkarusObject perform this check anyway.
IkarusObject * ikarus_property_to_object(IkarusProperty * property) {
return static_cast<IkarusObject *>(property);
}
IkarusObject const * ikarus_property_to_object_const(IkarusProperty const * property) {
return static_cast<IkarusObject const *>(property);
}

View file

@ -0,0 +1,29 @@
#pragma once
#include <variant>
#include <ikarus/objects/object.hpp>
struct IkarusProperty : IkarusObject {
public:
using Data = std::variant<struct IkarusToggleProperty *, struct IkarusNumberProperty *, struct IkarusTextProperty *>;
public:
IkarusProperty(struct IkarusProject * project, IkarusId id, Data data);
IkarusProperty(IkarusProperty const &) = default;
IkarusProperty(IkarusProperty &&) = default;
IkarusProperty & operator=(IkarusProperty const &) = default;
IkarusProperty & operator=(IkarusProperty &&) = default;
~IkarusProperty() override = default;
public:
inline std::string_view get_table_name() const noexcept override {
return "properties";
}
public:
Data data;
};

View file

@ -0,0 +1,57 @@
#include "property_scope.hpp"
#include <cppbase/templates.hpp>
#include <ikarus/objects/blueprint.hpp>
#include <ikarus/objects/entity.hpp>
IkarusPropertyScope::IkarusPropertyScope(Data data):
data{data} {}
IkarusId IkarusPropertyScope::get_id() const {
return std::visit(
cppbase::overloaded{
[](IkarusBlueprint const * blueprint) { return blueprint->id; },
[](IkarusEntity const * entity) { return entity->id; }
},
data
);
}
IkarusPropertyScope * ikarus_property_source_create_blueprint(IkarusBlueprint * blueprint) {
return new IkarusPropertyScope{blueprint};
}
IkarusPropertyScope * ikarus_property_source_create_entity(IkarusEntity * entity) {
return new IkarusPropertyScope{entity};
}
void ikarus_property_source_visit(
struct IkarusPropertyScope * property_source,
void (*blueprint_visitor)(struct IkarusBlueprint *, void *),
void (*entity_visitor)(struct IkarusEntity *, void *),
void * user_data
) {
std::visit(
cppbase::overloaded{
[blueprint_visitor, user_data](IkarusBlueprint * blueprint) { blueprint_visitor(blueprint, user_data); },
[entity_visitor, user_data](IkarusEntity * entity) { entity_visitor(entity, user_data); }
},
property_source->data
);
}
void ikarus_property_source_visit_const(
struct IkarusPropertyScope const * property_source,
void (*blueprint_visitor)(struct IkarusBlueprint const *, void *),
void (*entity_visitor)(struct IkarusEntity const *, void *),
void * user_data
) {
std::visit(
cppbase::overloaded(
[blueprint_visitor, user_data](IkarusBlueprint const * blueprint) { blueprint_visitor(blueprint, user_data); },
[entity_visitor, user_data](IkarusEntity const * entity) { entity_visitor(entity, user_data); }
),
property_source->data
);
}

View file

@ -0,0 +1,39 @@
#pragma once
#include <variant>
#include <ikarus/id.h>
#include <ikarus/objects/properties/property_scope.h>
#define IKARUS_FAIL_IF_PROPERTY_SCOPE_INVALID(scope, ret) \
std::visit( \
cppbase::overloaded{[error_out](auto const * object) { \
IKARUS_FAIL_IF_NULL(object, ); \
IKARUS_FAIL_IF_OBJECT_MISSING(object, ); \
}}, \
scope->data \
); \
\
IKARUS_FAIL_IF_ERROR(nullptr);
struct IkarusPropertyScope {
public:
using Data = std::variant<IkarusBlueprint *, IkarusEntity *>;
public:
explicit IkarusPropertyScope(Data data);
IkarusPropertyScope(IkarusPropertyScope const &) = default;
IkarusPropertyScope(IkarusPropertyScope &&) = default;
IkarusPropertyScope & operator=(IkarusPropertyScope const &) = default;
IkarusPropertyScope & operator=(IkarusPropertyScope &&) = default;
virtual ~IkarusPropertyScope() = default;
public:
[[nodiscard]] IkarusId get_id() const;
public:
Data data;
};

View file

@ -0,0 +1,32 @@
#include "text_property.hpp"
#include <cppbase/result.hpp>
#include <ikarus/objects/properties/property.h>
#include <ikarus/objects/properties/property_scope.hpp>
#include <ikarus/objects/properties/util.hpp>
#include <ikarus/values/value.hpp>
IkarusTextProperty::IkarusTextProperty(IkarusProject * project, IkarusId id):
IkarusProperty{project, id, this} {}
IkarusTextProperty * ikarus_text_property_create(
struct IkarusProject * project,
char const * name,
struct IkarusPropertyScope * property_source,
IkarusErrorData * error_out
) {
return ikarus::util::create_property<IkarusTextProperty>(project, name, property_source, error_out);
}
IkarusTextValue * ikarus_text_property_get_default_value(IkarusTextProperty * property, IkarusErrorData * error_out) {
return ikarus::util::get_default_value<IkarusTextProperty>(property, error_out);
}
void ikarus_text_property_set_default_value(
IkarusTextProperty * property,
IkarusTextValue * new_default_value,
IkarusErrorData * error_out
) {
ikarus::util::set_default_value<IkarusTextProperty>(property, new_default_value, error_out);
}

View file

@ -0,0 +1,14 @@
#pragma once
#include <ikarus/objects/properties/property.hpp>
#include <ikarus/objects/properties/property_type.h>
#include <ikarus/values/text_value.hpp>
struct IkarusTextProperty : IkarusProperty {
public:
using value_type = IkarusTextValue;
constexpr auto static PropertyType = IkarusPropertyType_Text;
public:
IkarusTextProperty(struct IkarusProject * project, IkarusId id);
};

View file

@ -0,0 +1,32 @@
#include "toggle_property.hpp"
#include <cppbase/result.hpp>
#include <ikarus/objects/properties/property.h>
#include <ikarus/objects/properties/property_scope.hpp>
#include <ikarus/objects/properties/util.hpp>
#include <ikarus/values/value.hpp>
IkarusToggleProperty::IkarusToggleProperty(IkarusProject * project, IkarusId id):
IkarusProperty{project, id, this} {}
IkarusToggleProperty * ikarus_toggle_property_create(
struct IkarusProject * project,
char const * name,
struct IkarusPropertyScope * property_source,
IkarusErrorData * error_out
) {
return ikarus::util::create_property<IkarusToggleProperty>(project, name, property_source, error_out);
}
IkarusToggleValue * ikarus_toggle_property_get_default_value(struct IkarusToggleProperty * property, IkarusErrorData * error_out) {
return ikarus::util::get_default_value<IkarusToggleProperty>(property, error_out);
}
void ikarus_toggle_property_set_default_value(
struct IkarusToggleProperty * property,
struct IkarusToggleValue * new_default_value,
IkarusErrorData * error_out
) {
ikarus::util::set_default_value<IkarusToggleProperty>(property, new_default_value, error_out);
}

View file

@ -0,0 +1,14 @@
#pragma once
#include <ikarus/objects/properties/property.hpp>
#include <ikarus/objects/properties/property_type.h>
#include <ikarus/values/toggle_value.hpp>
struct IkarusToggleProperty : IkarusProperty {
public:
using value_type = IkarusToggleValue;
constexpr auto static PropertyType = IkarusPropertyType_Toggle;
public:
IkarusToggleProperty(struct IkarusProject * project, IkarusId id);
};

View file

@ -0,0 +1,95 @@
#pragma once
#include <boost/type_index.hpp>
#include <cppbase/strings.hpp>
#include <ikarus/errors.hpp>
#include <ikarus/objects/properties/property.h>
#include <ikarus/objects/properties/property.hpp>
#include <ikarus/objects/properties/property_scope.hpp>
#include <ikarus/objects/util.hpp>
#include <ikarus/persistence/project.hpp>
#include <ikarus/values/value.hpp>
namespace ikarus::util {
template<typename T>
T * create_property(
struct IkarusProject * project,
char const * name,
struct IkarusPropertyScope * property_scope,
IkarusErrorData * error_out
) {
IKARUS_FAIL_IF_NULL(project, nullptr);
IKARUS_FAIL_IF_NULL(property_scope, nullptr);
IKARUS_FAIL_IF_PROPERTY_SCOPE_INVALID(property_scope, nullptr);
IKARUS_FAIL_IF_NAME_INVALID(name, project, property_scope, nullptr);
IKARUS_VTRYRV_OR_FAIL(
IkarusId const id,
nullptr,
"failed to create property: {}",
IkarusErrorInfo_Database_QueryFailed,
project->db->transact([name, property_scope](auto * db) -> cppbase::Result<IkarusId, sqlitecpp::TransactionError> {
TRY(db->execute("INSERT INTO `objects`(`type`, `name`, `information`) VALUES(?, ?, ?)", IkarusObjectType_Property, name, ""));
auto id = ikarus_id_from_data_and_type(db->last_insert_rowid(), IkarusObjectType_Property);
TRY(db->execute(
"INSERT INTO `properties`(`id`, `type`, `source`) VALUES(?, ?, ?)",
id,
T::PropertyType,
property_scope->get_id()
));
return cppbase::ok(id);
})
);
auto * ret = dynamic_cast<T *>(project->get_property(id, T::PropertyType));
IKARUS_FAIL_IF(
ret == nullptr,
nullptr,
fmt::format("created {} cannot be casted down from IkarusProject", boost::typeindex::type_id<T>().pretty_name()),
IkarusErrorInfo_LibIkarus_InvalidState
);
return ret;
}
template<typename T>
typename T::value_type * get_default_value(IkarusProperty const * property, IkarusErrorData * error_out) {
auto * value = ikarus_property_get_default_value(property, error_out);
IKARUS_FAIL_IF_ERROR(nullptr);
auto * ret = boost::variant2::get_if<typename T::value_type *>(&value->data);
IKARUS_FAIL_IF(
ret == nullptr,
nullptr,
fmt::format(
"{} default value is not a(n) {}",
boost::typeindex::type_id<T>().pretty_name(),
boost::typeindex::type_id<typename T::value_type>().pretty_name()
),
IkarusErrorInfo_Database_InvalidState
);
return *ret;
}
template<typename T>
void set_default_value(T * property, typename T::value_type * new_default_value, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(property, );
IKARUS_FAIL_IF_OBJECT_MISSING(property, );
IKARUS_FAIL_IF_NULL(new_default_value, );
auto value_json_str = boost::json::serialize(new_default_value->to_json());
IKARUS_TRYRV_OR_FAIL(
,
"unable to set property default value: {}",
IkarusErrorInfo_Database_QueryFailed,
property->project->db->execute("UPDATE `properties` SET `default_value` = ? WHERE `id` = ?", value_json_str, property->id)
);
}
} // namespace ikarus::util

125
src/ikarus/objects/util.hpp Normal file
View file

@ -0,0 +1,125 @@
#pragma once
#include <string_view>
#include <cppbase/strings.hpp>
#include <ikarus/errors.h>
#include <ikarus/errors.hpp>
#include <ikarus/objects/blueprint.hpp>
#include <ikarus/objects/entity.hpp>
#include <ikarus/objects/object.hpp>
#include <ikarus/objects/properties/property.h>
#include <ikarus/objects/properties/property.hpp>
#include <ikarus/objects/properties/property_scope.hpp>
#include <ikarus/persistence/project.hpp>
namespace ikarus::util {
template<typename O>
[[nodiscard]] IkarusProject * object_get_project(O const * object, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(object, nullptr);
IKARUS_FAIL_IF_OBJECT_MISSING(object, nullptr);
return object->project;
}
template<typename O>
[[nodiscard]] char const * object_get_name(O const * object, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(object, nullptr);
IKARUS_FAIL_IF_OBJECT_MISSING(object, nullptr);
IKARUS_VTRYRV_OR_FAIL(
auto const ret,
nullptr,
fmt::runtime(fmt::format("unable to fetch {} name: {{}}", ikarus_object_type_to_string(ikarus_id_get_object_type(object->id)))),
IkarusErrorInfo_Database_QueryFailed,
object->project->db
->template query_one<std::string>(fmt::format("SELECT `name` FROM `{}` WHERE `id` = ?", object->get_table_name()), object->id)
);
return strdup(ret.data());
}
[[nodiscard]] inline bool name_is_unique(
IkarusProject const * project,
std::string_view name,
[[maybe_unused]] IkarusBlueprint const * blueprint,
IkarusErrorData * error_out
) {
IKARUS_VTRYRV_OR_FAIL(
bool const exists,
false,
"unable to check if blueprint name is unique",
IkarusErrorInfo_Database_QueryFailed,
project->db->query_one<bool>("SELECT EXISTS(SELECT 1 FROM `blueprints` WHERE `name` = ?)", name)
);
return exists;
}
[[nodiscard]] inline bool name_is_unique(
IkarusProject const * project,
std::string_view name,
[[maybe_unused]] IkarusEntity const * entity,
IkarusErrorData * error_out
) {
IKARUS_VTRYRV_OR_FAIL(
bool const exists,
false,
"unable to check if entity name is unique",
IkarusErrorInfo_Database_QueryFailed,
project->db->query_one<bool>("SELECT EXISTS(SELECT 1 FROM `entities` WHERE `name` = ?)", name)
);
return exists;
}
[[nodiscard]] inline bool
name_is_unique(IkarusProject const * project, std::string_view name, IkarusPropertyScope const * scope, IkarusErrorData * error_out) {
IKARUS_VTRYRV_OR_FAIL(
bool const exists,
false,
"unable to check if property name is unique",
IkarusErrorInfo_Database_QueryFailed,
project->db->query_one<bool>("SELECT EXISTS(SELECT 1 FROM `properties` WHERE `name` = ? AND `scope` = ?)", name, scope->get_id())
);
return exists;
}
[[nodiscard]] inline bool
name_is_unique(IkarusProject * project, std::string_view name, IkarusProperty const * property, IkarusErrorData * error_out) {
std::unique_ptr<IkarusPropertyScope const> scope{ikarus_property_get_scope(property, error_out)};
IKARUS_FAIL_IF_ERROR(false);
return name_is_unique(project, name, scope.get(), error_out);
}
#define IKARUS_FAIL_IF_NAME_INVALID(name, project, object, ret, ...) \
IKARUS_FAIL_IF_NULL(name, ret); \
IKARUS_FAIL_IF(cppbase::is_empty_or_blank(name), ret, "name must not be empty", IkarusErrorInfo_Client_InvalidInput); \
IKARUS_FAIL_IF( \
!ikarus::util::name_is_unique(project, name, object, error_out), \
ret, \
"name must be unique", \
IkarusErrorInfo_Client_InvalidInput \
); \
IKARUS_FAIL_IF_ERROR(ret);
template<typename O>
void object_set_name(O * object, char const * name, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(object, );
IKARUS_FAIL_IF_OBJECT_MISSING(object, );
IKARUS_FAIL_IF_NULL(name, );
IKARUS_FAIL_IF_NAME_INVALID(name, object->project, object, );
IKARUS_TRYRV_OR_FAIL(
,
fmt::runtime(fmt::format("unable to set {} name: {{}}", ikarus_object_type_to_string(ikarus_id_get_object_type(object->id)))),
IkarusErrorInfo_Database_QueryFailed,
object->project->db->execute(fmt::format("UPDATE `{}` SET `name` = ? WHERE `id` = ?", object->get_table_name()), name, object->id)
);
}
} // namespace ikarus::util

View file

@ -0,0 +1,40 @@
#pragma once
#include <array>
#include <cppbase/assets.hpp>
#include <cppbase/result.hpp>
#include <sqlitecpp/connection.hpp>
namespace ikarus {
CPPBASE_ASSET(m0_initial_layout, "ikarus/persistence/migrations/m0_initial_layout.sql");
class Migration : public sqlitecpp::Migration {
public:
Migration(char const * sql, size_t size):
sql{sql, size} {}
~Migration() override = default;
public:
[[nodiscard]] inline auto get_content() const -> std::string_view override {
return sql;
}
public:
std::string_view sql;
};
#define DECLARE_MIGRATION(name) std::make_unique<ikarus::Migration>(static_cast<char const *>(name()), name##_size())
constexpr std::string_view DB_VERSION_KEY = "IKARUS_DB_VERSION";
std::vector<std::unique_ptr<sqlitecpp::Migration>> const MIGRATIONS = []() {
std::vector<std::unique_ptr<sqlitecpp::Migration>> ret;
ret.emplace_back(DECLARE_MIGRATION(m0_initial_layout));
return ret;
}();
} // namespace ikarus

View file

@ -0,0 +1,68 @@
CREATE TABLE `objects`
(
`do_not_access_rowid_alias` INTEGER PRIMARY KEY,
`type` INT NOT NULL,
`id` INT GENERATED ALWAYS AS (`do_not_access_rowid_alias` | (`type` << 56)) VIRTUAL UNIQUE
) STRICT;
CREATE UNIQUE INDEX `object_id` ON `objects` (`id`);
CREATE INDEX `object_type` ON `objects` (`type`);
CREATE TABLE `entities`
(
`id` INT,
`name` TEXT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE (`name`),
FOREIGN KEY (`id`) REFERENCES `objects` (`id`) ON DELETE CASCADE
) WITHOUT ROWID, STRICT;
CREATE TABLE `blueprints`
(
`id` INT,
`name` TEXT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE (`name`),
FOREIGN KEY (`id`) REFERENCES `objects` (`id`) ON DELETE CASCADE
) WITHOUT ROWID, STRICT;
CREATE TABLE `entity_blueprint_links`
(
`entity` INT NOT NULL,
`blueprint` INT NOT NULL,
PRIMARY KEY (`entity`, `blueprint`),
FOREIGN KEY (`entity`) REFERENCES `entities` (`id`) ON DELETE CASCADE,
FOREIGN KEY (`blueprint`) REFERENCES `blueprints` (`id`) ON DELETE CASCADE
) WITHOUT ROWID, STRICT;
CREATE TABLE `properties`
(
`id` INT,
`name` TEXT NOT NULL,
`type` INT NOT NULL,
`default_value` TEXT NOT NULL,
`settings` TEXT NOT NULL,
`source` INT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE(`source`, `name`),
FOREIGN KEY (`id`) REFERENCES `objects` (`id`) ON DELETE CASCADE,
FOREIGN KEY (`source`) REFERENCES `objects` (`id`) ON DELETE CASCADE
) WITHOUT ROWID, STRICT;
CREATE INDEX `properties_type` ON `properties` (`type`);
CREATE INDEX `properties_source` ON `properties` (`source`);
CREATE TABLE `values`
(
`entity` INT NOT NULL,
`property` INT NOT NULL,
`value` TEXT NOT NULL,
PRIMARY KEY (`entity`, `property`),
FOREIGN KEY (`entity`) REFERENCES `entities` (`id`) ON DELETE CASCADE,
FOREIGN KEY (`property`) REFERENCES `properties` (`id`) ON DELETE CASCADE
) WITHOUT ROWID, STRICT;

View file

@ -0,0 +1,277 @@
#include "ikarus/persistence/project.h"
#include <boost/filesystem.hpp>
#include <cppbase/strings.hpp>
#include <ikarus/objects/blueprint.hpp>
#include <ikarus/objects/entity.hpp>
#include <ikarus/objects/properties/number_property.hpp>
#include <ikarus/objects/properties/property.hpp>
#include <ikarus/objects/properties/text_property.hpp>
#include <ikarus/objects/properties/toggle_property.hpp>
#include <ikarus/persistence/migrations.hpp>
#include <ikarus/persistence/project.hpp>
IkarusProject::IkarusProject(std::string_view name, std::string_view path, std::unique_ptr<sqlitecpp::Connection> && db):
name{name},
path{std::move(path)},
db{std::move(db)},
_blueprints{},
_properties{},
_entities{} {}
IkarusBlueprint * IkarusProject::get_blueprint(IkarusId id) {
return get_cached_object<IkarusBlueprint>(id, this->_blueprints);
}
auto IkarusProject::uncache(IkarusBlueprint * blueprint) -> void {
remove_cached_object(blueprint, _blueprints);
}
auto IkarusProject::get_entity(IkarusId id) -> IkarusEntity * {
return get_cached_object<IkarusEntity>(id, this->_entities);
}
auto IkarusProject::uncache(IkarusEntity * entity) -> void {
remove_cached_object(entity, _entities);
}
auto IkarusProject::get_property(IkarusId id, IkarusPropertyType type) -> IkarusProperty * {
auto const iter = _properties.find(id);
if (iter == _properties.cend()) {
switch (type) {
case IkarusPropertyType_Toggle:
return _properties.emplace(id, std::make_unique<IkarusToggleProperty>(this, id)).first->second.get();
case IkarusPropertyType_Number:
return _properties.emplace(id, std::make_unique<IkarusNumberProperty>(this, id)).first->second.get();
case IkarusPropertyType_Text: return _properties.emplace(id, std::make_unique<IkarusTextProperty>(this, id)).first->second.get();
}
}
return iter->second.get();
}
auto IkarusProject::uncache(IkarusProperty * property) -> void {
remove_cached_object(property, _properties);
}
IkarusProject * ikarus_project_create(char const * path, char const * name, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(path, nullptr);
IKARUS_FAIL_IF_NULL(name, nullptr);
IKARUS_FAIL_IF(cppbase::is_empty_or_blank(path), nullptr, "path must not be empty", IkarusErrorInfo_Client_InvalidInput);
IKARUS_FAIL_IF(cppbase::is_empty_or_blank(name), nullptr, "name must not be empty", IkarusErrorInfo_Client_InvalidInput);
boost::filesystem::path fs_path{path};
{
boost::system::error_code ec;
bool const exists = fs::exists(fs_path, ec);
IKARUS_FAIL_IF(ec, nullptr, "unable to check whether path is occupied", IkarusErrorInfo_Filesystem_AlreadyExists);
IKARUS_FAIL_IF(exists, nullptr, "path is already occupied", IkarusErrorInfo_Filesystem_AlreadyExists);
}
IKARUS_VTRYRV_OR_FAIL(
auto db,
nullptr,
"failed to create project db: {}",
IkarusErrorInfo_Database_ConnectionFailed,
sqlitecpp::Connection::open(path)
);
IKARUS_TRYRV_OR_FAIL(
nullptr,
"failed to migrate project db: {}",
IkarusErrorInfo_Database_MigrationFailed,
db->migrate(ikarus::MIGRATIONS)
);
if (auto res = db->execute("INSERT INTO `metadata`(`key`, `value`) VALUES(?, ?)", DB_PROJECT_NAME_KEY, name); res.is_error()) {
boost::system::error_code ec;
fs::remove(fs_path, ec);
IKARUS_FAIL_IF(
ec,
nullptr,
"failed to remove project db after being unable to insert name into metadata table: {}",
IkarusErrorInfo_Filesystem_AccessIssue
);
IKARUS_FAIL(nullptr, "failed to insert project name into metadata: {}", IkarusErrorInfo_Database_QueryFailed);
}
return new IkarusProject{name, path, std::move(db)};
}
IkarusProject * ikarus_project_create_in_memory(char const * name, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(name, nullptr);
IKARUS_FAIL_IF(cppbase::is_empty_or_blank(name), nullptr, "name must not be empty", IkarusErrorInfo_Client_InvalidInput);
IKARUS_VTRYRV_OR_FAIL(
auto db,
nullptr,
"failed to create project db in memory: {}",
IkarusErrorInfo_Database_ConnectionFailed,
sqlitecpp::Connection::open_in_memory()
);
IKARUS_TRYRV_OR_FAIL(
nullptr,
"failed to migrate project db: {}",
IkarusErrorInfo_Database_MigrationFailed,
db->migrate(ikarus::MIGRATIONS)
);
IKARUS_TRYRV_OR_FAIL(
nullptr,
"failed to insert project name into metadata: {}",
IkarusErrorInfo_Database_QueryFailed,
db->execute("INSERT INTO `metadata`(`key`, `value`) VALUES(?, ?)", DB_PROJECT_NAME_KEY, name)
);
return new IkarusProject{name, ":memory:", std::move(db)};
}
IkarusProject * ikarus_project_open(char const * path, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(path, nullptr);
IKARUS_FAIL_IF(cppbase::is_empty_or_blank(path), nullptr, "path must not be empty", IkarusErrorInfo_Client_InvalidInput);
IKARUS_VTRYRV_OR_FAIL(
auto db,
nullptr,
"failed to open project db: {}",
IkarusErrorInfo_Database_ConnectionFailed,
sqlitecpp::Connection::open(path)
);
IKARUS_TRYRV_OR_FAIL(
nullptr,
"failed to migrate project db: {}",
IkarusErrorInfo_Database_MigrationFailed,
db->migrate(ikarus::MIGRATIONS)
);
IKARUS_VTRYRV_OR_FAIL(
auto const & name,
nullptr,
"failed to retrieve project name from metadata: {}",
IkarusErrorInfo_Database_QueryFailed,
db->query_one<std::string>("SELECT `value` FROM `metadata` WHERE `key` = ?", DB_PROJECT_NAME_KEY)
);
return new IkarusProject{name, path, std::move(db)};
}
char const * ikarus_project_get_name(IkarusProject const * project, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(project, nullptr);
return project->name.data();
}
void ikarus_project_set_name(IkarusProject * project, char const * new_name, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(project, );
IKARUS_FAIL_IF_NULL(new_name, );
IKARUS_FAIL_IF(cppbase::is_empty_or_blank(new_name), , "name must not be empty", IkarusErrorInfo_Client_InvalidInput);
IKARUS_TRYRV_OR_FAIL(
,
"failed to update project name: {}",
IkarusErrorInfo_Database_QueryFailed,
project->db->execute("UPDATE `metadata` SET `value` = ? WHERE `key` = ?", new_name, DB_PROJECT_NAME_KEY)
);
}
char const * ikarus_project_get_path(IkarusProject const * project, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(project, nullptr);
return project->path.data();
}
// these take a mutable project right now because the get_cached-* function must be mutable
// since we insert a backreference to the project into the objects, not ideal,
// but fine for now since "mutability" is a vague concept for projects anyway
void ikarus_project_get_blueprints(
IkarusProject * project,
struct IkarusBlueprint ** blueprints_out,
size_t blueprints_out_size,
IkarusErrorData * error_out
) {
IKARUS_FAIL_IF_NULL(project, );
IKARUS_FAIL_IF_NULL(blueprints_out, );
if (blueprints_out_size == 0) {
return;
}
IkarusId ids[blueprints_out_size];
IKARUS_TRYRV_OR_FAIL(
,
"unable to fetch project blueprints from database: {}",
IkarusErrorInfo_Database_QueryFailed,
project->db->query_many_buffered<IkarusId>("SELECT `id` FROM `blueprints`", ids, blueprints_out_size)
);
for (size_t i = 0; i < blueprints_out_size; ++i) {
blueprints_out[i] = project->get_blueprint(ids[i]);
}
}
size_t ikarus_project_get_blueprint_count(IkarusProject const * project, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(project, 0);
IKARUS_VTRYRV_OR_FAIL(
auto const ret,
0,
"unable to fetch project blueprint count from database: {}",
IkarusErrorInfo_Database_QueryFailed,
project->db->query_one<int64_t>("SELECT COUNT(*) FROM `blueprints`")
);
return ret;
}
void ikarus_project_get_entities(
IkarusProject * project,
struct IkarusEntity ** entities_out,
size_t entities_out_size,
IkarusErrorData * error_out
) {
IKARUS_FAIL_IF_NULL(project, );
IKARUS_FAIL_IF_NULL(entities_out, );
if (entities_out_size == 0) {
return;
}
IkarusId ids[entities_out_size];
IKARUS_TRYRV_OR_FAIL(
,
"unable to fetch project entities from database: {}",
IkarusErrorInfo_Database_QueryFailed,
project->db->query_many_buffered<IkarusId>("SELECT `id` FROM `entities`", ids, entities_out_size)
);
for (size_t i = 0; i < entities_out_size; ++i) {
entities_out[i] = project->get_entity(ids[i]);
}
}
size_t ikarus_project_get_entity_count(IkarusProject * project, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(project, 0);
IKARUS_VTRYRV_OR_FAIL(
auto const ret,
0,
"unable to fetch project entity count from database: {}",
IkarusErrorInfo_Database_QueryFailed,
project->db->query_one<int64_t>("SELECT COUNT(*) FROM `entities`")
);
return ret;
}

View file

@ -0,0 +1,61 @@
#pragma once
#include <ranges>
#include <stack>
#include <string>
#include <boost/filesystem.hpp>
#include <sqlitecpp/connection.hpp>
#include <ikarus/errors.h>
#include <ikarus/id.h>
#include <ikarus/objects/properties/property_type.h>
namespace fs = boost::filesystem;
/// \private
struct IkarusProject {
public:
IkarusProject(std::string_view name, std::string_view path, std::unique_ptr<sqlitecpp::Connection> && db);
public:
[[nodiscard]] auto get_blueprint(IkarusId id) -> struct IkarusBlueprint *;
auto uncache(struct IkarusBlueprint * blueprint) -> void;
[[nodiscard]] auto get_entity(IkarusId id) -> struct IkarusEntity *;
auto uncache(struct IkarusEntity * entity) -> void;
// TODO improve this to take a template param so that we don't have to cast in e.g. ikarus_toggle_property_create
[[nodiscard]] auto get_property(IkarusId id, IkarusPropertyType type) -> struct IkarusProperty *;
auto uncache(struct IkarusProperty * property) -> void;
private:
template<typename T>
[[nodiscard]] T * get_cached_object(IkarusId id, auto & cache) {
auto const iter = cache.find(id);
if (iter == cache.cend()) {
return cache.emplace(id, std::make_unique<T>(this, id)).first->second.get();
}
return iter->second.get();
}
template<typename T>
void remove_cached_object(T * object, std::unordered_map<IkarusId, std::unique_ptr<T>> & cache) {
cache.erase(object->id);
}
public:
std::string name;
std::string_view path;
std::unique_ptr<sqlitecpp::Connection> db;
private:
std::unordered_map<IkarusId, std::unique_ptr<struct IkarusBlueprint>> mutable _blueprints;
std::unordered_map<IkarusId, std::unique_ptr<struct IkarusProperty>> mutable _properties;
std::unordered_map<IkarusId, std::unique_ptr<struct IkarusEntity>> mutable _entities;
};
constexpr std::string_view DB_PROJECT_NAME_KEY = "PROJECT_NAME";

View file

@ -0,0 +1,21 @@
#include "entity_property_value.hpp"
#include <ikarus/errors.hpp>
IkarusEntity const * ikarus_entity_property_value_get_entity(IkarusEntityPropertyValue const * value, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(value, nullptr);
return value->entity;
}
IkarusProperty const * ikarus_entity_property_value_get_property(IkarusEntityPropertyValue const * value, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(value, nullptr);
return value->property;
}
IkarusValue const * ikarus_entity_property_value_get_value(IkarusEntityPropertyValue const * value, IkarusErrorData * error_out) {
IKARUS_FAIL_IF_NULL(value, nullptr);
return value->value;
}

View file

@ -0,0 +1,7 @@
#pragma once
struct IkarusEntityPropertyValue {
struct IkarusEntity const * entity;
struct IkarusProperty const * property;
struct IkarusValue const * value;
};

View file

@ -0,0 +1,65 @@
#include "ikarus/values/number_value.h"
#include <boost/functional/overloaded_function.hpp>
#include <ikarus/values/number_value.hpp>
#include <ikarus/values/value_base.hpp>
IkarusNumberValue::IkarusNumberValue():
IkarusValue{this} {}
IkarusNumberValue * ikarus_number_value_create() {
return new IkarusNumberValue{};
}
double const * ikarus_number_value_get(IkarusNumberValue * value, size_t idx) {
return ikarus_value_base_get(value, idx);
}
size_t ikarus_number_value_get_size(IkarusNumberValue const * value) {
return ikarus_value_base_get_size(value);
}
void ikarus_number_value_set(IkarusNumberValue * value, size_t idx, double new_data) {
return ikarus_value_base_set(value, idx, new_data);
}
void ikarus_number_value_remove(IkarusNumberValue * value, size_t idx) {
return ikarus_value_base_remove(value, idx);
}
void ikarus_number_value_insert(IkarusNumberValue * value, size_t idx, long double new_data) {
return ikarus_value_base_insert(value, idx, new_data);
}
void ikarus_number_value_clear(IkarusNumberValue * value) {
return ikarus_value_base_clear(value);
}
bool ikarus_number_value_is_undefined(IkarusNumberValue const * value) {
return ikarus_value_base_is_undefined(value);
}
void ikarus_number_value_set_undefined(IkarusNumberValue * value, bool undefined) {
return ikarus_value_base_set_undefined(value, undefined);
}
char const * ikarus_number_value_to_string(IkarusNumberValue const * value) {
return ikarus_value_base_to_string(value, [](auto const & value) { return value; });
}
bool ikarus_number_value_is_equal(IkarusNumberValue const * lhs, IkarusNumberValue const * rhs) {
return ikarus_value_base_is_equal(lhs, rhs);
}
IkarusNumberValue * ikarus_number_value_copy(IkarusNumberValue const * value) {
return ikarus_value_base_copy(value);
}
struct IkarusValue * ikarus_number_value_to_value(IkarusNumberValue * value) {
return ikarus_value_base_to_value(value);
}
struct IkarusValue const * ikarus_number_value_to_value_const(IkarusNumberValue const * value) {
return ikarus_value_base_to_value_const(value);
}

View file

@ -0,0 +1,25 @@
#pragma once
#include <boost/container/small_vector.hpp>
#include <boost/variant2.hpp>
#include <ikarus/values/value.hpp>
struct IkarusNumberValue : IkarusValue {
public:
using DataType = double;
public:
explicit IkarusNumberValue();
IkarusNumberValue(IkarusNumberValue const &) = default;
IkarusNumberValue(IkarusNumberValue &&) = default;
IkarusNumberValue & operator=(IkarusNumberValue const &) = default;
IkarusNumberValue & operator=(IkarusNumberValue &&) = default;
~IkarusNumberValue() override = default;
public:
boost::variant2::variant<boost::variant2::monostate, boost::container::small_vector<DataType, SMALL_VEC_VALUE_SIZE>> data{};
};

View file

@ -0,0 +1,66 @@
#include "ikarus/values/text_value.h"
#include <boost/bind/bind.hpp>
#include <boost/functional/overloaded_function.hpp>
#include <ikarus/values/text_value.hpp>
#include <ikarus/values/value_base.hpp>
IkarusTextValue::IkarusTextValue():
IkarusValue{this} {}
IkarusTextValue * ikarus_text_value_create() {
return new IkarusTextValue{};
}
char const * ikarus_text_value_get(IkarusTextValue * value, size_t idx) {
return ikarus_value_base_get(value, idx)->data();
}
size_t ikarus_text_value_get_size(IkarusTextValue const * value) {
return ikarus_value_base_get_size(value);
}
void ikarus_text_value_set(IkarusTextValue * value, size_t idx, char const * new_data) {
return ikarus_value_base_set(value, idx, new_data);
}
void ikarus_text_value_remove(IkarusTextValue * value, size_t idx) {
return ikarus_value_base_remove(value, idx);
}
void ikarus_text_value_insert(IkarusTextValue * value, size_t idx, char const * new_data) {
return ikarus_value_base_insert(value, idx, new_data);
}
void ikarus_text_value_clear(IkarusTextValue * value) {
return ikarus_value_base_clear(value);
}
bool ikarus_text_value_is_undefined(IkarusTextValue const * value) {
return ikarus_value_base_is_undefined(value);
}
void ikarus_text_value_set_undefined(IkarusTextValue * value, bool undefined) {
return ikarus_value_base_set_undefined(value, undefined);
}
char const * ikarus_text_value_to_string(IkarusTextValue const * value) {
return ikarus_value_base_to_string(value, [](auto const & value) { return value; });
}
bool ikarus_text_value_is_equal(IkarusTextValue const * lhs, IkarusTextValue const * rhs) {
return ikarus_value_base_is_equal(lhs, rhs);
}
IkarusTextValue * ikarus_text_value_copy(IkarusTextValue const * value) {
return ikarus_value_base_copy(value);
}
struct IkarusValue * ikarus_text_value_to_value(IkarusTextValue * value) {
return ikarus_value_base_to_value(value);
}
struct IkarusValue const * ikarus_text_value_to_value_const(IkarusTextValue const * value) {
return ikarus_value_base_to_value_const(value);
}

View file

@ -0,0 +1,24 @@
#pragma once
#include <boost/container/small_vector.hpp>
#include <ikarus/values/value.hpp>
struct IkarusTextValue : IkarusValue {
public:
using DataType = std::string;
public:
explicit IkarusTextValue();
IkarusTextValue(IkarusTextValue const &) = default;
IkarusTextValue(IkarusTextValue &&) = default;
IkarusTextValue & operator=(IkarusTextValue const &) = default;
IkarusTextValue & operator=(IkarusTextValue &&) = default;
~IkarusTextValue() override = default;
public:
boost::variant2::variant<boost::variant2::monostate, boost::container::small_vector<DataType, SMALL_VEC_VALUE_SIZE>> data{};
};

View file

@ -0,0 +1,66 @@
#include "ikarus/values/toggle_value.h"
#include <boost/functional/overloaded_function.hpp>
#include <boost/range/adaptors.hpp>
#include <ikarus/values/toggle_value.hpp>
#include <ikarus/values/value_base.hpp>
IkarusToggleValue::IkarusToggleValue():
IkarusValue{this} {}
IkarusToggleValue * ikarus_toggle_value_create() {
return new IkarusToggleValue{};
}
bool const * ikarus_toggle_value_get(IkarusToggleValue * value, size_t idx) {
return ikarus_value_base_get(value, idx);
}
size_t ikarus_toggle_value_get_size(IkarusToggleValue const * value) {
return ikarus_value_base_get_size(value);
}
void ikarus_toggle_value_set(IkarusToggleValue * value, size_t idx, bool new_data) {
return ikarus_value_base_set(value, idx, new_data);
}
void ikarus_toggle_value_remove(IkarusToggleValue * value, size_t idx) {
return ikarus_value_base_remove(value, idx);
}
void ikarus_toggle_value_insert(IkarusToggleValue * value, size_t idx, bool new_data) {
return ikarus_value_base_insert(value, idx, new_data);
}
void ikarus_toggle_value_clear(IkarusToggleValue * value) {
return ikarus_value_base_clear(value);
}
bool ikarus_toggle_value_is_undefined(IkarusToggleValue const * value) {
return ikarus_value_base_is_undefined(value);
}
void ikarus_toggle_value_set_undefined(IkarusToggleValue * value, bool undefined) {
return ikarus_value_base_set_undefined(value, undefined);
}
char const * ikarus_toggle_value_to_string(IkarusToggleValue const * value) {
return ikarus_value_base_to_string(value, [](auto const & value) { return value ? "" : ""; });
}
bool ikarus_toggle_value_is_equal(IkarusToggleValue const * lhs, IkarusToggleValue const * rhs) {
return ikarus_value_base_is_equal(lhs, rhs);
}
IkarusToggleValue * ikarus_toggle_value_copy(IkarusToggleValue const * value) {
return ikarus_value_base_copy(value);
}
struct IkarusValue * ikarus_toggle_value_to_value(IkarusToggleValue * value) {
return ikarus_value_base_to_value(value);
}
struct IkarusValue const * ikarus_toggle_value_to_value_const(IkarusToggleValue const * value) {
return ikarus_value_base_to_value_const(value);
}

View file

@ -0,0 +1,24 @@
#pragma once
#include <boost/container/small_vector.hpp>
#include <ikarus/values/value.hpp>
struct IkarusToggleValue : IkarusValue {
public:
using DataType = bool;
public:
explicit IkarusToggleValue();
IkarusToggleValue(IkarusToggleValue const &) = default;
IkarusToggleValue(IkarusToggleValue &&) = default;
IkarusToggleValue & operator=(IkarusToggleValue const &) = default;
IkarusToggleValue & operator=(IkarusToggleValue &&) = default;
~IkarusToggleValue() override = default;
public:
boost::variant2::variant<boost::variant2::monostate, boost::container::small_vector<DataType, SMALL_VEC_VALUE_SIZE>> data{};
};

138
src/ikarus/values/value.cpp Normal file
View file

@ -0,0 +1,138 @@
#include "ikarus/values/value.h"
#include <string>
#include <boost/container/small_vector.hpp>
// required for header-only inclusion
#include "cppbase/templates.hpp"
#include <boost/json/src.hpp>
#include <ikarus/objects/properties/property_type.h>
#include <ikarus/values/number_value.hpp>
#include <ikarus/values/text_value.hpp>
#include <ikarus/values/toggle_value.hpp>
#include <ikarus/values/value.hpp>
IkarusValue::IkarusValue(Data data):
data(data) {}
cppbase::Result<IkarusValue *, IkarusValue::FromJsonError> IkarusValue::from_json(boost::json::value json) {
if (auto const * obj = json.if_object(); obj == nullptr) {
return cppbase::err(FromJsonError{});
} else {
boost::int64_t const * type = nullptr;
boost::json::value const * data = nullptr;
if (auto const * type_value = obj->if_contains("type"); type_value == nullptr) {
return cppbase::err(FromJsonError{});
} else if (type = type_value->if_int64(); type == nullptr) {
return cppbase::err(FromJsonError{});
}
if (data = obj->if_contains("data"); data == nullptr) {
return cppbase::err(FromJsonError{});
}
auto create_value = [data]<typename T>() -> cppbase::Result<IkarusValue *, FromJsonError> {
T * ret = nullptr;
if (data->is_null()) {
ret = new T{};
ret->data = boost::variant2::monostate{};
} else {
auto res =
boost::json::try_value_to<boost::container::small_vector<typename T::DataType, IkarusValue::SMALL_VEC_VALUE_SIZE>>(*data
);
if (res.has_error()) {
return cppbase::err(FromJsonError{});
}
ret = new T{};
ret->data = std::move(res.value());
}
return cppbase::ok(ret);
};
switch (*type) {
case IkarusPropertyType_Toggle: {
return create_value.operator()<IkarusToggleValue>();
}
case IkarusPropertyType_Number: {
return create_value.operator()<IkarusNumberValue>();
}
case IkarusPropertyType_Text: {
return create_value.operator()<IkarusTextValue>();
}
default: {
return cppbase::err(FromJsonError{});
}
}
}
}
boost::json::value IkarusValue::to_json() const {
auto type = boost::variant2::visit(
cppbase::overloaded{
[]([[maybe_unused]] IkarusToggleValue const * value) { return IkarusPropertyType_Toggle; },
[]([[maybe_unused]] IkarusNumberValue const * value) { return IkarusPropertyType_Number; },
[]([[maybe_unused]] IkarusTextValue const * value) { return IkarusPropertyType_Text; }
},
data
);
auto data_json = boost::variant2::visit(
[]<typename T>(T const * value) -> boost::json::value {
return boost::variant2::visit(
cppbase::overloaded{
[]([[maybe_unused]] boost::variant2::monostate const & data) -> boost::json::value { return nullptr; },
[](auto const & data) -> boost::json::value { return boost::json::value_from(data); }
},
value->data
);
},
data
);
return {
{"type", type},
{"data", data_json}
};
}
void ikarus_value_visit(
IkarusValue * value,
void (*toggle_visitor)(IkarusToggleValue *, void *),
void (*number_visitor)(IkarusNumberValue *, void *),
void (*text_visitor)(IkarusTextValue *, void *),
void * data
) {
boost::variant2::visit(
cppbase::overloaded{
[toggle_visitor, data](IkarusToggleValue * toggle_value) { toggle_visitor(toggle_value, data); },
[number_visitor, data](IkarusNumberValue * number_value) { number_visitor(number_value, data); },
[text_visitor, data](IkarusTextValue * text_value) { text_visitor(text_value, data); }
},
value->data
);
}
void ikarus_value_visit_const(
IkarusValue const * value,
void (*toggle_visitor)(IkarusToggleValue const *, void *),
void (*number_visitor)(IkarusNumberValue const *, void *),
void (*text_visitor)(IkarusTextValue const *, void *),
void * data
) {
boost::variant2::visit(
cppbase::overloaded{
[toggle_visitor, data](IkarusToggleValue const * toggle_value) { toggle_visitor(toggle_value, data); },
[number_visitor, data](IkarusNumberValue const * number_value) { number_visitor(number_value, data); },
[text_visitor, data](IkarusTextValue const * text_value) { text_visitor(text_value, data); }
},
value->data
);
}

View file

@ -0,0 +1,76 @@
#pragma once
#include <boost/json.hpp>
#include <boost/variant2.hpp>
#include <cppbase/result.hpp>
#include <ikarus/errors.hpp>
#include <ikarus/persistence/project.hpp>
struct IkarusValue {
public:
using Data = boost::variant2::variant<struct IkarusToggleValue *, struct IkarusNumberValue *, struct IkarusTextValue *>;
constexpr static auto SMALL_VEC_VALUE_SIZE = 8;
public:
explicit IkarusValue(Data data);
IkarusValue(IkarusValue const &) = default;
IkarusValue(IkarusValue &&) noexcept = default;
IkarusValue & operator=(IkarusValue const &) = default;
IkarusValue & operator=(IkarusValue &&) noexcept = default;
virtual ~IkarusValue() = default;
public:
struct FromJsonError {};
[[nodiscard]] static cppbase::Result<IkarusValue *, FromJsonError> from_json(boost::json::value json);
[[nodiscard]] boost::json::value to_json() const;
public:
Data data;
};
template<>
struct fmt::formatter<IkarusValue::FromJsonError> {
template<typename FormatParseContext>
constexpr static auto parse(FormatParseContext & ctx) {
return ctx.end();
}
constexpr static auto format([[maybe_unused]] IkarusValue::FromJsonError const & error, fmt::format_context & ctx) {
return fmt::format_to(ctx.out(), "unable to parse ikarus value JSON");
}
};
template<typename... Args>
IkarusValue * fetch_value_from_db(IkarusProject * project, IkarusErrorData * error_out, std::string_view query, Args &&... args) {
IKARUS_VTRYRV_OR_FAIL(
auto const value_str,
nullptr,
"unable to fetch entity property value from database: {}",
IkarusErrorInfo_Database_QueryFailed,
project->db->query_one<std::string>(query, std::forward<Args>(args)...)
);
boost::json::error_code ec{};
boost::json::value json_value = boost::json::parse(value_str, ec);
if (ec) {
IKARUS_SET_ERROR(fmt::format("invalid json is stored in database: {}", ec.message()), IkarusErrorInfo_Database_InvalidState);
return nullptr;
}
IKARUS_VTRYRV_OR_FAIL(
auto const ret,
nullptr,
"unable to fetch entity property value: {}",
IkarusErrorInfo_LibIkarus_CannotPerformOperation,
IkarusValue::from_json(std::move(json_value))
);
return ret;
}

View file

@ -0,0 +1,120 @@
#pragma once
#include <ranges>
#include <boost/container/small_vector.hpp>
#include <cppbase/templates.hpp>
template<typename V>
typename V::DataType const * ikarus_value_base_get(V * value, size_t idx) {
if (auto * data =
boost::variant2::get_if<boost::container::small_vector<typename V::DataType, IkarusValue::SMALL_VEC_VALUE_SIZE>>(&value->data);
data != nullptr) {
return &(*data)[idx];
}
return nullptr;
}
template<typename V>
size_t ikarus_value_base_get_size(V const * value) {
if (auto * data =
boost::variant2::get_if<boost::container::small_vector<typename V::DataType, IkarusValue::SMALL_VEC_VALUE_SIZE>>(&value->data);
data != nullptr) {
return data->size();
}
return 0;
}
template<typename V>
void ikarus_value_base_set(V * value, size_t idx, typename V::DataType new_data) {
if (auto * data =
boost::variant2::get_if<boost::container::small_vector<typename V::DataType, IkarusValue::SMALL_VEC_VALUE_SIZE>>(&value->data);
data != nullptr) {
(*data)[idx] = new_data;
}
}
template<typename V>
void ikarus_value_base_remove(V * value, size_t idx) {
if (auto * data =
boost::variant2::get_if<boost::container::small_vector<typename V::DataType, IkarusValue::SMALL_VEC_VALUE_SIZE>>(&value->data);
data != nullptr) {
data->erase(data->begin() + idx);
}
}
template<typename V>
void ikarus_value_base_insert(V * value, size_t idx, typename V::DataType new_data) {
if (auto * data =
boost::variant2::get_if<boost::container::small_vector<typename V::DataType, IkarusValue::SMALL_VEC_VALUE_SIZE>>(&value->data);
data != nullptr) {
data->insert(data->begin() + idx, new_data);
}
}
template<typename V>
void ikarus_value_base_clear(V * value) {
if (auto * data =
boost::variant2::get_if<boost::container::small_vector<typename V::DataType, IkarusValue::SMALL_VEC_VALUE_SIZE>>(&value->data);
data != nullptr) {
data->clear();
}
}
template<typename V>
bool ikarus_value_base_is_undefined(V const * value) {
return boost::variant2::holds_alternative<boost::variant2::monostate>(value->data);
}
template<typename V>
void ikarus_value_base_set_undefined(V * value, bool undefined) {
if (undefined) {
value->data = boost::variant2::monostate{};
} else {
value->data = boost::container::small_vector<typename V::DataType, IkarusValue::SMALL_VEC_VALUE_SIZE>{};
}
}
template<typename V, std::invocable<typename V::DataType> F>
char const * ikarus_value_base_to_string(V const * value, F transformer) {
return boost::variant2::visit(
cppbase::overloaded{
[](boost::variant2::monostate const &) -> char const * { return nullptr; },
[&transformer](auto const & data) -> char const * {
auto buffer = fmt::memory_buffer{};
fmt::format_to(
std::back_inserter(buffer),
"{}",
fmt::join(data | std::views::transform(std::forward<F>(transformer)), ", ")
);
return buffer.data();
}
},
value->data
);
}
template<typename V>
bool ikarus_value_base_is_equal(V const * lhs, V const * rhs) {
return lhs->data == rhs->data;
}
template<typename V>
V * ikarus_value_base_copy(V const * value) {
return new V{*value};
}
template<typename V>
struct IkarusValue * ikarus_value_base_to_value(V * value) {
return static_cast<IkarusValue *>(value);
}
template<typename V>
struct IkarusValue const * ikarus_value_base_to_value_const(V const * value) {
return static_cast<IkarusValue const *>(value);
}