Wt
4.11.1
|
A database session. More...
#include <Wt/Dbo/Session.h>
Public Member Functions | |
Session () | |
Creates a database session. | |
virtual | ~Session () |
Destructor. More... | |
void | setConnection (std::unique_ptr< SqlConnection > connection) |
Sets a dedicated connection. More... | |
void | setConnectionPool (SqlConnectionPool &pool) |
Sets a connection pool. More... | |
template<class C > | |
void | mapClass (const char *tableName) |
Maps a class to a database table. More... | |
template<class C > | |
const char * | tableName () const |
Returns the mapped table name for a class. More... | |
template<class C > | |
const std::string | tableNameQuoted () const |
Returns the mapped quoted table name for a class. More... | |
template<class C > | |
ptr< C > | add (ptr< C > &ptr) |
Persists a transient object. More... | |
template<class C > | |
ptr< C > | add (std::unique_ptr< C > obj) |
Persists a transient object. More... | |
template<typename T , typename ... Args> | |
ptr< T > | addNew (Args &&...args) |
Persists a transient object. More... | |
template<class C > | |
ptr< C > | load (const typename dbo_traits< C >::IdType &id, bool forceReread=false) |
Loads a persisted object. More... | |
template<class C > | |
ptr< C > | loadLazy (const typename dbo_traits< C >::IdType &id) |
Lazy loads a persisted object. More... | |
template<class C , typename BindStrategy = DynamicBinding> | |
Query< ptr< C >, BindStrategy > | find (const std::string &condition=std::string()) |
Finds database objects. More... | |
template<class Result , typename BindStrategy = DynamicBinding> | |
Query< Result, BindStrategy > | query (const std::string &sql) |
Creates a query. More... | |
Call | execute (const std::string &sql) |
Executs an Sql command. More... | |
void | createTables () |
Creates the database schema. More... | |
std::string | tableCreationSql () |
Returns database creation SQL. | |
void | dropTables () |
Drops the database schema. More... | |
void | flush () |
Flushes the session. More... | |
void | rereadAll (const char *tableName=nullptr) |
Rereads all objects. More... | |
void | discardUnflushed () |
Discards all unflushed changes. More... | |
FlushMode | flushMode () |
Returns the flushMode. More... | |
void | setFlushMode (FlushMode mode) |
Sets the flushMode. More... | |
A database session.
A database session manages meta data about the mapping of C++ classes to database tables, and keeps track of a working set of in-memory objects (objects which are referenced from your code or from within a transaction).
It also manages an active transaction, which you need to access database objects.
You can provide the session with a dedicated database connection using setConnection(), or with a connection pool (from which it will take a connection while processing a transaction) using setConnectionPool().
A session will typically be a long-lived object in your application.
|
virtual |
Destructor.
A session must survive all database objects that have been loaded through it, and will warning during this destructor if there are still database objects that are being referenced from a ptr.
Persists a transient object.
The transient object pointed to by ptr
is added to the session, and will be persisted when the session is flushed.
A transient object is usually a newly created object which want to add to the database.
The method returns ptr
.
ptr< C > Wt::Dbo::Session::add | ( | std::unique_ptr< C > | obj | ) |
Persists a transient object.
This is an overloaded method for convenience, and is implemented as:
The method returns a database pointer to the object.
ptr<T> Wt::Dbo::Session::addNew | ( | Args &&... | args | ) |
Persists a transient object.
This an overloaded method for convenience, and is implemented as:
void Wt::Dbo::Session::createTables | ( | ) |
Creates the database schema.
This will create the database schema of the mapped tables. Schema creation will fail if one or more tables already existed. The creation of the tables is executed in a transaction that is rolled back when an error occurs.
This method throws an Wt::Dbo::Exception if the table creation failed.
void Wt::Dbo::Session::discardUnflushed | ( | ) |
Discards all unflushed changes.
This method is useful when the flushMode() is set to Manual. It discards all Dbo-objects which were added to the session and rereads all existing Dbo-objects.
void Wt::Dbo::Session::dropTables | ( | ) |
Drops the database schema.
This will drop the database schema. Dropping the schema will fail if one or more tables did not exist.
Call Wt::Dbo::Session::execute | ( | const std::string & | sql | ) |
Executs an Sql command.
This executs an Sql command. It differs from query() in that no result is expected from the call.
Usage example:
Query< ptr< C >, BindStrategy > Wt::Dbo::Session::find | ( | const std::string & | condition = std::string() | ) |
Finds database objects.
This method creates a query for finding objects of type C
.
When passing an empty condition
parameter, it will return all objects of type C
. Otherwise, it will add the condition, by generating an SQL where clause.
The BindStrategy
specifies how you want to bind parameters to your query (if any).
When using DynamicBinding
(which is the default), you will defer the binding until the query is run. This has the advantage that you can compose the query definition using helper methods provided in the query object, you can keep the query around and run the query multiple times, perhaps with different parameter values or to scroll through the query results.
When using DirectBinding
, the query must be specified entirely using the condition
, and can be run only once. This method does have the benefit of binding parameters directly to the underlying prepared statement.
This method is convenient when you are querying only results from a single table. For more generic query support, see query().
Usage example:
In the condition
, parameters can be bound using '?' as a positional placeholder: each occurence of '?' (as a lexical token) is replaced by a bound parameter. This is actually done by most of the backends themselves using prepared statements and parameter binding. Parameter binding is possible for all types for which sql_value_traits is specialized.
void Wt::Dbo::Session::flush | ( | ) |
Flushes the session.
This flushes all modified objects to the database. This does not commit the transaction.
Normally, you need not to call this method as the session is flushed automatically before committing a transaction, or before running a query (to be sure to take into account pending modifications).
FlushMode Wt::Dbo::Session::flushMode | ( | ) |
Returns the flushMode.
ptr< C > Wt::Dbo::Session::load | ( | const typename dbo_traits< C >::IdType & | id, |
bool | forceReread = false |
||
) |
Loads a persisted object.
This method returns a database object with the given object id. If the object was already loaded in the session, the loaded object is returned, otherwise the object is loaded from the database.
If forceReread
is set to true
, then a fresh copy is loaded from the database. This is almost equivalent to calling reread() on the returned object, except that it will not result in two database reads in case the object was in fact not yet loaded in the session.
Throws an ObjectNotFoundException when the object was not found.
ptr< C > Wt::Dbo::Session::loadLazy | ( | const typename dbo_traits< C >::IdType & | id | ) |
Lazy loads a persisted object.
This method returns a database object with the given object id without directly accessing the database.
If the object data is already available in the session, then it will be available upon return. Otherwise, the object data will be retrieved from the database on first access. Note: This will result in an ObjectNotFoundException if the object id is not valid.
lazyLoad can be used to obtain a ptr<C> from a known id when a ptr<C> is required, but access to the C object is not anticipated. For instance, a ptr<C> may be required to add an object of class X that is in a belongsTo relationship with C.
void Wt::Dbo::Session::mapClass | ( | const char * | tableName | ) |
Maps a class to a database table.
The class C
is mapped to table with name tableName
. You need to map classes to tables.
You may provide a schema-qualified table name, if the underlying database supports this, eg. "myschema.users"
.
Query< Result, BindStrategy > Wt::Dbo::Session::query | ( | const std::string & | sql | ) |
Creates a query.
The sql statement should be a complete SQL statement, starting with a "select ". The items listed in the "select" must match the Result
type. An item that corresponds to a database object (ptr) is substituted with the selection of all the fields in the dbo.
For example, the following query (class User is mapped onto table 'user'):
is the more general version of:
Note that "u" in this query will be expanded to select the fields of the user table (u.id, u.version, u.name, ...). The same expansion happens when using an alias in Query::groupBy().
The additional flexibility offered by query() over find() is however that it may support other result types.
Thus, it may return plain values:
Or std::tuple for an arbitrary combination of result values:
A tuple may combine any kind of object that is supported as a result, including database objects (see also ptr_tuple):
The BindStrategy
specifies how you want to bind parameters to your query (if any).
When using DynamicBinding
(which is the default), you will defer the binding until the query is run. This has the advantage that you can compose the query using helper methods provided in the Query object, you can keep the query around and run the query multiple times, perhaps with different parameter values or to scroll through the query results.
When using DirectBinding
, the query must be specified entirely using the sql
, and can be run only once. This method does have the benefit of binding parameters directly to the underlying prepared statement.
This method uses query_result_traits to unmarshal the query result into the Result
type.
In the sql
query, parameters can be bound using '?' as the positional placeholder: each occurence of '?' (as a lexical token) is replaced by a bound parameter. This is actually done by most of the backends themselves using prepared statements and parameter binding. Parameter binding is possible for all types for which sql_value_traits is specialized.
void Wt::Dbo::Session::rereadAll | ( | const char * | tableName = nullptr | ) |
Rereads all objects.
This rereads all objects from the database, possibly discarding unflushed modifications. This is a catch-all solution for a StaleObjectException.
If a tableName
is given, then only objects of that table are reread.
void Wt::Dbo::Session::setConnection | ( | std::unique_ptr< SqlConnection > | connection | ) |
Sets a dedicated connection.
The connection will be used exclusively by this session.
void Wt::Dbo::Session::setConnectionPool | ( | SqlConnectionPool & | pool | ) |
Sets a connection pool.
The connection pool is typically shared with other sessions.
void Wt::Dbo::Session::setFlushMode | ( | FlushMode | mode | ) |
Sets the flushMode.
The default flushMode is Auto. LabelOption::Inside a transaction this means that changes are flushed when a query is affected by them. When flushMode is set to Manual, changes are only flushed when the user manually calls flush(), or resets the mode to Auto. Query's wil possibly return an inconsistent result, but collections will still keep track of changes. This also makes it possible to operate on Dbo-objects and collections outside of a transaction. When the moment comes to flush the changes, a transaction must of course be active.
Note: only operations on a collecion are tracked in Manual mode, reciproke operations are not yet taken into account.
const char * Wt::Dbo::Session::tableName |
Returns the mapped table name for a class.
const std::string Wt::Dbo::Session::tableNameQuoted |
Returns the mapped quoted table name for a class.
This will quote schemas, as necessary.