head	1.12;
access;
symbols
	REL7_3_STABLE:1.12.0.2
	start:1.1.1.1
	jtv:1.1.1;
locks; strict;
comment	@# @;


1.12
date	2002.06.12.13.28.06;	author jtv;	state Exp;
branches;
next	1.11;

1.11
date	2002.06.08.19.51.36;	author jtv;	state Exp;
branches;
next	1.10;

1.10
date	2002.05.27.20.30.34;	author jtv;	state Exp;
branches;
next	1.9;

1.9
date	2002.05.20.02.52.33;	author jtv;	state Exp;
branches;
next	1.8;

1.8
date	2002.03.30.23.02.16;	author jtv;	state Exp;
branches;
next	1.7;

1.7
date	2002.03.26.20.41.30;	author jtv;	state Exp;
branches;
next	1.6;

1.6
date	2002.03.25.23.32.35;	author jtv;	state Exp;
branches;
next	1.5;

1.5
date	2002.03.20.01.00.49;	author jtv;	state Exp;
branches;
next	1.4;

1.4
date	2002.02.15.00.38.25;	author jtv;	state Exp;
branches;
next	1.3;

1.3
date	2002.02.03.19.16.28;	author jtv;	state Exp;
branches;
next	1.2;

1.2
date	2002.02.03.04.59.41;	author jtv;	state Exp;
branches;
next	1.1;

1.1
date	2002.01.26.20.00.39;	author jtv;	state Exp;
branches
	1.1.1.1;
next	;

1.1.1.1
date	2002.01.26.20.00.39;	author jtv;	state Exp;
branches;
next	;


desc
@@


1.12
log
@More documentation on Transactor
@
text
@<!doctype chapter PUBLIC "-//OASIS//DTD DocBook V4.1//EN">
 <chapter id="libpqxx">
  <title>libpqxx - C++ Binding Library</title>

  <sect1>
   <title>About <filename>libpqxx</filename></title>
   <para>
    <filename>libpqxx</filename> is a C++ <acronym>API</acronym> to 
    <productname>PostgreSQL</productname>.  It replaces the earlier
    <filename>libpq++</filename> with a more Standard Template Library
    (<acronym>STL</acronym>)-conformant interface and makes more extensive use 
    of C++ language features such as exceptions, templates, and strings.
   </para>

   <para>
    Since <filename>libpqxx</filename> builds on top of the C frontend
    <filename>libpq</filename>, you will need a working 
    <filename>libpq</filename> library on your system prior to getting started
    with <filename>libpqxx</filename>.  This is similar to the situation with
    the older <filename>libpq++</filename> interface.
   </para>

   <sect2>
    <title>Why another C++ SQL library?</title>
    <para>
     Several open-source C++ wrapper libraries are available for various
     databases, as well as some database-independent ones; there's
     <filename>libpql++</filename>, <filename>libpq++</filename>,
     <filename>libsqlxx</filename> and so on.
    </para>

    <para>
     So was <filename>libpqxx</filename> really necessary?
    </para>

    <para>
     I think it is.  The C++ Standard, and its standard library in particular,
     have stabilized during the latter half of the 1990s; compilers and 
     standard library implementations are still following suit at the time of 
     writing.  As a result, most older third-party libraries suffer from 
     symptoms such as: 
     <itemizedlist>
      <listitem>
       <para>
        Not using exceptions.  Many libraries return a status code and expect
	the caller to check for errors "if he's interested."  <emphasis>Of 
	course</emphasis> he's interested.  But checking each and every call is
	tedious and error prone.
       </para>
      </listitem>

      <listitem>
       <para>
        Ad-hoc exception classes.  Programs using C++ libraries need to deal 
	with various incompatible exception class hierarchies, and error 
	handling becomes a total nightmare with multiple essentially identical
	<literal>catch</literal> clauses for every <literal>try</literal> block.
       </para>
      </listitem>

      <listitem>
       <para>
        Ad-hoc string classes.  As one member of the C++ standards committee
	put it, if the C++ wasn't going to have a standard string class, "there 
	will be blood in the streets."  Luckily, the committee saw the wisdom 
	in this, and civilization was spared.
       </para>
      </listitem>

      <listitem>
       <para>
        "A Better C."  Using only the oldest features of C++ as extensions to
	the C language really only complicates things, but there was a time
	when this was the only way to write portable C++.
       </para>
      </listitem>

      <listitem>
       <para>
        Ad-hoc containers and algorithms.  Inventing your own container APIs,
	interesting as it may be, in most cases is wasted development effort.
	Besides that, there's also the redundant effort of having to learn how 
	they work.
       </para>
      </listitem>
     </itemizedlist>
    </para>
     
    <para>
     For these reasons, third-party libraries have tended to grow into
     intrusive frameworks.  Third-party code, and class libraries in 
     particular, need to be rewritten to replace such ad-hockery with the rich 
     and standardized functionality now provided by C++.  This is what 
     <filename>libpqxx</filename> intends to do for 
     <productname>PostgreSQL</productname>.  The library was designed to be a 
     forward-looking one, which means that ports to vendor X's compiler Y may 
     have to wait until X improves its support of the Standard.
    </para>

    <para>
     But there were other reasons to design a new SQL frontend from scratch.  
     C++ is a complex language, and the only things stopping a library writer
     from shooting himself
     <footnote>Yes, <emphasis>him</>self.  A "writer" is grammatically 
      <para>
       masculine, unless actual gender is known and definite.
      </para>
     </footnote> 
     in the foot are years of experience and an extensive idiom of good
     practices.  To name a few typical symptoms of foot-shooting:
    </para>

    <itemizedlist>
     <listitem>
      <para>
       Poor language integration.  Users need to learn myriads of function
       names when standard C++ operators can be overloaded instead to make code
       fit in more naturally with the core language.
      </para>
     </listitem>

     <listitem>
      <para>
       Overdoing overloading.  It's also easy to go overboard with operator
       or function overloading, and many classes do.  Some programmers use
       identical function names to mean very different things, or define
       operators whose semantics are not clearly derived from their 
       conventional meanings.
      </para>
     </listitem>

     <listitem>
      <para>
       Resource management.  In the complex world of C++, what the user really
       needs from a library is a little help in ensuring that objects are
       deleted at the proper time, pointers don't go off into never-never land,
       and so on.  Perhaps the most compelling usage of C++ is the "resource
       acquisition is initialization" paradigm, but too few libraries apply it 
       as yet.
      </para>
     </listitem>

     <listitem>
      <para>
       Convoluted family trees.  Class derivation is a beautiful thing, but it
       can be overused.  Some libraries construe far-fetched relations between
       classes, or needlessly expose "convenience" relations using public
       inheritance.
      </para>
     </listitem>

     <listitem>
      <para>
       Overweight classes.  Some classes lump together different pieces of
       functionality with different lifetimes.  For instance, some C++ SQL
       libraries integrate transaction bracketing into a Connection class.
       Yet it is not unreasonable for an application to perform multiple
       consecutive transactions using the same connection.
      </para>
     </listitem>

    </itemizedlist>

    <para>
     Again, <filename>libpqxx</filename> is an attempt to do better.  Hopefully
     this has resulted in a library that is easier to use than most 
     alternatives while giving you more flexibility, that helps you avoid 
     common pitfalls and reduces the need for debugging.
    </para>
   </sect2>
  </sect1>

  <sect1>
   <title>Class overview</title>

   <para>
    To work with <filename>libpqxx</filename>, you need to be aware of at least
    the following classes.  These are all introduced in a dedicated namespace,
    <literal>pqxx</literal>:
   </para>

   <itemizedlist>
    <listitem>
     <para>
      <literal>Connection</literal> represents a connection from your program
      to a <productname>PostgreSQL</productname> back-end server.  Naturally
      your program may open multiple connections, simultaneous or not, to any
      number of databases.
     </para>
    </listitem>
 
    <listitem>
     <para>
      <literal>Transaction</literal> represents a transaction being executed 
      in the context of a <literal>Connection</literal>, and is a unit of work 
      that must be completed as a whole by the database backend.  If execution 
      fails, everything done within that <literal>Transaction</literal> is 
      undone by the backend as if it had never happened<footnote>
       Actually <filename>libpqxx</filename> provides three classes doing this
       at various levels of reliability, called 
       <literal>NonTransaction</literal>, <literal>Transaction</literal>, and
       <literal>RobustTransaction</literal> for little, standard, and best
        reliability respectively.  
      </footnote>.
     </para>
     <para>
      I recommend that you do not set up your own <literal>Transaction</>s
      however, but have them managed for you by a 
      <emphasis><literal>Transactor</literal></emphasis> instead (see below).
     </para>
    </listitem>

    <listitem>
     <para>
      <literal>Result</literal> is a container holding the resulting data
      coming out of a query or command executed in a 
      <literal>Transaction</literal>.  It behaves just like a standard C++
      container as found in the STL, although its contents are not modifiable.
     </para>
    </listitem>

   </itemizedlist>

   <para>
    I would also like to use this opportunity to plug the invaluable
    <function>Quote</function> function, which you should use whenever you want
    to include a variable as a string in your SQL (eg. insert it into a CHAR
    field in a table).  See below.
   </para>

   <para>
    There are other classes that may be of interest to you; these are either 
    not essential to writing a simple program using 
    <filename>libpqxx</filename>, or are used in such a way that knowledge of 
    them is not immediately necessary.  You will probably want to look them up 
    at some point when it becomes necessary to understand complex compiler 
    warnings.  Unfortunately C++ compilers are not yet very good at unravelling 
    template-related errors and making them readable, so you may find some long
    and strange names when they happen.
   </para>
   <para>
     Some of the classes you may become interested in fairly quickly are:
   </para>
   <itemizedlist>
    <listitem>
     <para>
      <literal>broken_connection</literal> is an exception class that may be 
      thrown if <filename>libpqxx</filename> loses its connection to the 
      back-end.  It is derived from the standard C++ exception
      <literal>std::runtime_error</literal>, and can generally be treated as
      such.  It is not currently guaranteed that a broken connection will
      result in a <literal>broken_connection</literal> being thrown; a normal
      <literal>std::runtime_error</literal> may be thrown instead.
     </para>
    </listitem>

    <listitem>
     <para>
      <literal>Cursor</literal> is a way of iterating over a query result 
      using an SQL cursor.  This can be useful for selectively retrieving 
      parts of a query, or for retrieving and processing results in chunks so 
      your program can do useful work on one chunk while the next is still 
      coming in over a network connection.  Or you may want to use this to 
      give progress reports to the user between chunk transfers.
     </para>
    </listitem>

    <listitem>
     <para>
      <literal>in_doubt_error</literal> is an exception class to indicate a
      rare and difficult error condition.  Explaining this is a bit painful,
      since it invalidates some of what was said above (and is commonly said in
      the database world).
     </para>
     <para>
      In theory, a "transaction" is an integral, atomic unit of work that 
      either fails or succeeds.  This is a beautiful idea, but in practice
      there is nothing that cannot be broken.  In practice there is a tiny
      risk that, like Schroedinger's Cat, the transaction ends up in a third,
      indeterminate state.  This happens when the connection to the backend
      is lost just when you were waiting for confirmation after completing
      your transaction.  Your transaction may have succeeded (in fact it
      probably has), but if the connection is lost during just this small time
      window, it has no way to confirm this to your application.
     </para>
      When this happens, libpqxx throws an <literal>in_doubt_error</literal> on
      the client side, which you may want to <literal>catch</literal> as a 
      special case.  If you do, make sure all alarm bells go off!
     </para>
     <para>
      See also the description for <literal>RobustTransaction</literal>, which
      sacrifices some performance to deal with this risk.
     </para>
    </listitem>

    <listitem>
     <para>
      <literal>NonTransaction</literal> is just like a regular 
      <literal>Transaction</literal> as far your code is concerned.  The big
      difference is that where the latter opens a back-end transaction to keep
      your view and modifications of the database atomic, the former does
      <emphasis>nothing</emphasis> to maintain integrity.  It just passes your
      queries directly to the database, with no enclosing transaction. 
     </para>
     <para>
      This gives you the best performance, but may have unforseen implications
      if you expect certain levels of consistency in the database--especially
      if other programs (perhaps even other instances of your own) may be
      modifying the database at the same time.  You'll probably only want to
      use this in the following cases:
     </para>
      <itemizedlist>
       <listitem>
        <para>
	 If you only want to read from the database, not modify it, and you
	 know that the data is not going to be updated while your program is
	 running.
        </para>
       </listitem>

       <listitem>
        <para>
	 If you are interested in always getting the very latest information
	 out of your database, even if that means that you may not get a
	 temporally consistent view of the database.
        </para>
       </listitem>

       <listitem>
        <para>
	 If full integrity is less important than performance, as might be the
	 case with e.g. updating or displaying a webcounter.  Losing one or two
	 hits may be less of a problem to you than keeping visitors waiting.
        </para>
       </listitem>

      </itemizedlist>
    </listitem>

    <listitem>
     <para>
      <literal>RobustTransaction</literal> is essentially the same as a
      <literal>Transaction</literal>, ie. an atomic unit of work, except that
      it works harder to prevent <literal>in_doubt_error</>s from happening.
      This comes at the cost of some performance, which is one reason why this 
      behaviour isn't the default.  It also creates some extra tables in your 
      database to keep track of what's happening.
     </para>
     <para>
      Use this class instead of plain old <literal>Transaction</literal> if you
      get <literal>in_doubt_error</>s in your application--but only
      <emphasis>after</> thoroughly inspecting your code for bugs that might be
      causing the problem, or you'll only be hiding glitches that should be
      fixed instead.
     </para>
    </listitem>

    <listitem>
     <para>
      <literal>TableStream</literal> provides simple, relatively direct access
      to a table for either reading (<literal>TableReader</literal>) or
      writing (<literal>TableWriter</literal>) using 
      <productname>PostgreSQL</productname>'s <literal>COPY</literal> command.
     </para>
    </listitem>
 
    <listitem>
     <para>
      <literal>TransactionItf</literal> defines the common public interface for
      the <literal>Transaction</>-like classes: <literal>NonTransaction</>,
      <literal>RobustTransaction</>, and <literal>Transaction</> itself.  To
      look up methods available in these classes, see the definition (or
      documentation) for <literal>TransactionItf</literal> instead.
     </para>
    </listitem>

    <listitem>
     <para>
      <literal>Transactor</literal> is a framework that makes it easier for 
      you to write correct, robust transaction code to be executed in a
      <literal>Transaction</literal> (or any of its sibling classes).  You 
      should generally try to write your code as a class derived from 
      <literal>Transactor</literal>, but this is not required.
     </para>
     <para>
      A <literal>Transactor</>-derived class may select its own "quality of
      service" in transactional integrity by overriding the nested
      <literal>argument_type</literal> typedef defined within its base class,
      <literal>Transactor</>.
     </para>
    </listitem>

    <listitem>
     <para>
      <literal>Trigger</literal> is an instance of the Observer design 
      pattern.  Any code connected to a backend may flag an event using the 
      <productname>PostgreSQL</productname> <literal>NOTIFY</literal> command. 
      Frontends connected to that same backend database may be listening for 
      an event of that name to occur.  A frontend using 
      <filename>libpqxx</filename> does this by registering an observer object 
      derived from <literal>Trigger</literal>, which will be invoked by 
      <filename>libpqxx</filename> to handle the event when it occurs.
     </para>
     <para>
      What every programmer using triggers in PostgreSQL should know, by the
      way, is that trigger notifications are not delivered to your program 
      while it is inside a back-end transaction.  This makes sense from a
      correctness point of view (otherwise your processing of the event might
      get rolled back just because the transaction you're in happens to fail),
      but may be a little confusing to the unaware programmer.
     </para>
    </listitem>

    <listitem>
     <para>
      <literal>Unique</literal> is really only intended for use by the library
      itself, although you may find it useful for your own code.  It allows a
      "host" class to enforce a one-to-one association with a "guest" class,
      such that at most 1 "guest" object may be associated with any one "host"
      object at any given time.  This is used to ensure that no more than one
      <literal>Transaction</literal> at a time is active on a single 
      <literal>Connection</literal>, and that no more than one 
      <literal>Cursor</literal> is active on a single <literal>Transaction</>.
     </para>
    </listitem>

    <listitem>
     <para>
      <literal>Result::Tuple</literal> is a nested class defined within
      <literal>Result</literal>.  It refers to a tuple of data within a
      <literal>Result</literal> object.
     </para>
    </listitem>

    <listitem>
     <para>
      <literal>Result::Field</literal>, also nested within 
      <literal>Result</literal>, refers to one field within a 
      <literal>Tuple</literal>.  A <literal>Field</literal> contains one 
      retrieved value such as a number or a string.
     </para>
    </listitem>

    <listitem>
     <para>
      <literal>Result::const_iterator</literal> allows you to enumerate the
      <literal>Tuple</>s in a <literal>Result</literal> in a similar way to
      the iterators defined by any standard C++ container.
     </para>
    </listitem>
   </itemizedlist>

  <para>
   Finally, there are also some functions that you may want to know about, that
   live alone in the <literal>pqxx</literal> namespace without being part of
   any class:
  </para>

  <itemizedlist>
   <listitem>
    <para>
     <function>Quote</function> is the canonical way to use strings in your SQL.
     This function not only adds SQL-style quotes around your string; it also 
     escapes quotes, backslashes, and other characters that would otherwise 
     cause syntax errors in your queries when included directly.
    </para>
    <para>
     <emphasis>Use this function</emphasis> whenever you want to have a variable
     string in your SQL queries.  If you don't, you'll be left with annoying
     bugs or possibly even security holes in your program.  Use this function,
     use this function, use this function.  Please.  Make me proud.
    </para>
   <listitem>

   <listitem>
    <para>
     <function>ToString</function> knows how to render many types of values as
     strings.  This is used internally by <literal>libpqxx</literal>, and it
     may be replaced in the future<footnote>
      Apparently the BOOST library's <literal>numeric_cast</literal> provides
      similar functionality.  This may be used to replace the custom code at
      some point.
     </footnote>.
    </para>
   <listitem>

   <listitem>
    <para>
     <function>FromString</function> is the inverse of 
     <function>ToString</function>.  Like <function>ToString</function> it may
     someday be replaced.  For now it is used by eg. 
     <function>Result::Field::to()</function> to convert the incoming field 
     data (which is in text format) to the desired C++ type.
    </para>
   <listitem>

   <lististem>
    <para>
     <function>FmtString</function> is used by some specializations of the
     <function>ToString</function> and <function>FromString</function> functions
     to statically determine the appropriate C stdio-style format strings for
     the various builtin types like <literal>int</literal>, 
     <literal>char</literal>, and so on.
    </para>
   </listitem>
  </itemizedlist>
  </sect1>


  <sect1>
   <title>Tutorial</title>

   <sect2>
    <title>Before we begin</title>

    <sect3>
     <title>This document</title>

     <para>
      This frontend library is built on top of the <filename>libpq</filename>
      frontend library, which defines <productname>PostgreSQL</productname>'s C 
      <acronym>API</acronym>.  Therefore this manual will sometimes refer to 
      the <filename>libpq</filename> documentation rather than repeat what is 
      said there.  This was not done to annoy you, but to ensure that the 
      <filename>libpqxx</filename> documentation remains up-to-date with any 
      changes in the C frontend.  Please bear with us.
     </para>

     <para>
      Furthermore, if you're ever in doubt about how to use the basic features 
      of <filename>libpqxx</filename>, take a look at the example programs 
      provided; they're called <filename>test1</filename>, 
      <filename>test2</filename> etc.  Those should help give you an idea of 
      how simple the library can be in practice.  Don't let that keep you from 
      submitting a request for improved documentation though; your questions 
      define what this tutorial needs to say!
     </para>

    </sect3>

    <sect3>
     <title>C++ conventions</title>

     <para>
      All definitions made by <filename>libpqxx</filename> reside in a 
      namespace <literal>pqxx</literal>.  If you're not familiar with C++
      namespaces, you have two options:
     </para>

     <itemizedlist>
      <listitem> 
       <para> Always import the whole of the <literal>pqxx</literal> namespace 
	in your programs.
       </para>
       <para> This tells the compiler to always look in the 
	<literal>pqxx</literal> namespace when trying to resolve a name that 
	doesn't occur in the global (ie. the "normal") namespace).  To do 
	this, include the directive 
	<programlisting>
using namespace pqxx;
        </programlisting>
        near the top of each source file that uses <filename>libpqxx</filename>.
       </para>
      </listitem>

      <listitem>
       <para> Explicitly qualify each <filename>libpqxx</filename> name with
	the <literal>pqxx</literal> namespace.
       </para>

       <para>
	This will tell the compiler exactly which names are supposed to be in
	the <literal>pqxx</literal> namespace, avoiding any confusion over
	multiple classes or functions used in your program possibly having the 
	same name.  As long as they're in different namespaces, the compiler
	will be able to tell them apart without trouble.  To do this, write
	<literal>pqxx::Connection</literal> instead of 
	<literal>Connection</literal>, 
	<literal>pqxx::Result::const_iterator</literal> instead of
	<literal>Result::const_iterator</literal>, and so on.
       </para>
      </listitem>
     </itemizedlist>

    </sect3>

    <sect3>
     <title></title>
     <para>
      Now let's get programming...
     </para>
    </sect3>

   </sect2>

   <sect2>
    <title>Setting up a connection</title>

     <para>
      The very first thing to do before we can begin working with a database, 
      is to actually connect to one.  We do this by creating a 
      <literal>Connection</literal> object that will serve as our "handle" on
      the connection:

     <programlisting>
Connection Conn("dbname=test");
     </programlisting>
    </para>

    <para>
     The <literal>Connection</literal> constructor is passed one argument, the
     "connect string".  This string may be used to specify which host
     on the network runs the database backend we wish to connect to, which
     database we're interested in, which user name we'll be using to log in,
     etc.  Refer to <xref linkend="libpq-connect">the libpq 
     <function>connect</function> call</xref> for a complete definition 
     of what may go into the connect string.  In this case we're connecting to 
     a database <literal>test</literal> residing on the local machine.
    </para>

    <para>
     If no connection could be established, the <literal>Connection</literal>
     constructor may throw an exception immediately; or it may decide to retry
     the connection later in case the problem is only temporary.  In the latter
     case, an exception may occur at some later point if the problem turns out
     not to be so temporary after all.
    </para>

    <para>
     The <literal>Connection</literal> can now act as a "service counter" for 
     our database; your client will use it to perform one or more transactions
     related to the database.
    </para>

    <para>
     Connections cannot be copied or assigned.  Any attempt to do so will be 
     met with a compiler error.
    </para>

    <sect3>
     <title>Important note</title>
     <para>
      As a matter of design, <filename>libpqxx</filename> will not allow you
      to perform queries on the <literal>Connection</literal> directly.  You
      will need to have a <literal>Transaction</literal> object instead.
     </para>

     <para>
      See the section on transactions below.
     </para>
    </sect3>

   </sect2>

   <sect2>
    <title>Performing a transaction</title>

    <sect3>
     <title>What's a Transaction?</title>
     <para>
      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."
     </para>
     <para>
      All access to the database in <filename>libpqxx</filename> must go 
      through a transaction object, so familiarity with this class (or its 
      siblings) is essential.
     </para>
    </sect3>

    <sect3>
     <title>Creating a Transaction object</title>
     <para>
      Creating a Transaction object is not normally something you will have to
      do.  The <literal>Transactor</literal> 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 <literal>Transactor</literal> whereever possible.
     </para>

     <para>
      When creating a <literal>Transaction</literal>, pass it the 
      <literal>Connection</literal> 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 <filename>libpqxx</filename> to 
      make some error messages more specific.

      <programlisting>
Transaction Xaction(Conn, "DemoTransaction");
      </programlisting>
     </para>

     <para>
      The lifetime of the <literal>Transaction</literal> 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.
     </para>

     <para>
      The <literal>Transaction</literal> class 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.
     </para>

     <para>
      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.
     </para>
    </sect3>
   </sect2>

   <sect2>
    <title>Ending a transaction</title>
    <para>
     A transaction ends either successfully through an explicit commit command,
     or unsuccessfully in any of a number of ways.  The following are the ways
     to end a transaction:
    </para>
    <itemizedlist>
     <listitem>
      <para>
       The transaction may be committed through its <literal>Commit</literal>
       member function:
      </para>
      <programlisting>
Xaction.Commit();
      </programlisting>
      <para>
       The commit operation is sent to the backend at the point where the
       <literal>Commit()</literal> call occurs.  Any exceptions generated by
       the database transaction will be thrown from here at the latest.  The
       only exceptions that may be generated by <literal>Xaction</literal>
       beyond this point are related to incorrect handling of the transaction
       object, eg. if an attempt is made to abort <literal>Xaction</literal>
       after it has been committed, or runtime errors such as memory running 
       out.
      </para>
      <para>
       As a consequence, any streams nested within the transaction (to be
       discussed later) must have been closed before the 
       <literal>Commit()</literal>.  To do otherwise could possibly allow a
       transaction to be committed before all related actions had completed.
       The library will throw an exception if this happens.
      </para>
     </listitem>

     <listitem>
      <para>
       A Transaction is aborted if it is destroyed without having been
       explicitly committed:
      </para>
      <itemizedlist>
       <listitem>
        <programlisting>
{
  Transaction Xaction(Conn, "DemoTransaction");

  // (Queries)

} // Xaction destroyed here
	</programlisting>
       </listitem>

       <listitem>
        <programlisting>
Transaction *XactionP = new Transaction(Conn, "DemoTransaction");

// (Queries)

delete XactionP; // Xaction destroyed here
	</programlisting>
       </listitem>

       <listitem>
        <programlisting>
try
{
  Transaction Xaction(Conn, "DemoTransaction");

  // (Queries)

  Xaction.Commit();
  // If we get here, Xaction is committed
}
catch (...)
{
  // If we get here, Xaction has been rolled back
}
	</programlisting>
       </listitem>

      </itemizedlist>
      <para>
       No matter where exactly the decision to abort is made, the actual abort
       operation is sent to the backend when the transaction's destructor is
       called.  If the abort fails, eg. because the network connection has
       been lost, no error is reported<footnote>
        <para>
         Throwing an exception from a destructor to report the error would have
	 serious effects on program correctness.  <emphasis>Never throw 
	 exceptions from a destructor.</emphasis>
	</para>
       </footnote> and the transaction will die of natural causes (either it
       has been closed by the backend already, or it soon will be if the 
       connection is lost).
      </para>
     </listitem>

     <listitem>
      <para>
       If a database error occurs during the transaction, such as an SQL syntax 
       error or lost connection to the backend, the Transaction is aborted.
      </para>
      <programlisting>
Transaction Xaction(Conn, "DemoTransaction");
try
{
  // (Queries)
  Xaction.Exec("SELECT !?^H^H^H^H");	// Fails: SQL syntax error
}
catch (...)
{
}
Xaction.Commit(); // ERROR: Xaction has already aborted!
      </programlisting>
      <para>
       For this reason, it is recommended to always include the "commit"
       operation inside the <literal>try</literal> block (if any) surrounding
       the transaction code, <emphasis>not</> after the 
       <literal>catch</literal> block.
      </para>
      <para>
       Think of it as a natural extension of structural programming: the
       transaction is "nested" within the connection, and the transaction code
       can be "nested" in a <literal>try</literal>/<literal>catch</literal>
       block.
      </para>
     </listitem>

    </itemizedlist>
    <para>
     No more queries may be issued to the Transaction regardless of how it
     ended; an exception will be thrown if the application attempts to continue
     the transaction after that time.
     Ending a transaction more than once is an error, except that aborting it
     multiple times is tolerated to facilitate error handling.
    </para>
   </sect2>

   <sect2>
    <title>Executing queries</title>
    <para>
     So let's execute an actual query.  There is no "query class" in
     <productname>libpqxx</productname>; we're trying to keep your life simple.
    </para>
    <para>
     A query is executed within a <literal>Transaction</literal> by passing
     the query string to its <function>Exec</function> method.  If the
     query fails to execute properly, this method will throw the appropriate
     exception.
    </para>
     
    <para>
     The query itself is a standard C string, ie. a 
     <literal>const char *</literal> but you'll frequently want to use a C++ 
     <literal>string</literal> to make it easy to include variables:
    </para>
    <programlisting>
void DeleteEntry(Transaction &amp;T, string Table, long ID)
{
  T.Exec(("DELETE FROM " + Table + " WHERE ID=" + ID).c_str());
}
    </programlisting>
    <para>
     It seems inconvenient that <function>Exec</function> does not
     accept C++ <literal>string</>s directly.  This choice was made to prevent
     the interface from inviting you to write inefficient code that makes
     multiple unnecessary conversions between C strings and C++ 
     <literal>string</>s.
    </para>
   </sect2>

   <sect2>
    <title>Getting query results</title>
    <para>
     Obviously not all queries are commands--the more common kind actually
     returns useful data.  Result data in <productname>libpqxx</productname>
     are encapsulated in a <literal>Result</literal> object, which acts as a
     container similar to the STL's <literal>vector</literal> template.
    </para>
    <programlisting>
Result R = T.Exec("SELECT firstname FROM employee WHERE lastname='Ng'");
    </programlisting>
    <para>
     Two ways are provided to get at individual rows in a 
     <literal>Result</literal>: first, through indexing with the array index 
     operator <literal>[]</literal> or the <function>at</> member function, and 
     second, through random-access iterators.  Either will give you a 
     <literal>Result::Tuple</literal> object that in turn can be addressed with 
     the array index operator (or the <function>at</> member function) to get 
     at its individual fields
      <footnote>
       The difference between <literal>[]</literal> and <function>at</function> 
       is that the latter does bounds-checking, throwing an exception if you 
       pass it an illegal index value.  With the array index operator you get 
       slightly better performance, but attempting to address a nonexistant
       row or field will result in undefined behaviour such as program crashes
       or inexplicably strange results.
      </footnote>.
    </para>
    <para>
     Thus, <literal>R[0]</literal> will return the first ("zeroeth") tuple in 
     R.  You won't normally want to bother with <literal>Tuple</>s though; they
     don't contain the actual data, but rather serve as placeholders to later 
     tell <literal>Result</literal> which fields to fetch when field values 
     from the tuple are requested.  The class exists mostly for technical 
     reasons related to the array index operators<footnote>
      <para>
       This is an instance of the <wordasword>Proxy</> implementation pattern, 
       needed to allow a <literal>Result</literal> to be indexed as if it were 
       a two-dimensional array.  C++'s array index operator doesn't allow this
       usage directly, but the operator can be applied to the result of a
       previous use of the same operator.  The "result in the middle" needs to
       have a type of its own, though.
      </para>
     </footnote>.
     What you'll usually do is index the row directly to get at the field you
     want, eg. <literal>R[0][0]</literal> to get the first field of the first
     row.
    </para>
    <para>
     Array indexing of tuples also works with the fields' names instead of 
     their numbers, eg.:
    </para>
    <programlisting>
// Process employees' names one by one.  ProcessNames() doesn't know exactly
// what columns are going to be in R, but there must be one called "lastname".
void ProcessNames(Result R)
{
  for (Result::size_type i = 0; i != R.size(); ++i)
    Process(R[i]["lastname"]);
}
    </programlisting>
    <para>
     As for the alternative, accessing the result tuples through an iterator,
     only <literal>const</literal> iterators are provided so the contents of
     the result cannot be modified.  Use these iterators as random-access
     iterators like with any STL-like container:
    </para>
    <programlisting>
for (Result::const_iterator i = R.begin(); i != R.end(); ++i)
  Process(*i);
    </programlisting>
    <para>
     Iterators may be incremented or decremented (whether pre- or post-), they
     may be added to or subtracted from to jump through the result tuples;
     their positions may be compared (provided they point into the same
     <literal>Result</>, and they may be dereferenced through the <literal>*</>
     or <literal>-></literal> operators.
    </para>
    <para>
     Finally, the iterated tuples' fields may be addressed using the array 
     index operator on the iterator directly, eg. <literal>R.begin()[0]</>
     gets you the first field of <literal>R</>'s first row, just like
     <literal>R[0][0]</> would<footnote>
      <para>
       Or <literal>(*R.begin())[0]</literal>.  It may seem quirky to have
       <literal>R.begin()</> and <literal>*R.begin()</> mean the same thing, 
       but it makes practical use of iterators a lot easier.
      </para>
     </footnote>.
    </para>
    <para>
     Either way, once you've indexed the <literal>Result::Tuple</> you get a 
     <literal>Result::Field</>--which is another placeholder, but this time
     encapsulates an actual field value in our query result.  A 
     <literal>Field</> <literal>F</> also knows its column name, which can be 
     obtained as <literal>F.Name()</>.
    </para>
    <para>
     Again, there is more than one way to read the field's value.  Let's start
     out with the easy one, <function>c_str</>, which reads the value as a 
     C string:
    </para>
    <programlisting>
cout &lt;&lt; "Name: " &lt;&lt; F.c_str() &lt;&lt; endl;
    </programlisting>
    <para>
     This will return the empty string (<literal>""</literal>) if field F has 
     the null value.  Use <function>is_null</function> to see if this is the 
     case:
    </para>
    <programlisting>
if (!F.is_null())
  cout &lt;&lt; "Name: " &lt;&lt; F.c_str() &lt;&lt; endl;
    </programlisting>
    <para>
     In practice of course, not all data is going to consist of strings.  Many
     fields will be integer values, or decimals, or Booleans.  To convert the
     field's value to one of these, use its <function>to</> method.  This
     adapts itself to the type of variable you pass it, expecting the field
     value to be of an appropriate form for that type.  For convenience,
     <function>to</> returns <literal>false</> if the field had the null
     value, and <literal>true</> otherwise.  In the former case, the variable
     will retain the value it had before the call.
    </para>
    <programlisting>
// Pay an employee his salary.  Add bonus for managers.
// The employee tuple must contain the fields
void PaySalary(Result::const_iterator empl)
{
  long id;
  float salary;
  bool is_manager=false;

  // Get id.  Must never be null.
  if (!i[0].to(id)) throw runtime_error("No id!");

  // Get salary.  If this employee has no salary, skip payment.
  if (!i[1].to(salary)) return;

  // Get manager status.  If field is null, variable's original value (false)
  // will be preserved.
  i[2].to(is_manager);

  if (is_manager) salary += Bonus;

  TransferMoney(id, salary);
}
    </programlisting>
    <para>
     If conversion fails, eg. when trying to convert a floating-point value to
     an integer variable, <function>to</function> will throw a 
     <literal>runtime_error</literal> reporting the problem in its 
     <function>what</function> message.
    </para>
   </sect2>

   <sect2>
    <title>Doing Transactions Right: Transactors</title>
    <para>
     Writing database code can be tricky.  One of the most complicated areas is
     dealing with unexpected error conditions, such as losing one's connection
     to the database server.  For long-running processes you'll frequently
     find yourself rewriting code for a simple transaction to make it:
    </para>
    <itemizedlist>
     <listitem> 
      Attempt to perform the transaction.
     </listitem>

     <listitem>
      Check for "connection lost" errors.
     </listitem>

     <listitem>
      Attempt to restore the connection.
     </listitem>

     <listitem>
      Repeat until the transaction succeeds.
     </listitem>
    </itemizedlist>

    <para>
     This is bad for the heart, and clutters up your code besides.  The
     <literal>Transactor</literal> framework will take this work out of your
     hands if you let it.  
    </para>
     
    <sect3>
     <title>Functors</title>
     <para>
      The mechanism is based on the concept of <emphasis>Functors</>, a
      powerful object-oriented design pattern that replaces the older practice
      of passing callback functions (or hooks, as they're sometimes called, or
      exits) to foreign code.  Unlike classic callback functions, Functors 
      provide an elegant way of maintaining custom state in your callback 
      code, when the exact form or size of that state was not known in advance
      to the writer of the foreign code that will eventually invoke your 
      callback.
     </para>

     <para>
      Functors in C++ are simple objects that can be invoked just like 
      functions or function pointers can, by virtue of providing the function
      invocation operator, <function>operator()</>.
     </para>

     <para>
      A simple functor could look like this:
     </para>

     <programlisting>
struct HelloFunctor
{
  void operator()() { cout &lt;&lt; "Hello World" &lt;&lt; endl; }
};
     </programlisting>

     <para>
      ...And once an object of this functor type has been created, it can be
      "invoked" just as if it were a function:
     </para>

     <programlisting>
HelloFunctor Hi;
Hi();
     </programlisting>

     <para>
      But the invoking code may also be foreign code knowing nothing about the
      type of your functor.  The foreign code is usually a template, so it
      automatically becomes "specialized" to your type of functor when the one 
      meets the other: 
     </para>
     <programlisting>
template&lt;typename FUNCTOR&gt; void DoFunctor(const FUNCTOR &Hi)
{
  Hi();
}
     </programlisting>

     <para>
      The great thing about functors is that they can carry state.  This is
      most useful when you need to pass a functor object to foreign code like
      <function>DoFunctor</> above, but you need certain extra parameters to be 
      passed to your functor that the foreign code isn't going to pass.  The 
      classic C solution to this problem is to let you pass both a function 
      pointer and a pointer-to-<literal>void</> as a method of letting you 
      provide any type of data of your liking to it.  This generally makes 
      programs a little harder to read, and is not very safe or convenient.
     </para>

     <para>
      With functors, there is a better way to do the same thing.  Let's say you
      want to adapt the <literal>HelloFunctor</literal> class to print its
      output to a different output stream.  What you'd really like to do is add
      a parameter to your <literal>()</literal> operator to indicate which
      stream to print to:
     </para>
     <programlisting>
  void operator()(ostream &Stream) 
  { 
    Stream &lt;&lt; "Hello World" &lt;&lt; endl;
  }
     </programlisting>

     <para>
      Unfortunately, <function>DoFunctor</function> doesn't know about this new 
      parameter, let alone what argument to pass!  So instead, let's make this 
      <literal>Stream</literal> a class member:
     </para>
     <programlisting>
struct HelloFunctor
{
  ostream &amp;Stream;

  // Set Stream when creating a HelloFunctor
  explicit HelloFunctor(ostream &amp;S) : Stream(S) { }

  // Print to output stream selected at construction time
  void operator()()
  {
    Stream &lt;&lt; "Hello World" &lt;&lt; endl;
  }
};
     </programlisting>

     <para>
      We can now provide the necessary information (ie., which stream to print
      to) to our <literal>HelloFunctor</literal> before we pass it to
      <function>DoFunctor</>:
     </para>

     <programlisting>
  HelloFunctor Hi1(cout), Hi2(cerr);

  DoFunctor(Hi1);  // Print to cout
  DoFunctor(Hi2);  // Print to cerr
     </programlisting>
    </sect3>

    <para>
     Naturally a functor's <literal>()</literal> operator may also return some
     other type than <literal>void</literal>, and it may take arguments just
     like any other function.  This mechanism is used extensively by the STL to 
     sort containers, to find items in sorted containers like 
     <literal>set</literal> or <literal>map</literal>, and so on.
    </para>

    <sect3>
     <title>How Transactors Work</title>

     A transactor is a functor derived from <filename>libpqxx</>'s
     <literal>Transactor</literal> class.  Instead of writing your database 
     transaction inline with the rest of your code, you encapsulate it in your
     functor's <literal>()</literal> operator.  When the time comes to execute
     your transaction, you create an object of your functor type and pass it to
     the <function>Perform</function> method of your 
     <literal>Connection</literal> to the database.

     <para>
      <function>Perform</function> will make a copy of your transactor (which
      means it needs to be copy-constructible, by the way).  It will also create
      a transaction object and invoke your transactor's <literal>()</literal>
      operator, passing the transaction object to it.  All your transactor needs
      to do is perform its queries on this object and return, after which
      <function>Perform</function> will commit the transaction.  If your
      <literal>()</literal> operator throws an exception instead, 
      <function>Perform</function> will discard the copy of your original
      transactor, and try again with a new copy until it either succeeds or
      eventually gives up<footnote>
       <function>Perform</> gives up if the transaction fails too many times in
       succession.  The maximum number of attempts that are made can be passed
       to <function>Perform</> as an optional second argument.
      </footnote>.  
      If the connection is lost, the transaction will fail
      but <function>Perform</> will restore it transparently and simply try 
      again.
     </para>

     <para>
      To make all this work, your transactor's <literal>()</literal> operator
      must make <emphasis>no</emphasis> changes to the rest of your program's 
      state.  Any intermediate results, data to be processed, and so on, must
      stay within your transactor, and be destroyed when the transactor is.  
      That is the magic trick that allows <function>Perform</function> to 
      create copies of your transactor and use them to rerun the transaction as
      many times as needed, without your program noticing.
     </para>

     <para>
      So how does your transactor pass query results back to the outside world
      once it's done?  For this purpose, you may redefine 
      <literal>Transactor</>'s <function>OnCommit</function> member function to
      pass any data back to the rest of your program.  This member function will
      be called only if your transaction succeeded.
     </para>
     
     <para>
      (You may also wish to go the other route, storing data to variables
      outside the transactor right away, and override the <function>OnAbort</>
      and <function>OnDoubt</> functions to remove the data again if the 
      transaction failed, but this is much more likely to cause subtle bugs.)
     </para>
    </sect3>

    <para>
     Please refer to the reference manual, the source code, and the test 
     programs that come with <filename>libpqxx</> to learn more about how
     transactors work.
    </para>
     
   </sect2>

  </sect1>

 </chapter>

@


1.11
log
@*** empty log message ***
@
text
@d909 14
a922 5
     <literal>Result</literal>: through indexing with the array index operator
     <literal>[]</literal>, and through random-access iterators.  Either way,
     this will give you a <literal>Result::Tuple</literal> object that in turn
     can be addressed with the array index operator to get at its individual
     fields.
d932 3
a934 3
       This is an instance of the <wordasword>Proxy</> design pattern, needed 
       to allow a <literal>Result</literal> to be indexed as if it were a 
       two-dimensional array.  C++'s array index operator doesn't allow this
d1002 3
a1004 2
     This will return the empty string (<literal>""</>) if field F has the
     null value.  Use <function>is_null</> to see if this is the case:
d1050 218
@


1.10
log
@*** empty log message ***
@
text
@d20 1
a20 1
    <filename>libpq++</filename>.
d54 4
a57 3
        Ad-hoc exception classes.  Programs using such libraries need to deal 
	with various incompatible exception hierarchies, and error handling
	becomes a total nightmare.
d64 3
a66 2
	put it, "if C++ doesn't have a standard string, there will be blood in
	the streets."  Luckily, the committee saw the wisdom in this.
d80 4
a83 4
        Ad-hoc containers and algorithms.  Inventing your own container APIs is
	not just wasted development effort unless you happen to be designing a
	new and different container library.  Having to learn how they work is
	wasted user effort as well.
d106 1
a106 1
       masculine, regardless of actual gender.
d186 3
a188 1
      to a <productname>PostgreSQL</productname> back-end server.
d226 1
a226 1
    <literal>Quote()</literal> function, which you should use whenever you want
d232 8
a239 6
    There are other classes; these are either not essential to writing a simple
    program using <filename>libpqxx</filename>, or are used in such a way that
    knowledge of them is not immediately necessary.  You will probably want to
    look them up at some point when it becomes necessary to understand 
    complex compiler warnings.  Unfortunately C++ compilers are not yet very
    good at unravelling template-related errors and making them readable.
d247 3
a249 3
      <literal>broken_connection</literal> is an exception class that is
      may be thrown when <filename>libpqxx</filename> loses its connection to 
      the back-end.  It is derived from the standard C++ exception
d286 3
a288 3
      When this happens, an <literal>in_doubt_error</literal> is thrown which
      you may want to <literal>catch</literal> as a special case.  If you do,
      make sure all alarm bells go off!
d404 8
d462 4
a465 4
     <literal>Quote</literal> is the canonical way to use strings in your SQL.
     This function not only adds quotes around your string; it also escapes
     quotes, backslashes, and other characters that would otherwise cause syntax
     errors in your queries when included directly.
d477 1
a477 1
     <literal>ToString</literal> knows how to render many types of values as
d489 2
a490 2
     <literal>FromString</literal> is the inverse of 
     <literal>ToString</literal>.  Like <literal>ToString</literal> it may
d492 2
a493 2
     <literal>Result::Field::to()</literal> to convert the incoming field data 
     (which is in text format) to the desired C++ type.
d497 9
d530 2
a531 2
      If you're ever in doubt about how to use the basic features of 
      <filename>libpqxx</filename>, take a look at the example programs 
d533 2
a534 2
      <filename>test2</filename> etc.  That should help give you an idea of how 
      simple the library can be in practice.  Don't let that keep you from 
d562 1
a562 1
        near the top of each source file using <filename>libpqxx</filename>.
d630 2
a631 2
     The <literal>Connection</literal> can now act as a counter window for our 
     database; your client will use it to perform one or more transactions
d636 2
a637 2
     Connections cannot be copied or assigned; any attempt to do so will be met 
     with a compiler error.
d661 6
a666 6
      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."
d670 2
a671 2
      through a <literal>Transaction</literal> object, so familiarity with this
      class is essential.
d717 4
a720 3
      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.
d814 1
a814 1
	 exceptions from a destructor.</>
a1040 9

  </sect1>

  <sect1>
   <title>Reference</title>

   <para>
    Yet to be written!
   </para>
@


1.9
log
@*** empty log message ***
@
text
@d382 1
a382 1
      <literal>TRANSACTIONTYPE</literal> typedef defined within its base class,
d958 1
a958 1
     obtained as <literal>F.name()</>.
@


1.8
log
@Mainly DocBook syntax fixes, thanks Ray Dassen
@
text
@d194 7
a200 1
      undone by the backend as if it had never happened.
d203 3
a205 7
      Actually <filename>libpqxx</filename> provides three classes doing this
      at various levels of reliability, called 
      <literal>NonTransaction</literal>, <literal>Transaction</literal>, and
      <literal>RobustTransaction</literal> for little, standard, and best
      reliability respectively.  These are all derived from a single abstract
      base class called <literal>TransactionItf</literal>, which defines the
      library's public transaction programming interface.
d214 1
a214 1
      container as found in the STL.
d221 7
d230 8
a237 2
    knowledge of them is not immediately necessary.
    </para>
d241 3
a243 4
      <literal>broken_connection</literal> is a connection class that is
      sometimes (but currently not necessarily) thrown when 
      <filename>libpqxx</filename> loses its connection to the back-end.  It 
      is derived from the standard C++ exception 
d245 3
a247 1
      such.
d264 90
d363 10
d375 9
a383 3
      <literal>Transaction</literal>.  You should generally try to write your
      code as a class derived from <literal>Transactor</literal>, but this is
      not required.
d402 13
d439 45
d485 1
@


1.7
log
@*** empty log message ***
@
text
@d1 1
a1 1

d46 2
a47 2
	the caller to check for errors "if it's interested."  <strong>Of 
	course</strong> he's interested.  But checking each and every call is
d102 4
a105 2
     <footnote>Yes, <strong>him</>self.  A "writer" is grammatically masculine,
      regardless of actual gender.
d383 6
a388 3
    <para>
     Now let's get programming...
    </para>
d408 1
a408 1
     <italics>connect string</>.  This string may be used to specify which host
d412 1
a412 1
     <functionname>connect</functionname> call</xref> for a complete definition 
d457 1
a457 1
      A transaction demarcates a <italics>unit of work</> operating on the 
d461 2
a462 3
      called the <italics>commit</italics> operation, and the process of 
      aborting it and undoing any changes it may have made is called 
      <italics>rollback</>.
d504 5
a508 5
      <italics>explicit commit</italics>, 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.
d606 5
a610 3
        Throwing an exception from a destructor to report the error would have
	serious effects on program correctness.  <italics>Never throw 
	exceptions from a destructor.</italics>
d637 1
a637 1
       the transaction code, <strong>not</strong> after the 
d666 1
a666 1
     the query string to its <functionname>Exec</functionname> method.  If the
d677 1
a677 1
void DeleteEntry(Transaction &T, string Table, long ID)
d683 1
a683 1
     It seems inconvenient that <functionname>Exec</functionname> does not
d711 10
a720 9
     Thus, <literal>R[0]</literal> will return the first (<italics>zeroeth</>)
     tuple in R.  You won't normally want to bother with <literal>Tuple</>s
     though; they don't contain the actual data, but rather serve as 
     placeholders to later tell <literal>Result</literal> which fields to fetch
     when field values from the tuple are requested.  The class exists mostly 
     for technical reasons related to the array index operators<footnote>
       This is an instance of the <italics>Proxy</italics> design pattern,
       needed to allow a <literal>Result</literal> to be indexed as if it were
       a two-dimensional array.  C++'s array index operator doesn't allow this
d724 1
d765 5
a769 3
      Or <literal>(*R.begin())[0]</literal>.  It may seem quirky to have
      <literal>R.begin()</> and <literal>*R.begin()</> mean the same thing, but
      it makes practical use of iterators a lot easier.
d781 1
a781 1
     out with the easy one, <functionname>c_str</>, which reads the value as a 
d785 1
a785 1
cout << "Name: " << F.c_str() << endl;
d789 1
a789 1
     null value.  Use <functionname>is_null</> to see if this is the case:
d793 1
a793 1
  cout << "Name: " << F.c_str() << endl;
d798 1
a798 1
     field's value to one of these, use its <functionname>to</> method.  This
d801 1
a801 1
     <functionname>to</> returns <literal>false</> if the field had the null
d831 1
a831 1
     an integer variable, <functionname>to</functionname> will throw a 
d833 1
a833 1
     <functionname>what</functionname> message.
@


1.6
log
@Fixed loads of errors, thanks Bruce Momjian
@
text
@d621 1
a621 1
  // (Query with SQL syntax error)
@


1.5
log
@Great Renaming
@
text
@d1 1
d10 3
a12 3
    <filename>libpq++</filename> with a more <acronym>STL</acronym>-conformant 
    interface and makes more extensive use of C++ language features such as 
    exceptions, templates, and strings.
d170 1
a170 1
   <title>Class overview</title1>
d176 9
a184 7
    <itemizedlist>
     <listitem>
      <para>
       <literal>Connection</literal> represents a connection from your program
       to a <productname>PostgreSQL</productname> back-end server.
      </para>
     </listitem>
d186 18
a203 9
     <listitem>
      <para>
       <literal>Transaction</literal> represents a transaction being executed 
       in the context of a <literal>Connection</literal>, and is a unit of work 
       that must be either completed as a whole.  If execution fails, 
       everything done within that <literal>Transaction</literal> is undone by 
       the backend as if it had never happened.
      </para>
     </listitem>
d205 8
a212 7
     <listitem>
      <para>
       <literal>Result</literal> is a container holding the resulting data
       coming out of a query or command executed in a 
       <literal>Transaction</literal>.
      </para>
     </listitem>
d214 1
a214 2
    </itemizedlist>
   </para>
d220 12
a231 11
    <itemizedlist>
     <listitem>
      <para>
       <literal>broken_connection</literal> is a connection class that is
       sometimes (but currently not necessarily) thrown when 
       <filename>libpqxx</filename> loses its connection to the back-end.  It 
       is derived from the standard C++ exception 
       <literal>std::runtime_error</literal>, and can generally be treated as
       such.
      </para>
     </listitem>
d233 10
a242 10
     <listitem>
      <para>
       <literal>Cursor</literal> is a way of iterating over a query result 
       using an SQL cursor.  This can be useful for selectively retrieving 
       parts of a query, or for retrieving and processing results in chunks so 
       your program can do useful work on one chunk while the next is still 
       coming in over a network connection.  Or you may want to use this to 
       give progress reports to the user between chunk transfers.
      </para>
     </listitem>
d244 8
a251 8
     <listitem>
      <para>
       <literal>TableStream</literal> provides simple, relatively direct access
       to a table for either reading (<literal>TableReader</literal>) or
       writing (<literal>TableWriter</literal>) using 
       <productname>PostgreSQL</productname>'s <literal>COPY</literal> command.
      </para>
     </listitem>
d253 9
a261 9
     <listitem>
      <para>
       <literal>Transactor</literal> is a framework that makes it easier for 
       you to write correct, robust transaction code to be executed in a
       <literal>Transaction</literal>.  You should generally try to write your
       code as a class derived from <literal>Transactor</literal>, but this is
       not required.
      </para>
     </listitem>
d263 12
a274 12
     <listitem>
      <para>
       <literal>Trigger</literal> is an instance of the Observer design 
       pattern.  Any code connected to a backend may flag an event using the 
       <productname>PostgreSQL</productname> <literal>NOTIFY</literal> command. 
       Frontends connected to that same backend database may be listening for 
       an event of that name to occur.  A frontend using 
       <filename>libpqxx</filename> does this by registering an observer object 
       derived from <literal>Trigger</literal>, which will be invoked by 
       <filename>libpqxx</filename> to handle the event when it occurs.
      </para>
     </listitem>
d276 7
a282 7
     <listitem>
      <para>
       <literal>Result::Tuple</literal> is a nested class defined within
       <literal>Result</literal>.  It refers to a tuple of data within a
       <literal>Result</literal> object.
      </para>
     </listitem>
d284 8
a291 8
     <listitem>
      <para>
       <literal>Result::Field</literal>, also nested within 
       <literal>Result</literal>, refers to one field within a 
       <literal>Tuple</literal>.  A <literal>Field</literal> contains one 
       retrieved value such as a number or a string.
      </para>
     </listitem>
d293 7
a299 7
     <listitem>
      <para>
       <literal>Result::const_iterator</literal> allows you to enumerate the
       <literal>Tuple</>s in a <literal>Result</literal> in a similar way to
       the iterators defined by any standard C++ container.
      </para>
     </listitem>
d310 2
a311 1
    <sect3>This document</sect3>
d315 1
a315 1
      frontend library, which defines <productname>PostgreSQL<productname>'s C 
d342 1
a342 1
     <para>
d406 4
a409 3
     etc.  Refer to <xref linkend="libpq-connect"> for a complete definition of
     what may go into the connect string.  In this case we're connecting to a
     database <literal>test</literal> residing on the local machine.
d465 1
a465 1
    <sect3>
d500 2
a501 2
      <italics>explicit commit</>, ie. the commit operation must always be
      explicit in the code.  If the Transaction is destroyed before a commit
d750 1
a750 1
     or <literal>-&gt;</literal> operators.
d775 1
a775 1
cout &lt;&lt; "Name: " &lt;&lt; F.c_str() &lt;&lt; endl;
d783 1
a783 1
  cout &lt;&lt; "Name: " &lt;&lt; F.c_str() &lt;&lt; endl;
d821 3
a823 3
     an integer variable, <functionname>to</> will throw a 
     <literal>runtime_error</> reporting the problem in its 
     <functionname>what</> message.
@


1.4
log
@Some extra explanation on transaction bracketing implementation.
@
text
@d174 1
a174 1
    <literal>Pg</literal>:
d326 1
a326 1
      namespace <literal>Pg</literal>.  If you're not familiar with C++
d332 1
a332 1
       <para> Always import the whole of the <literal>Pg</literal> namespace 
d336 1
a336 1
	<literal>Pg</literal> namespace when trying to resolve a name that 
d340 1
a340 1
using namespace Pg;
d348 1
a348 1
	the <literal>Pg</literal> namespace.
d353 1
a353 1
	the <literal>Pg</literal> namespace, avoiding any confusion over
d357 1
a357 1
	<literal>Pg::Connection</literal> instead of 
d359 1
a359 1
	<literal>Pg::Result::const_iterator</literal> instead of
@


1.3
log
@*** empty log message ***
@
text
@d14 8
d517 17
d582 12
@


1.2
log
@*** empty log message ***
@
text
@d738 4
a741 1
     value to be of an appropriate form for that type:
d767 6
@


1.1
log
@Initial revision
@
text
@d36 9
d576 12
d602 29
a630 1
    TODO: Write!
d635 129
a763 1
    TODO: Write!
@


1.1.1.1
log
@Imported sources
@
text
@@
