Performing a transaction

What's a Transaction?

A transaction demarcates a "unit of work" operating on the database, ie. a series of operations that must either complete successfully, or if it is aborted at any stage, must not affect the data in the database at all. Hence the process of completing a transaction is called the "commit" operation, and the process of aborting it and undoing any changes it may have made is called "rollback."

All access to the database in libpqxx™ must go through a transaction object, so familiarity with this class family's interface is essential.

Creating a transaction object

Creating a transaction object is not normally something you will have to do. The transactor class, discussed below, will take care of that and some other red tape besides. Still, there are cases where creating the object is unavoidable (when acting on multiple database connections simultaneously) or just plain easier to do. Please consider using a transactor whereever possible.

When creating a transaction, pass it the connection object it is to act on, and optionally an identifying name for your transaction. The name, which need not be unique but should begin with a letter and may contain only letters, digits and underscores, can be used by libpqxx™ to make some error messages more specific.

	    transaction<> Xaction(Conn, "DemoTransaction");
	  

Or, alternatively (once you get fed up with typing transaction<>):

	    work Xaction(Conn, "DemoTransaction");
	  

The lifetime of the transaction object demarcates the unit of work. Its construction marks the beginning of the transaction, and its destruction means that the transaction is ended--whether through commit or rollback.

The transaction class hierarchy is built on the principle of "explicit commit," ie. the commit operation must always be explicit in the code. If the transaction is destroyed before a commit was given, the transaction is implicitly aborted (rolled back). If your transaction makes no changes to the database, however, there is nothing to commit or roll back and the commit may safely be omitted.

Destroying the connection object while the transaction still exists is an error that may result in a program crash, although the library will try to log an error message. Transactions cannot be copied, nor assigned, nor constructed without a connection (default-constructed); attempts to do any of these will result in compile errors.