Wt: Wt::Dbo::Session Class Reference

Wt 4.10.4

Loading...
Searching...
No Matches
Public Member Functions | List of all members
Wt::Dbo::Session Class Reference
Database Objects (Wt::Dbo)

A database session. More...

`#include <Wt/Dbo/Session.h>`

## Public Member Functions
| Session ()
| Creates a database session.
virtual | ~Session ()
| Destructor.
void | setConnection (std::unique_ptr< SqlConnection > connection)
| Sets a dedicated connection.
void | setConnectionPool (SqlConnectionPool &pool)
| Sets a connection pool.
template<class C >
void | mapClass (const char *tableName)
| Maps a class to a database table.
template<class C >
const char * | tableName () const
| Returns the mapped table name for a class.
template<class C >
const std::string | tableNameQuoted () const
| Returns the mapped quoted table name for a class.
template<class C >
ptr< C > | add (ptr< C > &ptr)
| Persists a transient object.
template<class C >
ptr< C > | add (std::unique_ptr< C > obj)
| Persists a transient object.
template<typename T , typename ... Args>
ptr< T > | addNew (Args &&...args)
| Persists a transient object.
template<class C >
ptr< C > | load (const typename dbo_traits< C >::IdType &id, bool forceReread=false)
| Loads a persisted object.
template<class C >
ptr< C > | loadLazy (const typename dbo_traits< C >::IdType &id)
| Lazy loads a persisted object.
template<class C , typename BindStrategy = DynamicBinding>
Query< ptr< C >, BindStrategy > | find (const std::string &condition=std::string())
| Finds database objects.
template<class Result , typename BindStrategy = DynamicBinding>
Query< Result, BindStrategy > | query (const std::string &sql)
| Creates a query.
Call | execute (const std::string &sql)
| Executs an Sql command.
void | createTables ()
| Creates the database schema.
std::string | tableCreationSql ()
| Returns database creation SQL.
void | dropTables ()
| Drops the database schema.
void | flush ()
| Flushes the session.
void | rereadAll (const char *tableName=nullptr)
| Rereads all objects.
void | discardUnflushed ()
| Discards all unflushed changes.
FlushMode | flushMode ()
| Returns the flushMode.
void | setFlushMode (FlushMode mode)
| Sets the flushMode.

## Detailed Description

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.

## Constructor & Destructor Documentation

## ◆ ~Session()

virtual Wt::Dbo::Session::~Session | ( |  | ) |
| 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.

## Member Function Documentation

## ◆ add() [1/2]

template<class C >

ptr< C > Wt::Dbo::Session::add | ( | ptr< C > & | 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`.

## ◆ add() [2/2]

template<class C >

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:

return add(ptr<C>(std::move(obj)));
Wt::Dbo::Session::add
ptr< C > add(ptr< C > &ptr)
Persists a transient object.
Definition Session_impl.h:207
Wt::Dbo::ptr
A smart pointer for a database object.
Definition WGlobal.h:283

The method returns a database pointer to the object.

## ◆ addNew()

template<typename T , typename ... Args>

ptr< T > Wt::Dbo::Session::addNew | ( | Args &&... | args | ) |

Persists a transient object.

This an overloaded method for convenience, and is implemented as:

return add(ptr<C>(std::unique_ptr<T>(new T(...))))
Wt::Key::T
@ T
'T' key

See also
  Wt::Dbo::make_ptr()

## ◆ createTables()

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.

See also
  mapClass(), dropTables()

## ◆ discardUnflushed()

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.

See also
  setFlushMode()

## ◆ dropTables()

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.

See also
  createTables()

## ◆ execute()

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:

session.execute("update user set name = ? where name = ?").bind("Bart").bind("Sarah");

## ◆ find()

template<class C , typename BindStrategy >

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:

// Bart is missing, let's find him.
Wt::Dbo::ptr<User> bart = session.find<User>().where("name = ?").bind("Bart");
// Find all users, order by name
typedef Wt::Dbo::collection< Wt::Dbo::ptr<User> > Users;
Users users = session.find<User>().orderBy("name");
Wt::Dbo::collection
An STL container for iterating query results.
Definition WGlobal.h:280
Wt::Dbo::collection::find
Query< C, DynamicBinding > find() const
Returns the query that backs the collection.
Definition collection_impl.h:544
Wt::EventType::User
@ User
A user-initiated event.

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.

See also
  query()

## ◆ flush()

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()

FlushMode Wt::Dbo::Session::flushMode | ( |  | ) |

Returns the flushMode.

See also
  setFlushMode()

## ◆ load()

template<class C >

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.

See also
  ptr::id(), loadLazy()

## ◆ loadLazy()

template<class C >

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.

See also
  ptr::id(), load()

## ◆ mapClass()

template<class 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()

template<class Result , typename BindStrategy >

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'):

session.query< ptr<User> >("select u from user u").where("u.name = ?").bind("Bart");

is the more general version of:

session.find<User>().where("name = ?").bind("Bart");

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:

session.query<int>("select count(1) from ...");

Or std::tuple for an arbitrary combination of result values:

session.query< std::tuple<int, int> >("select A.id, B.id from table_a A, table_b B").where("...");

A tuple may combine any kind of object that is supported as a result, including database objects (see also ptr_tuple):

session.query< std::tuple<ptr<A>, ptr<B> > >("select A, B from table_a A, table_b B").where("...");

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.

Note
  PostgreSQL uses a literal question mark ('?') as an operator. To distinguish between a positional placeholder and a literal '?', use a double question mark ('??') if you mean a literal '?'.
  The query must be a ASCII-7 string: UTF-8 is not supported by the underlying query parser. To add a non-English string to the query use parameter binding instead (which prevents against SQL injection attacks at the same time) instead of string concatenation.

## ◆ rereadAll()

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.

See also
  ptr::reread()

## ◆ setConnection()

void Wt::Dbo::Session::setConnection | ( | std::unique_ptr< SqlConnection > | connection | ) |

Sets a dedicated connection.

The connection will be used exclusively by this session.

See also
  setConnectionPool()

## ◆ setConnectionPool()

void Wt::Dbo::Session::setConnectionPool | ( | SqlConnectionPool & | pool | ) |

Sets a connection pool.

The connection pool is typically shared with other sessions.

See also
  setConnection()

## ◆ setFlushMode()

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.

See also
  flushMode(), discardUnflushed()

## ◆ tableName()

template<class C >

const char * Wt::Dbo::Session::tableName | ( |  | ) | const

Returns the mapped table name for a class.

See also
  mapClass(), tableNameQuoted()

## ◆ tableNameQuoted()

template<class C >

const std::string Wt::Dbo::Session::tableNameQuoted | ( |  | ) | const

Returns the mapped quoted table name for a class.

This will quote schemas, as necessary.

See also
  mapClass(), tableName()