Common Issues With Using DB in Phat
There are common errors that are made when using the database (TPhDatabase)
in Phat. This document attempts to outline those errors, explain why they are an
issue, and tell what the (current) best way to solve these issues is.
Why should you care? Interacting with the database is special because
you are interacting with a critical system. Most importantly, the database is
needed during data-taking. If too many sessions or cursors are opened the
database can reach a limit and deny access to other people trying to connect
(including the DAQ). There is, currently, no simple way to set a priority for
certain connections. This fact makes it critical that users properly open and
close connections (especially when running a large number of batch jobs - such
as in code used by data validation).
Issues:
- The main issue with using the Database is to properly mark when you start
using it and when you stop. This is done with TPhDatabase::Activate() and
TPhDatabase::Release(). Activate() tells the database that you wish to use
its connection authenticated with its current user. Release() tells the
database that you are done using it. Most commonly this is done using gPhDb:
void UseDatabase()
{
gPhDb->Activate();
gPhDb->Connection()->NewStatement(mysqlquery);
// run the query
gPhDb->Release();
}
The use of Activate() and Release() here is fine as long as there exists no
way for the function to exit before reaching the Release(). A utility to
care of the situation of early return is the subclass TPhDatabase::TConn.
TConn is a wrapper that calls Activate() in its constructor and Release() in
its destructor. The same code as above can be written below with TConn as:
void UseDatabase()
{
TPhDatabase::TConn activate(gPhDb);
gPhDb->Connection()->NewStatement(mysqlquery);
// run the query
}
The advantage here is that upon any exit of the function the destructor for
activate is called an the connection is released. It should be noted that
the use of TConn in macros has not always worked. It should work now.
However, Phat's tab completion doesn't appear to recognize it in the list of
available commands.
If you get an error from Phat that begins:
"Warning in TPhDatabase::Connection: Connection has not been Activated!
Activating.".
This is a signal that some code (that you have written or you are using in
Phat) has asked for the connection without activated the database and a
Release() will be necessary to close the connection. This implicit
activation may be removed eventually to increase the likelihood of users
releasing their connections when they are finished using the database.