Wt: Wt::Dbo::Session Class Reference

Wt 3.3.0

- Main Page
- Related Pages
- Modules
- Namespaces
- Classes

- Class List
- Class Hierarchy
- Class Members

Public Member Functions
Wt::Dbo::Session Class Reference
Database Objects (Wt::Dbo)

A database session. More...

`#include <Wt/Dbo/Session>`

List of all members.

## Public Member Functions
| Session ()
| Creates a database session.
| ~Session ()
| Destructor.
void | setConnection (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 >
ptr< C > | add (ptr< C > &ptr)
| Persists a transient object.
template<class C >
ptr< C > | add (C *obj)
| 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 , 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=0)
| Rereads all objects.

## 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(). In either case, the session does not take ownership of the connection or connection pool.

A session will typically be a long-lived object in your application.

## Constructor & Destructor Documentation

Wt::Dbo::Session::~Session | ( |  | ) |

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

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`.

template<class C >

ptr< C > Wt::Dbo::Session::add | ( | C * | obj | ) |

Persists a transient object.

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

     return add(ptr<C>(obj));

The method returns a database pointer to the object.

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.

See also:
  mapClass(), 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()

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");

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");

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

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

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

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"`.

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 Boost.Tuple for an arbitrary combination of result values:

     session.query< boost::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< boost::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:
  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.

void Wt::Dbo::Session::rereadAll | ( | const char * | tableName = `0` | ) |

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

void Wt::Dbo::Session::setConnection | ( | SqlConnection & | connection | ) |

Sets a dedicated connection.

The connection will be used exclusively by this session.

See also:
  setConnectionPool()

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

Sets a connection pool.

The connection pool is typically shared with other sessions.

See also:
  setConnection()

template<class C >

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

Returns the mapped table name for a class.

See also:
  mapClass()

All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator