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. The step 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 it's essential to learn about the transaction classes.
When creating a transaction, pass your connection
object to the constructor, and optionally an identifying name for
your transaction. The name need not be unique. It's just there to
make error messages a bit easier to debug.
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 there was a commit, that implicitly aborts (or "rolls back") the transaction.
Destroying the connection object while the transaction still exists is an error that may result in a program crash. Transactions cannot be copied, nor assigned, nor constructed without a connection (default-constructed). Attempts to do any of these will result in compile errors.