Database Helpers
The DatabaseHelpers<T>
class is a helper to implement some basic functionalities for a dedicated type. It focuses on fetching from the database, but also exposes a helper to delete an entity from the DB.
It is meant to be inherited by the class representing an entity in database. For instance, the Media
class is declared as such:
class Media : public IMedia,
public DatabaseHelpers<Media>
Functionalities
-
fetch
allows to fetch a single entity (so a single row from the database). 2 flavors are available: one that uses a primary key, one that takes a request and an arbitrary number of arguments that will be bound to the request -
fetchAll
is very similar to fetch, except it will return more than one entity -
destroy
will delete an entity with the given primary key from the database -
deleteAll
will delete all entities from the table associated with the entities targeted -
insert
is used by the various creation factories to insert the entity in database and fetch the newly inserted entity's primary key
Requirements
Table
inner class
All operations need a table name, and must be able to access it based on the DatabaseHelpers
template parameter. The insertion operation also requires a way to modify the member variable containing the entity primary key.
In order to do so, all classes leveraging the DatabaseHelpers<T>
class are expected to implement an inner class name Table
. This class must provide those members:
-
Name
(std::string
or compatible) containing the name of the table -
PrimaryKeyColumn
(std::string
or compatible) containing the name of the column holding the primary key -
PrimaryKey
(int64_t T::* const
) storing a pointer to the member containing the primary key
This is enforced through duck typing, but could (and probably should) be expressed through a concept once we can use a recent enough C++ version.
Providing the table name in a dedicated constant also helps finding reference to that table without relying on text based search, which often proves useful.
sqlite::Row based constructor(s)
In order for the fetch
and fetchAll
helpers to instantiate a class representing a row, all entity classes are expected to expose a constructor taking a media library instance and a database row.
For instance, for the Media
class again:
Media( MediaLibraryPtr ml, sqlite::Row& row );