Skip to content

Database connection control options #1399

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 27 additions & 9 deletions dev/connection_holder.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include <sqlite3.h>
#ifndef SQLITE_ORM_IMPORT_STD_MODULE
#include <atomic>
#include <functional> // std::function
#include <string> // std::string
#endif

Expand All @@ -12,25 +13,38 @@ namespace sqlite_orm {
namespace internal {

struct connection_holder {
connection_holder(std::string filename) : filename(std::move(filename)) {}
connection_holder(std::string filename, std::function<void(sqlite3*)> onAfterOpen) :
_onAfterOpen{std::move(onAfterOpen)}, filename(std::move(filename)) {}

connection_holder(const connection_holder&) = delete;

connection_holder(const connection_holder& other, std::function<void(sqlite3*)> onAfterOpen) :
_onAfterOpen{std::move(onAfterOpen)}, filename{other.filename} {}

void retain() {
// first one opens the connection.
// we presume that the connection is opened once in a single-threaded context [also open forever].
// therefore we can just use an atomic increment but don't need sequencing due to `prevCount > 0`.
if (this->_retain_count.fetch_add(1, std::memory_order_relaxed) == 0) {
int rc = sqlite3_open(this->filename.c_str(), &this->db);
if (_retainCount.fetch_add(1, std::memory_order_relaxed) == 0) {
int rc = sqlite3_open_v2(this->filename.c_str(),
&this->db,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
nullptr);
if (rc != SQLITE_OK) SQLITE_ORM_CPP_UNLIKELY /*possible, but unexpected*/ {
throw_translated_sqlite_error(this->db);
}
}

if (_onAfterOpen) {
_onAfterOpen(this->db);
}
}

void release() {
// last one closes the connection.
// we assume that this might happen by any thread, therefore the counter must serve as a synchronization point.
if (this->_retain_count.fetch_sub(1, std::memory_order_acq_rel) == 1) {
int rc = sqlite3_close(this->db);
if (_retainCount.fetch_sub(1, std::memory_order_acq_rel) == 1) {
int rc = sqlite3_close_v2(this->db);
if (rc != SQLITE_OK) SQLITE_ORM_CPP_UNLIKELY {
throw_translated_sqlite_error(this->db);
} else {
Expand All @@ -48,16 +62,20 @@ namespace sqlite_orm {
* @attention While retrieving the reference count value is atomic it makes only sense at single-threaded points in code.
*/
int retain_count() const {
return this->_retain_count.load(std::memory_order_relaxed);
return _retainCount.load(std::memory_order_relaxed);
}

const std::string filename;

protected:
sqlite3* db = nullptr;

private:
std::atomic_int _retain_count{};
std::atomic_int _retainCount{};

private:
const std::function<void(sqlite3* db)> _onAfterOpen;

public:
const std::string filename;
};

struct connection_ref {
Expand Down
5 changes: 4 additions & 1 deletion dev/functional/cxx_core_features.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,12 @@
#define SQLITE_ORM_STRUCTURED_BINDINGS_SUPPORTED
#endif

#if __cpp_deduction_guides >= 201703L
#define SQLITE_ORM_CTAD_SUPPORTED
#endif

#if __cpp_generic_lambdas >= 201707L
#define SQLITE_ORM_EXPLICIT_GENERIC_LAMBDA_SUPPORTED
#else
#endif

#if __cpp_init_captures >= 201803L
Expand Down
14 changes: 13 additions & 1 deletion dev/functional/mpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ namespace sqlite_orm {
* Commonly used named abbreviation for `check_if<std::is_same, Type>`.
*/
template<class Type>
using check_if_is_type = mpl::bind_front_fn<std::is_same, Type>;
using check_if_is_type = check_if<std::is_same, Type>;

/*
* Quoted trait metafunction that checks if a type's template matches the specified template
Expand All @@ -463,6 +463,18 @@ namespace sqlite_orm {
using check_if_is_template =
mpl::pass_extracted_fn_to<mpl::bind_front_fn<std::is_same, mpl::quote_fn<Template>>>;

/*
* Quoted trait metafunction that checks if a type names a nested type determined by `Op`.
*/
template<template<typename...> class Op>
using check_if_names = mpl::bind_front_higherorder_fn<polyfill::is_detected, Op>;

/*
* Quoted trait metafunction that checks if a type does not name a nested type determined by `Op`.
*/
template<template<typename...> class Op>
using check_if_lacks = mpl::not_<check_if_names<Op>>;

/*
* Quoted metafunction that finds the index of the given type in a tuple.
*/
Expand Down
9 changes: 5 additions & 4 deletions dev/pragma.h
Original file line number Diff line number Diff line change
Expand Up @@ -258,11 +258,12 @@ namespace sqlite_orm {
}

void set_pragma_impl(const std::string& query, sqlite3* db = nullptr) {
auto con = this->get_connection();
if (db == nullptr) {
db = con.get();
if (db) {
perform_void_exec(db, query);
} else {
auto con = this->get_connection();
perform_void_exec(con.get(), query);
}
perform_void_exec(db, query);
}
};
}
Expand Down
67 changes: 59 additions & 8 deletions dev/storage.h
Original file line number Diff line number Diff line change
Expand Up @@ -81,21 +81,39 @@ namespace sqlite_orm {
polyfill::void_t<indirectly_test_preparable<decltype(std::declval<S>().prepare(std::declval<E>()))>>> =
true;

template<class Opt, class OptionsTpl>
decltype(auto) storage_opt_or_default(OptionsTpl& options) {
#ifdef SQLITE_ORM_CTAD_SUPPORTED
if constexpr (tuple_has_type<OptionsTpl, Opt>::value) {
return std::move(std::get<Opt>(options));
} else {
return Opt{};
}
#else
return Opt{};
#endif
}

/**
* Storage class itself. Create an instanse to use it as an interfacto to sqlite db by calling `make_storage`
* function.
*/
template<class... DBO>
struct storage_t : storage_base {
using self = storage_t<DBO...>;
using self_type = storage_t;
using db_objects_type = db_objects_tuple<DBO...>;

/**
* @param filename database filename.
* @param dbObjects db_objects_tuple
*/
storage_t(std::string filename, db_objects_type dbObjects) :
storage_base{std::move(filename), foreign_keys_count(dbObjects)}, db_objects{std::move(dbObjects)} {}
template<class OptionsTpl>
storage_t(std::string filename, db_objects_type dbObjects, OptionsTpl options) :
storage_base{std::move(filename),
storage_opt_or_default<connection_control>(options),
storage_opt_or_default<on_open_spec>(options),
foreign_keys_count(dbObjects)},
db_objects{std::move(dbObjects)} {}

storage_t(const storage_t&) = default;

Expand All @@ -114,7 +132,7 @@ namespace sqlite_orm {
*
* Hence, friend was replaced by `obtain_db_objects()` and `pick_const_impl()`.
*/
friend const db_objects_type& obtain_db_objects(const self& storage) noexcept {
friend const db_objects_type& obtain_db_objects(const self_type& storage) noexcept {
return storage.db_objects;
}

Expand Down Expand Up @@ -246,7 +264,7 @@ namespace sqlite_orm {

public:
template<class T, class O = mapped_type_proxy_t<T>, class... Args>
mapped_view<O, self, Args...> iterate(Args&&... args) {
mapped_view<O, self_type, Args...> iterate(Args&&... args) {
this->assert_mapped_type<O>();

auto con = this->get_connection();
Expand Down Expand Up @@ -781,7 +799,7 @@ namespace sqlite_orm {
std::enable_if_t<!is_prepared_statement<Ex>::value && !is_mapped<db_objects_type, Ex>::value,
bool> = true>
std::string dump(E&& expression, bool parametrized = false) const {
static_assert(is_preparable_v<self, Ex>, "Expression must be a high-level statement");
static_assert(is_preparable_v<self_type, Ex>, "Expression must be a high-level statement");

decltype(auto) e2 = static_if<is_select<Ex>::value>(
[](auto expression) -> auto {
Expand Down Expand Up @@ -1702,17 +1720,50 @@ namespace sqlite_orm {
}
#endif // SQLITE_ORM_OPTIONAL_SUPPORTED
}; // struct storage_t

#ifdef SQLITE_ORM_CTAD_SUPPORTED
template<class Elements>
using dbo_index_sequence = filter_tuple_sequence_t<Elements, check_if_lacks<storage_opt_tag_t>::template fn>;

template<class Elements>
using opt_index_sequence = filter_tuple_sequence_t<Elements, check_if_names<storage_opt_tag_t>::template fn>;

template<class... DBO, class OptionsTpl>
storage_t<DBO...> make_storage(std::string filename, std::tuple<DBO...> dbObjects, OptionsTpl options) {
return {std::move(filename), std::move(dbObjects), std::move(options)};
}
#endif
}
}

SQLITE_ORM_EXPORT namespace sqlite_orm {
#ifdef SQLITE_ORM_CTAD_SUPPORTED
/*
* Factory function for a storage instance, from a database file, a set of database object definitions
* and option storage options like connection control options and an 'on open' callback.
*
* E.g.
* auto storage = make_storage("", connection_control{.open_forever = true}, on_open([](sqlite3* db) {}));
*/
template<class... Spec>
auto make_storage(std::string filename, Spec... specifications) {
using namespace ::sqlite_orm::internal;

std::tuple specTuple{std::forward<Spec>(specifications)...};
return internal::make_storage(
std::move(filename),
create_from_tuple<std::tuple>(std::move(specTuple), dbo_index_sequence<decltype(specTuple)>{}),
create_from_tuple<std::tuple>(std::move(specTuple), opt_index_sequence<decltype(specTuple)>{}));
}
#else
/*
* Factory function for a storage, from a database file and a bunch of database object definitions.
* Factory function for a storage instance, from a database file and a bunch of database object definitions.
*/
template<class... DBO>
internal::storage_t<DBO...> make_storage(std::string filename, DBO... dbObjects) {
return {std::move(filename), internal::db_objects_tuple<DBO...>{std::forward<DBO>(dbObjects)...}};
return {std::move(filename), {std::forward<DBO>(dbObjects)...}, std::tuple<>{}};
}
#endif

/**
* sqlite3_threadsafe() interface.
Expand Down
Loading