diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,40 @@
+# Changelog
+
+## 2.5.0.1
+
+* Bump time upper bound to 1.14, add round-trip test for 0-padded date.
+
+## 2.5.0.0
+
+* Add explicit call to `finalizeForeignPtr` on connection disconnects. Ensures disconnects happen at the moment close is call, as opposed to when the GC frees the ForeignPtr.
+
+## 2.4.0.0
+
+* Remove custom reference counting logic. Thanks to David Johnson.
+
+### 2.3.2.8
+
+* Compatiblity with Cabal 3.2
+
+### 2.3.2.7
+
+* Compatibility with time 1.9 & GHC 8.8
+* Custom setup for cabal v2 & v3
+
+### 2.3.2.6
+
+* Fix postgresql header name collision
+
+#### 2.3.2.5
+
+* Compatibility with time 1.8, GHC 8.2.
+
+#### 2.3.2.4
+
+* Compatibility with time 1.6, base 4.9, and Cabal 1.24 (GHC 8).
+
+#### 2.3.2.3
+
+* Compatibility with time 1.5.
+* Fix test compilation.
+* Fix warnings.
diff --git a/COPYING b/COPYING
deleted file mode 100644
--- a/COPYING
+++ /dev/null
@@ -1,510 +0,0 @@
-
-                  GNU LESSER GENERAL PUBLIC LICENSE
-                       Version 2.1, February 1999
-
- Copyright (C) 1991, 1999 Free Software Foundation, Inc.
-	51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-[This is the first released version of the Lesser GPL.  It also counts
- as the successor of the GNU Library Public License, version 2, hence
- the version number 2.1.]
-
-                            Preamble
-
-  The licenses for most software are designed to take away your
-freedom to share and change it.  By contrast, the GNU General Public
-Licenses are intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-
-  This license, the Lesser General Public License, applies to some
-specially designated software packages--typically libraries--of the
-Free Software Foundation and other authors who decide to use it.  You
-can use it too, but we suggest you first think carefully about whether
-this license or the ordinary General Public License is the better
-strategy to use in any particular case, based on the explanations
-below.
-
-  When we speak of free software, we are referring to freedom of use,
-not price.  Our General Public Licenses are designed to make sure that
-you have the freedom to distribute copies of free software (and charge
-for this service if you wish); that you receive source code or can get
-it if you want it; that you can change the software and use pieces of
-it in new free programs; and that you are informed that you can do
-these things.
-
-  To protect your rights, we need to make restrictions that forbid
-distributors to deny you these rights or to ask you to surrender these
-rights.  These restrictions translate to certain responsibilities for
-you if you distribute copies of the library or if you modify it.
-
-  For example, if you distribute copies of the library, whether gratis
-or for a fee, you must give the recipients all the rights that we gave
-you.  You must make sure that they, too, receive or can get the source
-code.  If you link other code with the library, you must provide
-complete object files to the recipients, so that they can relink them
-with the library after making changes to the library and recompiling
-it.  And you must show them these terms so they know their rights.
-
-  We protect your rights with a two-step method: (1) we copyright the
-library, and (2) we offer you this license, which gives you legal
-permission to copy, distribute and/or modify the library.
-
-  To protect each distributor, we want to make it very clear that
-there is no warranty for the free library.  Also, if the library is
-modified by someone else and passed on, the recipients should know
-that what they have is not the original version, so that the original
-author's reputation will not be affected by problems that might be
-introduced by others.
-
-  Finally, software patents pose a constant threat to the existence of
-any free program.  We wish to make sure that a company cannot
-effectively restrict the users of a free program by obtaining a
-restrictive license from a patent holder.  Therefore, we insist that
-any patent license obtained for a version of the library must be
-consistent with the full freedom of use specified in this license.
-
-  Most GNU software, including some libraries, is covered by the
-ordinary GNU General Public License.  This license, the GNU Lesser
-General Public License, applies to certain designated libraries, and
-is quite different from the ordinary General Public License.  We use
-this license for certain libraries in order to permit linking those
-libraries into non-free programs.
-
-  When a program is linked with a library, whether statically or using
-a shared library, the combination of the two is legally speaking a
-combined work, a derivative of the original library.  The ordinary
-General Public License therefore permits such linking only if the
-entire combination fits its criteria of freedom.  The Lesser General
-Public License permits more lax criteria for linking other code with
-the library.
-
-  We call this license the "Lesser" General Public License because it
-does Less to protect the user's freedom than the ordinary General
-Public License.  It also provides other free software developers Less
-of an advantage over competing non-free programs.  These disadvantages
-are the reason we use the ordinary General Public License for many
-libraries.  However, the Lesser license provides advantages in certain
-special circumstances.
-
-  For example, on rare occasions, there may be a special need to
-encourage the widest possible use of a certain library, so that it
-becomes a de-facto standard.  To achieve this, non-free programs must
-be allowed to use the library.  A more frequent case is that a free
-library does the same job as widely used non-free libraries.  In this
-case, there is little to gain by limiting the free library to free
-software only, so we use the Lesser General Public License.
-
-  In other cases, permission to use a particular library in non-free
-programs enables a greater number of people to use a large body of
-free software.  For example, permission to use the GNU C Library in
-non-free programs enables many more people to use the whole GNU
-operating system, as well as its variant, the GNU/Linux operating
-system.
-
-  Although the Lesser General Public License is Less protective of the
-users' freedom, it does ensure that the user of a program that is
-linked with the Library has the freedom and the wherewithal to run
-that program using a modified version of the Library.
-
-  The precise terms and conditions for copying, distribution and
-modification follow.  Pay close attention to the difference between a
-"work based on the library" and a "work that uses the library".  The
-former contains code derived from the library, whereas the latter must
-be combined with the library in order to run.
-
-                  GNU LESSER GENERAL PUBLIC LICENSE
-   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
-  0. This License Agreement applies to any software library or other
-program which contains a notice placed by the copyright holder or
-other authorized party saying it may be distributed under the terms of
-this Lesser General Public License (also called "this License").
-Each licensee is addressed as "you".
-
-  A "library" means a collection of software functions and/or data
-prepared so as to be conveniently linked with application programs
-(which use some of those functions and data) to form executables.
-
-  The "Library", below, refers to any such software library or work
-which has been distributed under these terms.  A "work based on the
-Library" means either the Library or any derivative work under
-copyright law: that is to say, a work containing the Library or a
-portion of it, either verbatim or with modifications and/or translated
-straightforwardly into another language.  (Hereinafter, translation is
-included without limitation in the term "modification".)
-
-  "Source code" for a work means the preferred form of the work for
-making modifications to it.  For a library, complete source code means
-all the source code for all modules it contains, plus any associated
-interface definition files, plus the scripts used to control
-compilation and installation of the library.
-
-  Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope.  The act of
-running a program using the Library is not restricted, and output from
-such a program is covered only if its contents constitute a work based
-on the Library (independent of the use of the Library in a tool for
-writing it).  Whether that is true depends on what the Library does
-and what the program that uses the Library does.
-
-  1. You may copy and distribute verbatim copies of the Library's
-complete source code as you receive it, in any medium, provided that
-you conspicuously and appropriately publish on each copy an
-appropriate copyright notice and disclaimer of warranty; keep intact
-all the notices that refer to this License and to the absence of any
-warranty; and distribute a copy of this License along with the
-Library.
-
-  You may charge a fee for the physical act of transferring a copy,
-and you may at your option offer warranty protection in exchange for a
-fee.
-
-  2. You may modify your copy or copies of the Library or any portion
-of it, thus forming a work based on the Library, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
-    a) The modified work must itself be a software library.
-
-    b) You must cause the files modified to carry prominent notices
-    stating that you changed the files and the date of any change.
-
-    c) You must cause the whole of the work to be licensed at no
-    charge to all third parties under the terms of this License.
-
-    d) If a facility in the modified Library refers to a function or a
-    table of data to be supplied by an application program that uses
-    the facility, other than as an argument passed when the facility
-    is invoked, then you must make a good faith effort to ensure that,
-    in the event an application does not supply such function or
-    table, the facility still operates, and performs whatever part of
-    its purpose remains meaningful.
-
-    (For example, a function in a library to compute square roots has
-    a purpose that is entirely well-defined independent of the
-    application.  Therefore, Subsection 2d requires that any
-    application-supplied function or table used by this function must
-    be optional: if the application does not supply it, the square
-    root function must still compute square roots.)
-
-These requirements apply to the modified work as a whole.  If
-identifiable sections of that work are not derived from the Library,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works.  But when you
-distribute the same sections as part of a whole which is a work based
-on the Library, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote
-it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Library.
-
-In addition, mere aggregation of another work not based on the Library
-with the Library (or with a work based on the Library) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
-  3. You may opt to apply the terms of the ordinary GNU General Public
-License instead of this License to a given copy of the Library.  To do
-this, you must alter all the notices that refer to this License, so
-that they refer to the ordinary GNU General Public License, version 2,
-instead of to this License.  (If a newer version than version 2 of the
-ordinary GNU General Public License has appeared, then you can specify
-that version instead if you wish.)  Do not make any other change in
-these notices.
-
-  Once this change is made in a given copy, it is irreversible for
-that copy, so the ordinary GNU General Public License applies to all
-subsequent copies and derivative works made from that copy.
-
-  This option is useful when you wish to copy part of the code of
-the Library into a program that is not a library.
-
-  4. You may copy and distribute the Library (or a portion or
-derivative of it, under Section 2) in object code or executable form
-under the terms of Sections 1 and 2 above provided that you accompany
-it with the complete corresponding machine-readable source code, which
-must be distributed under the terms of Sections 1 and 2 above on a
-medium customarily used for software interchange.
-
-  If distribution of object code is made by offering access to copy
-from a designated place, then offering equivalent access to copy the
-source code from the same place satisfies the requirement to
-distribute the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
-  5. A program that contains no derivative of any portion of the
-Library, but is designed to work with the Library by being compiled or
-linked with it, is called a "work that uses the Library".  Such a
-work, in isolation, is not a derivative work of the Library, and
-therefore falls outside the scope of this License.
-
-  However, linking a "work that uses the Library" with the Library
-creates an executable that is a derivative of the Library (because it
-contains portions of the Library), rather than a "work that uses the
-library".  The executable is therefore covered by this License.
-Section 6 states terms for distribution of such executables.
-
-  When a "work that uses the Library" uses material from a header file
-that is part of the Library, the object code for the work may be a
-derivative work of the Library even though the source code is not.
-Whether this is true is especially significant if the work can be
-linked without the Library, or if the work is itself a library.  The
-threshold for this to be true is not precisely defined by law.
-
-  If such an object file uses only numerical parameters, data
-structure layouts and accessors, and small macros and small inline
-functions (ten lines or less in length), then the use of the object
-file is unrestricted, regardless of whether it is legally a derivative
-work.  (Executables containing this object code plus portions of the
-Library will still fall under Section 6.)
-
-  Otherwise, if the work is a derivative of the Library, you may
-distribute the object code for the work under the terms of Section 6.
-Any executables containing that work also fall under Section 6,
-whether or not they are linked directly with the Library itself.
-
-  6. As an exception to the Sections above, you may also combine or
-link a "work that uses the Library" with the Library to produce a
-work containing portions of the Library, and distribute that work
-under terms of your choice, provided that the terms permit
-modification of the work for the customer's own use and reverse
-engineering for debugging such modifications.
-
-  You must give prominent notice with each copy of the work that the
-Library is used in it and that the Library and its use are covered by
-this License.  You must supply a copy of this License.  If the work
-during execution displays copyright notices, you must include the
-copyright notice for the Library among them, as well as a reference
-directing the user to the copy of this License.  Also, you must do one
-of these things:
-
-    a) Accompany the work with the complete corresponding
-    machine-readable source code for the Library including whatever
-    changes were used in the work (which must be distributed under
-    Sections 1 and 2 above); and, if the work is an executable linked
-    with the Library, with the complete machine-readable "work that
-    uses the Library", as object code and/or source code, so that the
-    user can modify the Library and then relink to produce a modified
-    executable containing the modified Library.  (It is understood
-    that the user who changes the contents of definitions files in the
-    Library will not necessarily be able to recompile the application
-    to use the modified definitions.)
-
-    b) Use a suitable shared library mechanism for linking with the
-    Library.  A suitable mechanism is one that (1) uses at run time a
-    copy of the library already present on the user's computer system,
-    rather than copying library functions into the executable, and (2)
-    will operate properly with a modified version of the library, if
-    the user installs one, as long as the modified version is
-    interface-compatible with the version that the work was made with.
-
-    c) Accompany the work with a written offer, valid for at least
-    three years, to give the same user the materials specified in
-    Subsection 6a, above, for a charge no more than the cost of
-    performing this distribution.
-
-    d) If distribution of the work is made by offering access to copy
-    from a designated place, offer equivalent access to copy the above
-    specified materials from the same place.
-
-    e) Verify that the user has already received a copy of these
-    materials or that you have already sent this user a copy.
-
-  For an executable, the required form of the "work that uses the
-Library" must include any data and utility programs needed for
-reproducing the executable from it.  However, as a special exception,
-the materials to be distributed need not include anything that is
-normally distributed (in either source or binary form) with the major
-components (compiler, kernel, and so on) of the operating system on
-which the executable runs, unless that component itself accompanies
-the executable.
-
-  It may happen that this requirement contradicts the license
-restrictions of other proprietary libraries that do not normally
-accompany the operating system.  Such a contradiction means you cannot
-use both them and the Library together in an executable that you
-distribute.
-
-  7. You may place library facilities that are a work based on the
-Library side-by-side in a single library together with other library
-facilities not covered by this License, and distribute such a combined
-library, provided that the separate distribution of the work based on
-the Library and of the other library facilities is otherwise
-permitted, and provided that you do these two things:
-
-    a) Accompany the combined library with a copy of the same work
-    based on the Library, uncombined with any other library
-    facilities.  This must be distributed under the terms of the
-    Sections above.
-
-    b) Give prominent notice with the combined library of the fact
-    that part of it is a work based on the Library, and explaining
-    where to find the accompanying uncombined form of the same work.
-
-  8. You may not copy, modify, sublicense, link with, or distribute
-the Library except as expressly provided under this License.  Any
-attempt otherwise to copy, modify, sublicense, link with, or
-distribute the Library is void, and will automatically terminate your
-rights under this License.  However, parties who have received copies,
-or rights, from you under this License will not have their licenses
-terminated so long as such parties remain in full compliance.
-
-  9. You are not required to accept this License, since you have not
-signed it.  However, nothing else grants you permission to modify or
-distribute the Library or its derivative works.  These actions are
-prohibited by law if you do not accept this License.  Therefore, by
-modifying or distributing the Library (or any work based on the
-Library), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Library or works based on it.
-
-  10. Each time you redistribute the Library (or any work based on the
-Library), the recipient automatically receives a license from the
-original licensor to copy, distribute, link with or modify the Library
-subject to these terms and conditions.  You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties with
-this License.
-
-  11. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License.  If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Library at all.  For example, if a patent
-license would not permit royalty-free redistribution of the Library by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Library.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply, and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system which is
-implemented by public license practices.  Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
-  12. If the distribution and/or use of the Library is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Library under this License
-may add an explicit geographical distribution limitation excluding those
-countries, so that distribution is permitted only in or among
-countries not thus excluded.  In such case, this License incorporates
-the limitation as if written in the body of this License.
-
-  13. The Free Software Foundation may publish revised and/or new
-versions of the Lesser General Public License from time to time.
-Such new versions will be similar in spirit to the present version,
-but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number.  If the Library
-specifies a version number of this License which applies to it and
-"any later version", you have the option of following the terms and
-conditions either of that version or of any later version published by
-the Free Software Foundation.  If the Library does not specify a
-license version number, you may choose any version ever published by
-the Free Software Foundation.
-
-  14. If you wish to incorporate parts of the Library into other free
-programs whose distribution conditions are incompatible with these,
-write to the author to ask for permission.  For software which is
-copyrighted by the Free Software Foundation, write to the Free
-Software Foundation; we sometimes make exceptions for this.  Our
-decision will be guided by the two goals of preserving the free status
-of all derivatives of our free software and of promoting the sharing
-and reuse of software generally.
-
-                            NO WARRANTY
-
-  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
-WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
-EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
-OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
-KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
-LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
-THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
-  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
-WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
-FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
-CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
-LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
-RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
-FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
-SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGES.
-
-                     END OF TERMS AND CONDITIONS
-
-           How to Apply These Terms to Your New Libraries
-
-  If you develop a new library, and you want it to be of the greatest
-possible use to the public, we recommend making it free software that
-everyone can redistribute and change.  You can do so by permitting
-redistribution under these terms (or, alternatively, under the terms
-of the ordinary General Public License).
-
-  To apply these terms, attach the following notices to the library.
-It is safest to attach them to the start of each source file to most
-effectively convey the exclusion of warranty; and each file should
-have at least the "copyright" line and a pointer to where the full
-notice is found.
-
-
-    <one line to give the library's name and a brief idea of what it does.>
-    Copyright (C) <year>  <name of author>
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
-
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-
-Also add information on how to contact you by electronic and paper mail.
-
-You should also get your employer (if you work as a programmer) or
-your school, if any, to sign a "copyright disclaimer" for the library,
-if necessary.  Here is a sample; alter the names:
-
-  Yoyodyne, Inc., hereby disclaims all copyright interest in the
-  library `Frob' (a library for tweaking knobs) written by James
-  Random Hacker.
-
-  <signature of Ty Coon>, 1 April 1990
-  Ty Coon, President of Vice
-
-That's all there is to it!
-
-
diff --git a/COPYRIGHT b/COPYRIGHT
deleted file mode 100644
--- a/COPYRIGHT
+++ /dev/null
@@ -1,38 +0,0 @@
-Copyright (C) 2005-2007 John Goerzen <jgoerzen@complete.org>
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
-
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-
-Please see COPYING for the license.
-
-------------------------------------------------------------------
-
-pgtypes.h comes from the psqlodbc distribution, which bears this
-copyright:
-
-    Copyright (C) 1998          Insight Distribution Systems
-    Copyright (C) 1998 - 2005   The PostgreSQL Global Development Group
-
-    Multibyte support was added by Sankyo Unyu Service, (C) 2001.
-
-    The code contained in this library is based on code written by
-    Christian Czezatke and Dan McGuirk, (C) 1996.
-
-    This library is free software; you can redistribute it and/or modify
-    it under the terms of the GNU Library General Public License as
-    published by the Free Software Foundation; either version 2 of the
-    License, or (at your option) any later version.
-
-Most of pgtypes.h was removed by John Goerzen since it was not
-relevant for this task.
diff --git a/Database/HDBC/PostgreSQL.hs b/Database/HDBC/PostgreSQL.hs
--- a/Database/HDBC/PostgreSQL.hs
+++ b/Database/HDBC/PostgreSQL.hs
@@ -1,25 +1,7 @@
-{-
-Copyright (C) 2005 John Goerzen <jgoerzen@complete.org>
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
-
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
--}
-
 {- |
    Module     : Database.HDBC.PostgreSQL
-   Copyright  : Copyright (C) 2005 John Goerzen
-   License    : GNU LGPL, version 2.1 or above
+   Copyright  : Copyright (C) 2005-2011 John Goerzen
+   License    : BSD3
 
    Maintainer : John Goerzen <jgoerzen@complete.org>
    Stability  : provisional
@@ -28,13 +10,73 @@
 HDBC driver interface for PostgreSQL 8.x
 
 Written by John Goerzen, jgoerzen\@complete.org
+
+/NOTE ON DATES AND TIMES/
+
+The recommended correspondence between PostgreSQL date and time types and HDBC SqlValue
+types is:
+
+* SqlLocalDate: DATE
+
+* SqlLocalTimeOfDay: TIME WITHOUT TIME ZONE
+
+* SqlZonedLocalTimeOfDay: TIME WITH TIME ZONE
+
+* SqlLocalTime: TIMESTAMP WITHOUT TIME ZONE
+
+* SqlZonedTime: TIMESTAMP WITH TIME ZONE
+
+* SqlUTCTime: TIMESTAMP WITH TIME ZONE
+
+* SqlDiffTime: INTERVAL
+
+* SqlPOSIXTime: NUMERIC
+
+* SqlEpochTime: INTEGER
+
+* SqlTimeDiff: INTERVAL
+
+Other combinations are possible, and may even be converted automatically.
+The above simply represents the types that seem the most logical correspondence,
+and thus are tested by the HDBC-PostgreSQL test suite.
+
 -}
 
 module Database.HDBC.PostgreSQL
     (
-     connectPostgreSQL, Connection
+     -- * Connecting to Databases
+     connectPostgreSQL, withPostgreSQL,
+     connectPostgreSQL', withPostgreSQL',
+     Connection,
+
+     -- * Transactions
+     begin,
+
+     -- * PostgreSQL Error Codes
+     --
+     -- |When an @SqlError@ is thrown, the field @seState@ is set to one of the following
+     -- error codes.
+     module Database.HDBC.PostgreSQL.ErrorCodes,
+
+     -- * Threading
+     -- $threading
     )
 
 where
 
-import Database.HDBC.PostgreSQL.Connection(connectPostgreSQL, Connection())
+import Database.HDBC.PostgreSQL.Connection(connectPostgreSQL, withPostgreSQL,
+                                           connectPostgreSQL', withPostgreSQL',
+                                           begin, Connection())
+import Database.HDBC.PostgreSQL.ErrorCodes
+
+{- $threading
+   
+   Provided the local libpq library is thread-safe, multiple 'Connection's may be used
+   to have concurrent database queries.  Concurrent queries issued on a single 
+   'Connection' will be performed serially.
+
+   When the local libpq library is not thread-safe (ie. it has not been compiled with 
+   --enable-thread-safety), only a single database function will be performed at a time.
+  
+-}
+
diff --git a/Database/HDBC/PostgreSQL/Connection.hsc b/Database/HDBC/PostgreSQL/Connection.hsc
--- a/Database/HDBC/PostgreSQL/Connection.hsc
+++ b/Database/HDBC/PostgreSQL/Connection.hsc
@@ -1,78 +1,91 @@
 -- -*- mode: haskell; -*-
-{-# CFILES hdbc-postgresql-helper.c #-}
 -- Above line for hugs
-{-
-Copyright (C) 2005-2006 John Goerzen <jgoerzen@complete.org>
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
-
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
--}
+{-# LANGUAGE FlexibleContexts #-}
 
 module Database.HDBC.PostgreSQL.Connection
-	(connectPostgreSQL, Impl.Connection())
+        (connectPostgreSQL, withPostgreSQL,
+         connectPostgreSQL', withPostgreSQL',
+         Impl.begin, Impl.Connection())
  where
 
-import Database.HDBC.Types
 import Database.HDBC
 import Database.HDBC.DriverUtils
-import Database.HDBC.ColTypes
 import qualified Database.HDBC.PostgreSQL.ConnectionImpl as Impl
 import Database.HDBC.PostgreSQL.Types
 import Database.HDBC.PostgreSQL.Statement
 import Database.HDBC.PostgreSQL.PTypeConv
 import Foreign.C.Types
 import Foreign.C.String
-import Foreign.Marshal
-import Foreign.Storable
 import Database.HDBC.PostgreSQL.Utils
 import Foreign.ForeignPtr
 import Foreign.Ptr
 import Data.Word
 import Data.Maybe
+import qualified Data.ByteString as B
+import qualified Data.ByteString.UTF8 as BUTF8
+import Control.Monad (when)
 import Control.Concurrent.MVar
+import System.IO (stderr, hPutStrLn)
+import System.IO.Unsafe (unsafePerformIO)
+import Control.Exception(bracket)
+import Data.Convertible (Convertible)
 
 #include <libpq-fe.h>
 #include <pg_config.h>
 
+
+-- | A global lock only used when libpq is /not/ thread-safe.  In that situation
+-- this mvar is used to serialize access to the FFI calls marked as /safe/.
+globalConnLock :: MVar ()
+{-# NOINLINE globalConnLock #-}
+globalConnLock = unsafePerformIO $ newMVar ()
+
 {- | Connect to a PostgreSQL server.
 
 See <http://www.postgresql.org/docs/8.1/static/libpq.html#LIBPQ-CONNECT> for the meaning
 of the connection string. -}
 connectPostgreSQL :: String -> IO Impl.Connection
-connectPostgreSQL args = withCString args $
+connectPostgreSQL = connectPostgreSQL_helper True
+
+connectPostgreSQL' :: String -> IO Impl.Connection
+connectPostgreSQL' = connectPostgreSQL_helper False
+
+connectPostgreSQL_helper :: Bool -> String -> IO Impl.Connection
+connectPostgreSQL_helper auto_transaction args =
+  B.useAsCString (BUTF8.fromString args) $
   \cs -> do ptr <- pqconnectdb cs
+            threadSafe <- pqisThreadSafe ptr
+            connLock <- if threadSafe==0 -- Also check GHC.Conc.numCapabilities here?
+                          then do hPutStrLn stderr "WARNING: libpq is not threadsafe, \
+                                          \serializing all libpq FFI calls.  \
+                                          \(Consider recompiling libpq with \
+                                          \--enable-thread-safety.\n"
+                                  return globalConnLock
+                          else newMVar ()
             status <- pqstatus ptr
-            wrappedptr <- wrapconn ptr nullPtr
-            fptr <- newForeignPtr pqfinishptr wrappedptr
+            fptr <- newForeignPtr pqfinish ptr
             case status of
-                     #{const CONNECTION_OK} -> mkConn args fptr
+                     #{const CONNECTION_OK} -> mkConn auto_transaction args (connLock,fptr)
                      _ -> raiseError "connectPostgreSQL" status ptr
 
 -- FIXME: environment vars may have changed, should use pgsql enquiries
 -- for clone.
-mkConn :: String -> Conn -> IO Impl.Connection
-mkConn args conn = withConn conn $
-  \cconn -> 
+mkConn :: Bool -> String -> Conn -> IO Impl.Connection
+mkConn auto_transaction args conn = withConn conn $
+  \cconn ->
     do children <- newMVar []
-       begin_transaction conn children
+       when auto_transaction $ begin_transaction conn children
        protover <- pqprotocolVersion cconn
        serverver <- pqserverVersion cconn
        let clientver = #{const_str PG_VERSION}
-       return $ Impl.Connection {
+       let rconn = Impl.Connection {
                             Impl.disconnect = fdisconnect conn children,
-                            Impl.commit = fcommit conn children,
-                            Impl.rollback = frollback conn children,
+                            Impl.begin = if auto_transaction
+                                         then return ()
+                                         else begin_transaction conn children,
+                            Impl.commit = fcommit auto_transaction conn children,
+                            Impl.rollback = frollback auto_transaction conn children,
+                            Impl.runRaw = frunRaw conn children,
                             Impl.run = frun conn children,
                             Impl.prepare = newSth conn children,
                             Impl.clone = connectPostgreSQL args,
@@ -84,7 +97,17 @@
                             Impl.dbTransactionSupport = True,
                             Impl.getTables = fgetTables conn children,
                             Impl.describeTable = fdescribeTable conn children}
+       _ <- quickQuery rconn "SET client_encoding TO utf8;" []
+       return rconn
 
+-- | Connect to a PostgreSQL server,  and automatically disconnect
+-- if the handler exits normally or throws an exception.
+withPostgreSQL :: String -> (Impl.Connection -> IO a) -> IO a
+withPostgreSQL connstr = bracket (connectPostgreSQL connstr) (disconnect)
+
+withPostgreSQL' :: String -> (Impl.Connection -> IO a) -> IO a
+withPostgreSQL' connstr = bracket (connectPostgreSQL' connstr) (disconnect)
+
 --------------------------------------------------
 -- Guts here
 --------------------------------------------------
@@ -92,67 +115,81 @@
 begin_transaction :: Conn -> ChildList -> IO ()
 begin_transaction o children = frun o children "BEGIN" [] >> return ()
 
+frunRaw :: Conn -> ChildList -> String -> IO ()
+frunRaw o children query =
+    do sth <- newSth o children query
+       executeRaw sth
+       finish sth
+       return ()
+
+frun :: Conn -> ChildList -> String -> [SqlValue] -> IO Integer
 frun o children query args =
     do sth <- newSth o children query
        res <- execute sth args
        finish sth
        return res
 
-fcommit o cl = do frun o cl "COMMIT" []
-                  begin_transaction o cl
-frollback o cl =  do frun o cl "ROLLBACK" []
-                     begin_transaction o cl
+fcommit :: Bool -> Conn -> ChildList -> IO ()
+fcommit begin o cl = do _ <- frun o cl "COMMIT" []
+                        when begin $ begin_transaction o cl
 
+frollback :: Bool -> Conn -> ChildList -> IO ()
+frollback begin o cl =  do _ <- frun o cl "ROLLBACK" []
+                           when begin $ begin_transaction o cl
+
+fgetTables :: (Convertible SqlValue a) => Conn -> ChildList -> IO [a]
 fgetTables conn children =
-    do sth <- newSth conn children "select table_name from information_schema.tables where table_schema = 'public'"
-       execute sth []
+    do sth <- newSth conn children
+              "select table_name from information_schema.tables where \
+               \table_schema != 'pg_catalog' AND table_schema != \
+               \'information_schema'"
+       _ <- execute sth []
        res1 <- fetchAllRows' sth
        let res = map fromSql $ concat res1
        return $ seq (length res) res
 
+fdescribeTable :: Conn -> ChildList -> String -> IO [(String, SqlColDesc)]
 fdescribeTable o cl table = fdescribeSchemaTable o cl Nothing table
 
 fdescribeSchemaTable :: Conn -> ChildList -> Maybe String -> String -> IO [(String, SqlColDesc)]
 fdescribeSchemaTable o cl maybeSchema table =
-    do sth <- newSth o cl 
+    do sth <- newSth o cl
               ("SELECT attname, atttypid, attlen, format_type(atttypid, atttypmod), attnotnull " ++
                "FROM pg_attribute, pg_class, pg_namespace ns " ++
                "WHERE relname = ? and attnum > 0 and attisdropped IS FALSE " ++
                (if isJust maybeSchema then "and ns.nspname = ? " else "") ++
                "and attrelid = pg_class.oid and relnamespace = ns.oid order by attnum")
        let params = toSql table : (if isJust maybeSchema then [toSql $ fromJust maybeSchema] else [])
-       execute sth params
+       _ <- execute sth params
        res <- fetchAllRows' sth
        return $ map desccol res
     where
       desccol [attname, atttypid, attlen, formattedtype, attnotnull] =
-          (fromSql attname, 
+          (fromSql attname,
            colDescForPGAttr (fromSql atttypid) (fromSql attlen) (fromSql formattedtype) (fromSql attnotnull == False))
       desccol x =
           error $ "Got unexpected result from pg_attribute: " ++ show x
-         
 
-fdisconnect conn mchildren = 
-    do closeAllChildren mchildren
-       withRawConn conn $ pqfinish
+fdisconnect :: Conn -> ChildList -> IO ()
+fdisconnect (lock, fptr) childList = do
+  closeAllChildren childList
+  modifyMVar_ lock $ \_ ->
+    finalizeForeignPtr fptr
 
-foreign import ccall unsafe "libpq-fe.h PQconnectdb"
+foreign import ccall safe "libpq-fe.h PQconnectdb"
   pqconnectdb :: CString -> IO (Ptr CConn)
 
-foreign import ccall unsafe "hdbc-postgresql-helper.h wrapobjpg"
-  wrapconn :: Ptr CConn -> Ptr WrappedCConn -> IO (Ptr WrappedCConn)
-
-foreign import ccall unsafe "libpq-fe.h PQstatus"
+foreign import ccall safe "libpq-fe.h PQstatus"
   pqstatus :: Ptr CConn -> IO #{type ConnStatusType}
 
-foreign import ccall unsafe "hdbc-postgresql-helper.h PQfinish_app"
-  pqfinish :: Ptr WrappedCConn -> IO ()
-
-foreign import ccall unsafe "hdbc-postgresql-helper.h &PQfinish_finalizer"
-  pqfinishptr :: FunPtr (Ptr WrappedCConn -> IO ())
+foreign import ccall safe "libpq-fe.h &PQfinish"
+  pqfinish :: FunPtr (Ptr CConn -> IO ())
 
-foreign import ccall unsafe "libpq-fe.h PQprotocolVersion"
+foreign import ccall safe "libpq-fe.h PQprotocolVersion"
   pqprotocolVersion :: Ptr CConn -> IO CInt
 
-foreign import ccall unsafe "libpq-fe.h PQserverVersion"
+foreign import ccall safe "libpq-fe.h PQserverVersion"
   pqserverVersion :: Ptr CConn -> IO CInt
+
+foreign import ccall safe "libpq.fe.h PQisthreadsafe"
+  pqisThreadSafe :: Ptr CConn -> IO Int
diff --git a/Database/HDBC/PostgreSQL/ConnectionImpl.hs b/Database/HDBC/PostgreSQL/ConnectionImpl.hs
--- a/Database/HDBC/PostgreSQL/ConnectionImpl.hs
+++ b/Database/HDBC/PostgreSQL/ConnectionImpl.hs
@@ -1,32 +1,15 @@
-{-
-Copyright (C) 2005-2007 John Goerzen <jgoerzen@complete.org>
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
-
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
--}
-
 module Database.HDBC.PostgreSQL.ConnectionImpl where
 
-import qualified Database.HDBC.Statement as Types
 import qualified Database.HDBC.Types as Types
 import Database.HDBC.ColTypes as ColTypes
 
 data Connection = 
     Connection {
                 disconnect :: IO (),
+                begin :: IO (),
                 commit :: IO (),
                 rollback :: IO (),
+                runRaw :: String -> IO (),
                 run :: String -> [Types.SqlValue] -> IO Integer,
                 prepare :: String -> IO Types.Statement,
                 clone :: IO Connection,
@@ -44,6 +27,7 @@
   disconnect = disconnect
   commit = commit
   rollback = rollback
+  runRaw = runRaw
   run = run
   prepare = prepare
   clone = clone
diff --git a/Database/HDBC/PostgreSQL/ErrorCodes.hs b/Database/HDBC/PostgreSQL/ErrorCodes.hs
new file mode 100644
--- /dev/null
+++ b/Database/HDBC/PostgreSQL/ErrorCodes.hs
@@ -0,0 +1,820 @@
+-- Generated from "/usr/include/postgresql/utils/errcodes.h" (PostgreSQL 8.3).
+--
+-- The following vim regexp substitutions map "errorcodes.h" to this file:
+--
+-- " remove all comments
+-- :%s/\v\/\*\_.{-}\*\/
+--
+-- " remove empty lines
+-- :%s/^\s*\n/
+--
+-- " #defines -> functions
+-- :%s/\v#define ERRCODE_(\S*)\t*/\L\1 = /
+--
+-- " expand MAKE_SQLSTATE macro
+-- :%s/\vMAKE_SQLSTATE\('(.)',\s*'(.)',\s*'(.)',\s*'(.)',\s*'(.)'\)/"\1\2\3\4\5"/
+--
+-- " aliases
+-- :%s/\vERRCODE_(\S*)/\L\1/
+--
+-- " type signatures
+-- :%s/\v^(\S*)/\r\1 :: String\r\1/
+--
+-- " to mixedCase
+-- :%s/\v_(\l)/\u\1/g
+--
+-- " got ride of additional whitespace
+-- :%s/\s+=\s+/ = /
+--
+-- " Documentation
+-- :%s/\v(\a+) :: String\n\1 \= "(.*)"/-- |Is set to @\\"\2\\"@.\r\0
+--
+-- " Documentation for aliases
+-- :%s/\v(\a+) :: String\n\1 \= (\a+)/-- |Same as '\2'.\r\0
+--
+
+module Database.HDBC.PostgreSQL.ErrorCodes where
+
+-- |Is set to @\"00000\"@.
+successfulCompletion :: String
+successfulCompletion = "00000"
+
+-- |Is set to @\"01000\"@.
+warning :: String
+warning = "01000"
+
+-- |Is set to @\"0100C\"@.
+warningDynamicResultSetsReturned :: String
+warningDynamicResultSetsReturned = "0100C"
+
+-- |Is set to @\"01008\"@.
+warningImplicitZeroBitPadding :: String
+warningImplicitZeroBitPadding = "01008"
+
+-- |Is set to @\"01003\"@.
+warningNullValueEliminatedInSetFunction :: String
+warningNullValueEliminatedInSetFunction = "01003"
+
+-- |Is set to @\"01007\"@.
+warningPrivilegeNotGranted :: String
+warningPrivilegeNotGranted = "01007"
+
+-- |Is set to @\"01006\"@.
+warningPrivilegeNotRevoked :: String
+warningPrivilegeNotRevoked = "01006"
+
+-- |Is set to @\"01004\"@.
+warningStringDataRightTruncation :: String
+warningStringDataRightTruncation = "01004"
+
+-- |Is set to @\"01P01\"@.
+warningDeprecatedFeature :: String
+warningDeprecatedFeature = "01P01"
+
+-- |Is set to @\"02000\"@.
+noData :: String
+noData = "02000"
+
+-- |Is set to @\"02001\"@.
+noAdditionalDynamicResultSetsReturned :: String
+noAdditionalDynamicResultSetsReturned = "02001"
+
+-- |Is set to @\"03000\"@.
+sqlStatementNotYetComplete :: String
+sqlStatementNotYetComplete = "03000"
+
+-- |Is set to @\"08000\"@.
+connectionException :: String
+connectionException = "08000"
+
+-- |Is set to @\"08003\"@.
+connectionDoesNotExist :: String
+connectionDoesNotExist = "08003"
+
+-- |Is set to @\"08006\"@.
+connectionFailure :: String
+connectionFailure = "08006"
+
+-- |Is set to @\"08001\"@.
+sqlclientUnableToEstablishSqlconnection :: String
+sqlclientUnableToEstablishSqlconnection = "08001"
+
+-- |Is set to @\"08004\"@.
+sqlserverRejectedEstablishmentOfSqlconnection :: String
+sqlserverRejectedEstablishmentOfSqlconnection = "08004"
+
+-- |Is set to @\"08007\"@.
+transactionResolutionUnknown :: String
+transactionResolutionUnknown = "08007"
+
+-- |Is set to @\"08P01\"@.
+protocolViolation :: String
+protocolViolation = "08P01"
+
+-- |Is set to @\"09000\"@.
+triggeredActionException :: String
+triggeredActionException = "09000"
+
+-- |Is set to @\"0A000\"@.
+featureNotSupported :: String
+featureNotSupported = "0A000"
+
+-- |Is set to @\"0B000\"@.
+invalidTransactionInitiation :: String
+invalidTransactionInitiation = "0B000"
+
+-- |Is set to @\"0F000\"@.
+locatorException :: String
+locatorException = "0F000"
+
+-- |Is set to @\"0F001\"@.
+lEInvalidSpecification :: String
+lEInvalidSpecification = "0F001"
+
+-- |Is set to @\"0L000\"@.
+invalidGrantor :: String
+invalidGrantor = "0L000"
+
+-- |Is set to @\"0LP01\"@.
+invalidGrantOperation :: String
+invalidGrantOperation = "0LP01"
+
+-- |Is set to @\"0P000\"@.
+invalidRoleSpecification :: String
+invalidRoleSpecification = "0P000"
+
+-- |Is set to @\"21000\"@.
+cardinalityViolation :: String
+cardinalityViolation = "21000"
+
+-- |Is set to @\"22000\"@.
+dataException :: String
+dataException = "22000"
+
+-- |Is set to @\"2202E\"@.
+arrayElementError :: String
+arrayElementError = "2202E"
+
+-- |Same as 'arrayElementError'.
+arraySubscriptError :: String
+arraySubscriptError = arrayElementError
+
+-- |Is set to @\"22021\"@.
+characterNotInRepertoire :: String
+characterNotInRepertoire = "22021"
+
+-- |Is set to @\"22008\"@.
+datetimeFieldOverflow :: String
+datetimeFieldOverflow = "22008"
+
+-- |Same as 'datetimeFieldOverflow'.
+datetimeValueOutOfRange :: String
+datetimeValueOutOfRange = datetimeFieldOverflow
+
+-- |Is set to @\"22012\"@.
+divisionByZero :: String
+divisionByZero = "22012"
+
+-- |Is set to @\"22005\"@.
+errorInAssignment :: String
+errorInAssignment = "22005"
+
+-- |Is set to @\"2200B\"@.
+escapeCharacterConflict :: String
+escapeCharacterConflict = "2200B"
+
+-- |Is set to @\"22022\"@.
+indicatorOverflow :: String
+indicatorOverflow = "22022"
+
+-- |Is set to @\"22015\"@.
+intervalFieldOverflow :: String
+intervalFieldOverflow = "22015"
+
+-- |Is set to @\"2201E\"@.
+invalidArgumentForLog :: String
+invalidArgumentForLog = "2201E"
+
+-- |Is set to @\"2201F\"@.
+invalidArgumentForPowerFunction :: String
+invalidArgumentForPowerFunction = "2201F"
+
+-- |Is set to @\"2201G\"@.
+invalidArgumentForWidthBucketFunction :: String
+invalidArgumentForWidthBucketFunction = "2201G"
+
+-- |Is set to @\"22018\"@.
+invalidCharacterValueForCast :: String
+invalidCharacterValueForCast = "22018"
+
+-- |Is set to @\"22007\"@.
+invalidDatetimeFormat :: String
+invalidDatetimeFormat = "22007"
+
+-- |Is set to @\"22019\"@.
+invalidEscapeCharacter :: String
+invalidEscapeCharacter = "22019"
+
+-- |Is set to @\"2200D\"@.
+invalidEscapeOctet :: String
+invalidEscapeOctet = "2200D"
+
+-- |Is set to @\"22025\"@.
+invalidEscapeSequence :: String
+invalidEscapeSequence = "22025"
+
+-- |Is set to @\"22P06\"@.
+nonstandardUseOfEscapeCharacter :: String
+nonstandardUseOfEscapeCharacter = "22P06"
+
+-- |Is set to @\"22010\"@.
+invalidIndicatorParameterValue :: String
+invalidIndicatorParameterValue = "22010"
+
+-- |Is set to @\"22020\"@.
+invalidLimitValue :: String
+invalidLimitValue = "22020"
+
+-- |Is set to @\"22023\"@.
+invalidParameterValue :: String
+invalidParameterValue = "22023"
+
+-- |Is set to @\"2201B\"@.
+invalidRegularExpression :: String
+invalidRegularExpression = "2201B"
+
+-- |Is set to @\"22009\"@.
+invalidTimeZoneDisplacementValue :: String
+invalidTimeZoneDisplacementValue = "22009"
+
+-- |Is set to @\"2200C\"@.
+invalidUseOfEscapeCharacter :: String
+invalidUseOfEscapeCharacter = "2200C"
+
+-- |Is set to @\"2200G\"@.
+mostSpecificTypeMismatch :: String
+mostSpecificTypeMismatch = "2200G"
+
+-- |Is set to @\"22004\"@.
+nullValueNotAllowed :: String
+nullValueNotAllowed = "22004"
+
+-- |Is set to @\"22002\"@.
+nullValueNoIndicatorParameter :: String
+nullValueNoIndicatorParameter = "22002"
+
+-- |Is set to @\"22003\"@.
+numericValueOutOfRange :: String
+numericValueOutOfRange = "22003"
+
+-- |Is set to @\"22026\"@.
+stringDataLengthMismatch :: String
+stringDataLengthMismatch = "22026"
+
+-- |Is set to @\"22001\"@.
+stringDataRightTruncation :: String
+stringDataRightTruncation = "22001"
+
+-- |Is set to @\"22011\"@.
+substringError :: String
+substringError = "22011"
+
+-- |Is set to @\"22027\"@.
+trimError :: String
+trimError = "22027"
+
+-- |Is set to @\"22024\"@.
+unterminatedCString :: String
+unterminatedCString = "22024"
+
+-- |Is set to @\"2200F\"@.
+zeroLengthCharacterString :: String
+zeroLengthCharacterString = "2200F"
+
+-- |Is set to @\"22P01\"@.
+floatingPointException :: String
+floatingPointException = "22P01"
+
+-- |Is set to @\"22P02\"@.
+invalidTextRepresentation :: String
+invalidTextRepresentation = "22P02"
+
+-- |Is set to @\"22P03\"@.
+invalidBinaryRepresentation :: String
+invalidBinaryRepresentation = "22P03"
+
+-- |Is set to @\"22P04\"@.
+badCopyFileFormat :: String
+badCopyFileFormat = "22P04"
+
+-- |Is set to @\"22P05\"@.
+untranslatableCharacter :: String
+untranslatableCharacter = "22P05"
+
+-- |Is set to @\"2200L\"@.
+notAnXmlDocument :: String
+notAnXmlDocument = "2200L"
+
+-- |Is set to @\"2200M\"@.
+invalidXmlDocument :: String
+invalidXmlDocument = "2200M"
+
+-- |Is set to @\"2200N\"@.
+invalidXmlContent :: String
+invalidXmlContent = "2200N"
+
+-- |Is set to @\"2200S\"@.
+invalidXmlComment :: String
+invalidXmlComment = "2200S"
+
+-- |Is set to @\"2200T\"@.
+invalidXmlProcessingInstruction :: String
+invalidXmlProcessingInstruction = "2200T"
+
+-- |Is set to @\"23000\"@.
+integrityConstraintViolation :: String
+integrityConstraintViolation = "23000"
+
+-- |Is set to @\"23001\"@.
+restrictViolation :: String
+restrictViolation = "23001"
+
+-- |Is set to @\"23502\"@.
+notNullViolation :: String
+notNullViolation = "23502"
+
+-- |Is set to @\"23503\"@.
+foreignKeyViolation :: String
+foreignKeyViolation = "23503"
+
+-- |Is set to @\"23505\"@.
+uniqueViolation :: String
+uniqueViolation = "23505"
+
+-- |Is set to @\"23514\"@.
+checkViolation :: String
+checkViolation = "23514"
+
+-- |Is set to @\"24000\"@.
+invalidCursorState :: String
+invalidCursorState = "24000"
+
+-- |Is set to @\"25000\"@.
+invalidTransactionState :: String
+invalidTransactionState = "25000"
+
+-- |Is set to @\"25001\"@.
+activeSqlTransaction :: String
+activeSqlTransaction = "25001"
+
+-- |Is set to @\"25002\"@.
+branchTransactionAlreadyActive :: String
+branchTransactionAlreadyActive = "25002"
+
+-- |Is set to @\"25008\"@.
+heldCursorRequiresSameIsolationLevel :: String
+heldCursorRequiresSameIsolationLevel = "25008"
+
+-- |Is set to @\"25003\"@.
+inappropriateAccessModeForBranchTransaction :: String
+inappropriateAccessModeForBranchTransaction = "25003"
+
+-- |Is set to @\"25004\"@.
+inappropriateIsolationLevelForBranchTransaction :: String
+inappropriateIsolationLevelForBranchTransaction = "25004"
+
+-- |Is set to @\"25005\"@.
+noActiveSqlTransactionForBranchTransaction :: String
+noActiveSqlTransactionForBranchTransaction = "25005"
+
+-- |Is set to @\"25006\"@.
+readOnlySqlTransaction :: String
+readOnlySqlTransaction = "25006"
+
+-- |Is set to @\"25007\"@.
+schemaAndDataStatementMixingNotSupported :: String
+schemaAndDataStatementMixingNotSupported = "25007"
+
+-- |Is set to @\"25P01\"@.
+noActiveSqlTransaction :: String
+noActiveSqlTransaction = "25P01"
+
+-- |Is set to @\"25P02\"@.
+inFailedSqlTransaction :: String
+inFailedSqlTransaction = "25P02"
+
+-- |Is set to @\"26000\"@.
+invalidSqlStatementName :: String
+invalidSqlStatementName = "26000"
+
+-- |Is set to @\"27000\"@.
+triggeredDataChangeViolation :: String
+triggeredDataChangeViolation = "27000"
+
+-- |Is set to @\"28000\"@.
+invalidAuthorizationSpecification :: String
+invalidAuthorizationSpecification = "28000"
+
+-- |Is set to @\"2B000\"@.
+dependentPrivilegeDescriptorsStillExist :: String
+dependentPrivilegeDescriptorsStillExist = "2B000"
+
+-- |Is set to @\"2BP01\"@.
+dependentObjectsStillExist :: String
+dependentObjectsStillExist = "2BP01"
+
+-- |Is set to @\"2D000\"@.
+invalidTransactionTermination :: String
+invalidTransactionTermination = "2D000"
+
+-- |Is set to @\"2F000\"@.
+sqlRoutineException :: String
+sqlRoutineException = "2F000"
+
+-- |Is set to @\"2F005\"@.
+sREFunctionExecutedNoReturnStatement :: String
+sREFunctionExecutedNoReturnStatement = "2F005"
+
+-- |Is set to @\"2F002\"@.
+sREModifyingSqlDataNotPermitted :: String
+sREModifyingSqlDataNotPermitted = "2F002"
+
+-- |Is set to @\"2F003\"@.
+sREProhibitedSqlStatementAttempted :: String
+sREProhibitedSqlStatementAttempted = "2F003"
+
+-- |Is set to @\"2F004\"@.
+sREReadingSqlDataNotPermitted :: String
+sREReadingSqlDataNotPermitted = "2F004"
+
+-- |Is set to @\"34000\"@.
+invalidCursorName :: String
+invalidCursorName = "34000"
+
+-- |Is set to @\"38000\"@.
+externalRoutineException :: String
+externalRoutineException = "38000"
+
+-- |Is set to @\"38001\"@.
+eREContainingSqlNotPermitted :: String
+eREContainingSqlNotPermitted = "38001"
+
+-- |Is set to @\"38002\"@.
+eREModifyingSqlDataNotPermitted :: String
+eREModifyingSqlDataNotPermitted = "38002"
+
+-- |Is set to @\"38003\"@.
+eREProhibitedSqlStatementAttempted :: String
+eREProhibitedSqlStatementAttempted = "38003"
+
+-- |Is set to @\"38004\"@.
+eREReadingSqlDataNotPermitted :: String
+eREReadingSqlDataNotPermitted = "38004"
+
+-- |Is set to @\"39000\"@.
+externalRoutineInvocationException :: String
+externalRoutineInvocationException = "39000"
+
+-- |Is set to @\"39001\"@.
+eRIEInvalidSqlstateReturned :: String
+eRIEInvalidSqlstateReturned = "39001"
+
+-- |Is set to @\"39004\"@.
+eRIENullValueNotAllowed :: String
+eRIENullValueNotAllowed = "39004"
+
+-- |Is set to @\"39P01\"@.
+eRIETriggerProtocolViolated :: String
+eRIETriggerProtocolViolated = "39P01"
+
+-- |Is set to @\"39P02\"@.
+eRIESrfProtocolViolated :: String
+eRIESrfProtocolViolated = "39P02"
+
+-- |Is set to @\"3B000\"@.
+savepointException :: String
+savepointException = "3B000"
+
+-- |Is set to @\"3B001\"@.
+sEInvalidSpecification :: String
+sEInvalidSpecification = "3B001"
+
+-- |Is set to @\"3D000\"@.
+invalidCatalogName :: String
+invalidCatalogName = "3D000"
+
+-- |Is set to @\"3F000\"@.
+invalidSchemaName :: String
+invalidSchemaName = "3F000"
+
+-- |Is set to @\"40000\"@.
+transactionRollback :: String
+transactionRollback = "40000"
+
+-- |Is set to @\"40002\"@.
+tRIntegrityConstraintViolation :: String
+tRIntegrityConstraintViolation = "40002"
+
+-- |Is set to @\"40001\"@.
+tRSerializationFailure :: String
+tRSerializationFailure = "40001"
+
+-- |Is set to @\"40003\"@.
+tRStatementCompletionUnknown :: String
+tRStatementCompletionUnknown = "40003"
+
+-- |Is set to @\"40P01\"@.
+tRDeadlockDetected :: String
+tRDeadlockDetected = "40P01"
+
+-- |Is set to @\"42000\"@.
+syntaxErrorOrAccessRuleViolation :: String
+syntaxErrorOrAccessRuleViolation = "42000"
+
+-- |Is set to @\"42601\"@.
+syntaxError :: String
+syntaxError = "42601"
+
+-- |Is set to @\"42501\"@.
+insufficientPrivilege :: String
+insufficientPrivilege = "42501"
+
+-- |Is set to @\"42846\"@.
+cannotCoerce :: String
+cannotCoerce = "42846"
+
+-- |Is set to @\"42803\"@.
+groupingError :: String
+groupingError = "42803"
+
+-- |Is set to @\"42830\"@.
+invalidForeignKey :: String
+invalidForeignKey = "42830"
+
+-- |Is set to @\"42602\"@.
+invalidName :: String
+invalidName = "42602"
+
+-- |Is set to @\"42622\"@.
+nameTooLong :: String
+nameTooLong = "42622"
+
+-- |Is set to @\"42939\"@.
+reservedName :: String
+reservedName = "42939"
+
+-- |Is set to @\"42804\"@.
+datatypeMismatch :: String
+datatypeMismatch = "42804"
+
+-- |Is set to @\"42P18\"@.
+indeterminateDatatype :: String
+indeterminateDatatype = "42P18"
+
+-- |Is set to @\"42809\"@.
+wrongObjectType :: String
+wrongObjectType = "42809"
+
+-- |Is set to @\"42703\"@.
+undefinedColumn :: String
+undefinedColumn = "42703"
+
+-- |Same as 'invalidCursorName'.
+undefinedCursor :: String
+undefinedCursor = invalidCursorName
+
+-- |Same as 'invalidCatalogName'.
+undefinedDatabase :: String
+undefinedDatabase = invalidCatalogName
+
+-- |Is set to @\"42883\"@.
+undefinedFunction :: String
+undefinedFunction = "42883"
+
+-- |Same as 'invalidSqlStatementName'.
+undefinedPstatement :: String
+undefinedPstatement = invalidSqlStatementName
+
+-- |Same as 'invalidSchemaName'.
+undefinedSchema :: String
+undefinedSchema = invalidSchemaName
+
+-- |Is set to @\"42P01\"@.
+undefinedTable :: String
+undefinedTable = "42P01"
+
+-- |Is set to @\"42P02\"@.
+undefinedParameter :: String
+undefinedParameter = "42P02"
+
+-- |Is set to @\"42704\"@.
+undefinedObject :: String
+undefinedObject = "42704"
+
+-- |Is set to @\"42701\"@.
+duplicateColumn :: String
+duplicateColumn = "42701"
+
+-- |Is set to @\"42P03\"@.
+duplicateCursor :: String
+duplicateCursor = "42P03"
+
+-- |Is set to @\"42P04\"@.
+duplicateDatabase :: String
+duplicateDatabase = "42P04"
+
+-- |Is set to @\"42723\"@.
+duplicateFunction :: String
+duplicateFunction = "42723"
+
+-- |Is set to @\"42P05\"@.
+duplicatePstatement :: String
+duplicatePstatement = "42P05"
+
+-- |Is set to @\"42P06\"@.
+duplicateSchema :: String
+duplicateSchema = "42P06"
+
+-- |Is set to @\"42P07\"@.
+duplicateTable :: String
+duplicateTable = "42P07"
+
+-- |Is set to @\"42712\"@.
+duplicateAlias :: String
+duplicateAlias = "42712"
+
+-- |Is set to @\"42710\"@.
+duplicateObject :: String
+duplicateObject = "42710"
+
+-- |Is set to @\"42702\"@.
+ambiguousColumn :: String
+ambiguousColumn = "42702"
+
+-- |Is set to @\"42725\"@.
+ambiguousFunction :: String
+ambiguousFunction = "42725"
+
+-- |Is set to @\"42P08\"@.
+ambiguousParameter :: String
+ambiguousParameter = "42P08"
+
+-- |Is set to @\"42P09\"@.
+ambiguousAlias :: String
+ambiguousAlias = "42P09"
+
+-- |Is set to @\"42P10\"@.
+invalidColumnReference :: String
+invalidColumnReference = "42P10"
+
+-- |Is set to @\"42611\"@.
+invalidColumnDefinition :: String
+invalidColumnDefinition = "42611"
+
+-- |Is set to @\"42P11\"@.
+invalidCursorDefinition :: String
+invalidCursorDefinition = "42P11"
+
+-- |Is set to @\"42P12\"@.
+invalidDatabaseDefinition :: String
+invalidDatabaseDefinition = "42P12"
+
+-- |Is set to @\"42P13\"@.
+invalidFunctionDefinition :: String
+invalidFunctionDefinition = "42P13"
+
+-- |Is set to @\"42P14\"@.
+invalidPstatementDefinition :: String
+invalidPstatementDefinition = "42P14"
+
+-- |Is set to @\"42P15\"@.
+invalidSchemaDefinition :: String
+invalidSchemaDefinition = "42P15"
+
+-- |Is set to @\"42P16\"@.
+invalidTableDefinition :: String
+invalidTableDefinition = "42P16"
+
+-- |Is set to @\"42P17\"@.
+invalidObjectDefinition :: String
+invalidObjectDefinition = "42P17"
+
+-- |Is set to @\"44000\"@.
+withCheckOptionViolation :: String
+withCheckOptionViolation = "44000"
+
+-- |Is set to @\"53000\"@.
+insufficientResources :: String
+insufficientResources = "53000"
+
+-- |Is set to @\"53100\"@.
+diskFull :: String
+diskFull = "53100"
+
+-- |Is set to @\"53200\"@.
+outOfMemory :: String
+outOfMemory = "53200"
+
+-- |Is set to @\"53300\"@.
+tooManyConnections :: String
+tooManyConnections = "53300"
+
+-- |Is set to @\"54000\"@.
+programLimitExceeded :: String
+programLimitExceeded = "54000"
+
+-- |Is set to @\"54001\"@.
+statementTooComplex :: String
+statementTooComplex = "54001"
+
+-- |Is set to @\"54011\"@.
+tooManyColumns :: String
+tooManyColumns = "54011"
+
+-- |Is set to @\"54023\"@.
+tooManyArguments :: String
+tooManyArguments = "54023"
+
+-- |Is set to @\"55000\"@.
+objectNotInPrerequisiteState :: String
+objectNotInPrerequisiteState = "55000"
+
+-- |Is set to @\"55006\"@.
+objectInUse :: String
+objectInUse = "55006"
+
+-- |Is set to @\"55P02\"@.
+cantChangeRuntimeParam :: String
+cantChangeRuntimeParam = "55P02"
+
+-- |Is set to @\"55P03\"@.
+lockNotAvailable :: String
+lockNotAvailable = "55P03"
+
+-- |Is set to @\"57000\"@.
+operatorIntervention :: String
+operatorIntervention = "57000"
+
+-- |Is set to @\"57014\"@.
+queryCanceled :: String
+queryCanceled = "57014"
+
+-- |Is set to @\"57P01\"@.
+adminShutdown :: String
+adminShutdown = "57P01"
+
+-- |Is set to @\"57P02\"@.
+crashShutdown :: String
+crashShutdown = "57P02"
+
+-- |Is set to @\"57P03\"@.
+cannotConnectNow :: String
+cannotConnectNow = "57P03"
+
+-- |Is set to @\"58030\"@.
+ioError :: String
+ioError = "58030"
+
+-- |Is set to @\"58P01\"@.
+undefinedFile :: String
+undefinedFile = "58P01"
+
+-- |Is set to @\"58P02\"@.
+duplicateFile :: String
+duplicateFile = "58P02"
+
+-- |Is set to @\"F0000\"@.
+configFileError :: String
+configFileError = "F0000"
+
+-- |Is set to @\"F0001\"@.
+lockFileExists :: String
+lockFileExists = "F0001"
+
+-- |Is set to @\"P0000\"@.
+plpgsqlError :: String
+plpgsqlError = "P0000"
+
+-- |Is set to @\"P0001\"@.
+raiseException :: String
+raiseException = "P0001"
+
+-- |Is set to @\"P0002\"@.
+noDataFound :: String
+noDataFound = "P0002"
+
+-- |Is set to @\"P0003\"@.
+tooManyRows :: String
+tooManyRows = "P0003"
+
+-- |Is set to @\"XX000\"@.
+internalError :: String
+internalError = "XX000"
+
+-- |Is set to @\"XX001\"@.
+dataCorrupted :: String
+dataCorrupted = "XX001"
+
+-- |Is set to @\"XX002\"@.
+indexCorrupted :: String
+indexCorrupted = "XX002"
diff --git a/Database/HDBC/PostgreSQL/PTypeConv.hsc b/Database/HDBC/PostgreSQL/PTypeConv.hsc
--- a/Database/HDBC/PostgreSQL/PTypeConv.hsc
+++ b/Database/HDBC/PostgreSQL/PTypeConv.hsc
@@ -1,28 +1,9 @@
 -- -*- mode: haskell; -*-
-{-
-Copyright (C) 2006 John Goerzen <jgoerzen@complete.org>
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
-
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
--}
-
 module Database.HDBC.PostgreSQL.PTypeConv where
 import Database.HDBC.ColTypes
 import Data.Word
-import Data.Int
 
-#include "pgtypes.h"
+#include "pgtypes_internal.h"
 #include <libpq-fe.h>
 
 
@@ -45,7 +26,7 @@
     where
       maybeExtractFirstParenthesizedNumber s = case extractParenthesizedInts s of n:_ -> Just n; _ -> Nothing
 
-      maybeExtractSecondParenthesizedNumber s = case extractParenthesizedInts s of n1:n2:_ -> Just n2; _ -> Nothing
+      maybeExtractSecondParenthesizedNumber s = case extractParenthesizedInts s of _:n2:_ -> Just n2; _ -> Nothing
 
       extractParenthesizedInts :: String -> [Int]
       extractParenthesizedInts s =
@@ -77,6 +58,7 @@
       #{const PG_TYPE_BPCHAR} -> SqlCharT
       #{const PG_TYPE_VARCHAR} -> SqlVarCharT
       #{const PG_TYPE_TEXT} -> SqlVarCharT
+      #{const PG_TYPE_XML} -> SqlVarCharT
       #{const PG_TYPE_BYTEA} -> SqlVarBinaryT
       #{const PG_TYPE_INT2} -> SqlSmallIntT
       #{const PG_TYPE_OID} -> SqlIntegerT
@@ -87,13 +69,17 @@
       #{const PG_TYPE_FLOAT4} -> SqlRealT
       #{const PG_TYPE_FLOAT8} -> SqlFloatT
       #{const PG_TYPE_DATE} -> SqlDateT
-      #{const PG_TYPE_ABSTIME} -> SqlTimestampT
-      #{const PG_TYPE_DATETIME} -> SqlTimestampT
+      #{const PG_TYPE_ABSTIME} -> SqlTimestampWithZoneT
+
+      #{const PG_TYPE_DATETIME} -> SqlTimestampWithZoneT
       #{const PG_TYPE_TIMESTAMP_NO_TMZONE} -> SqlTimestampT
       #{const PG_TYPE_TIMESTAMP} -> SqlTimestampT
+
       #{const PG_TYPE_TIME} -> SqlTimeT
-      #{const PG_TYPE_TIME_WITH_TMZONE} -> SqlTimeT
+      #{const PG_TYPE_TIME_WITH_TMZONE} -> SqlTimeWithZoneT
+
       #{const PG_TYPE_TINTERVAL} -> SqlIntervalT SqlIntervalMonthT -- SqlIntervalMonthT chosen arbitrarily in these two. PG allows any parts
       #{const PG_TYPE_RELTIME}   -> SqlIntervalT SqlIntervalMonthT -- of an interval (microsecond to millennium) to be specified together.
+      1186 -> SqlIntervalT SqlIntervalMonthT
       #{const PG_TYPE_BOOL} -> SqlBitT
       x -> SqlUnknownT (show x)
diff --git a/Database/HDBC/PostgreSQL/Parser.hs b/Database/HDBC/PostgreSQL/Parser.hs
--- a/Database/HDBC/PostgreSQL/Parser.hs
+++ b/Database/HDBC/PostgreSQL/Parser.hs
@@ -1,63 +1,61 @@
 {- -*- mode: haskell; -*- 
-Copyright (C) 2005 John Goerzen <jgoerzen@complete.org>
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
-
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 -}
-
 {- PostgreSQL uses $1, $2, etc. instead of ? in query strings.  So we have to
 do some basic parsing on these things to fix 'em up. -}
 
+
 module Database.HDBC.PostgreSQL.Parser where
 
 import Text.ParserCombinators.Parsec
 
+escapeseq :: GenParser Char st String
 escapeseq = (try $ string "''") <|>
             (try $ string "\\'")
 
-literal = do char '\''
+literal :: GenParser Char st [Char]
+literal = do _ <- char '\''
              s <- many (escapeseq <|> (noneOf "'" >>= (\x -> return [x])))
-             char '\''
+             _ <- char '\''
              return $ "'" ++ (concat s) ++ "'"
 
-qidentifier = do char '"'
+qidentifier :: GenParser Char st [Char]
+qidentifier = do _ <- char '"'
                  s <- many (noneOf "\"")
-                 char '"'
+                 _ <- char '"'
                  return $ "\"" ++ s ++ "\""
 
+comment :: GenParser Char st [Char]
 comment = ccomment <|> linecomment
 
-ccomment = do string "/*"
+ccomment :: GenParser Char st [Char]
+ccomment = do _ <- string "/*"
               c <- manyTill ((try ccomment) <|> 
                              (anyChar >>= (\x -> return [x])))
                    (try (string "*/"))
               return $ "/*" ++ concat c ++ "*/"
 
-linecomment = do string "--"
+linecomment :: GenParser Char st [Char]
+linecomment = do _ <- string "--"
                  c <- many (noneOf "\n")
-                 char '\n'
+                 _ <- char '\n'
                  return $ "--" ++ c ++ "\n"
 
 -- FIXME: handle pgsql dollar-quoted constants
 
-qmark = do char '?'
+qmark :: (Num st, Show st) => GenParser Char st [Char]
+qmark = do _ <- char '?'
            n <- getState
            updateState (+1)
            return $ "$" ++ show n
 
+escapedQmark :: GenParser Char st [Char]
+escapedQmark = do _ <- try (char '\\' >> char '?')
+                  return "?"
+
+statement :: (Num st, Show st) => GenParser Char st [Char]
 statement = 
-    do s <- many ((try qmark) <|>
+    do s <- many ((try escapedQmark) <|>
+                  (try qmark) <|>
                   (try comment) <|>
                   (try literal) <|>
                   (try qidentifier) <|>
@@ -65,4 +63,4 @@
        return $ concat s
 
 convertSQL :: String -> Either ParseError String
-convertSQL input = runParser statement 1 "" input
+convertSQL input = runParser statement (1::Integer) "" input
diff --git a/Database/HDBC/PostgreSQL/Statement.hsc b/Database/HDBC/PostgreSQL/Statement.hsc
--- a/Database/HDBC/PostgreSQL/Statement.hsc
+++ b/Database/HDBC/PostgreSQL/Statement.hsc
@@ -1,24 +1,5 @@
--- -*- mode: haskell; -*-
-{-# CFILES hdbc-postgresql-helper.c #-}
--- Above line for hugs
-{-
-Copyright (C) 2005 John Goerzen <jgoerzen@complete.org>
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
-
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
--}
 module Database.HDBC.PostgreSQL.Statement where
+
 import Database.HDBC.Types
 import Database.HDBC
 import Database.HDBC.PostgreSQL.Types
@@ -28,26 +9,27 @@
 import Foreign.Ptr
 import Control.Concurrent.MVar
 import Foreign.C.String
-import Foreign.Marshal
-import Foreign.Storable
 import Control.Monad
 import Data.List
 import Data.Word
-import Data.Maybe
 import Data.Ratio
-import Control.Exception
-import System.IO
-import System.Time
+import qualified Data.ByteString as B
+import qualified Data.ByteString.UTF8 as BUTF8
 import Database.HDBC.PostgreSQL.Parser(convertSQL)
 import Database.HDBC.DriverUtils
 import Database.HDBC.PostgreSQL.PTypeConv
+import Data.Time.Format
+#ifndef MIN_TIME_15
+import System.Locale
+#endif
 
+l :: Monad m => t -> m ()
 l _ = return ()
 --l m = hPutStrLn stderr ("\n" ++ m)
 
 #include <libpq-fe.h>
 
-data SState = 
+data SState =
     SState { stomv :: MVar (Maybe Stmt),
              nextrowmv :: MVar (CInt), -- -1 for no next row (empty); otherwise, next row to read.
              dbo :: Conn,
@@ -56,25 +38,26 @@
 
 -- FIXME: we currently do no prepare optimization whatsoever.
 
-newSth :: Conn -> ChildList -> String -> IO Statement               
-newSth indbo mchildren query = 
+newSth :: Conn -> ChildList -> String -> IO Statement
+newSth indbo mchildren query =
     do l "in newSth"
        newstomv <- newMVar Nothing
        newnextrowmv <- newMVar (-1)
        newcoldefmv <- newMVar []
        usequery <- case convertSQL query of
-                      Left errstr -> throwDyn $ SqlError
+                      Left errstr -> throwSqlError $ SqlError
                                       {seState = "",
                                        seNativeError = (-1),
-                                       seErrorMsg = "hdbc prepare: " ++ 
+                                       seErrorMsg = "hdbc prepare: " ++
                                                     show errstr}
                       Right converted -> return converted
        let sstate = SState {stomv = newstomv, nextrowmv = newnextrowmv,
                             dbo = indbo, squery = usequery,
                             coldefmv = newcoldefmv}
-       let retval = 
+       let retval =
                 Statement {execute = fexecute sstate,
                            executeMany = fexecutemany sstate,
+                           executeRaw = fexecuteRaw sstate,
                            finish = public_ffinish sstate,
                            fetchRow = ffetchrow sstate,
                            originalQuery = query,
@@ -83,63 +66,98 @@
        addChild mchildren retval
        return retval
 
-fgetColumnNames sstate = 
+fgetColumnNames :: SState -> IO [(String)]
+fgetColumnNames sstate =
     do c <- readMVar (coldefmv sstate)
        return (map fst c)
 
-fdescribeResult sstate = 
+fdescribeResult :: SState -> IO [(String, SqlColDesc)]
+fdescribeResult sstate =
     readMVar (coldefmv sstate)
 
 {- For now, we try to just  handle things as simply as possible.
 FIXME lots of room for improvement here (types, etc). -}
-fexecute sstate args = withConn (dbo sstate) $ \cconn ->
-                       withCString (squery sstate) $ \cquery ->
-                       withCStringArr0 args $ \cargs ->
+fexecute :: (Num a, Read a) => SState -> [SqlValue] -> IO a
+fexecute sstate args = withConnLocked (dbo sstate) $ \cconn ->
+                       B.useAsCString (BUTF8.fromString (squery sstate)) $ \cquery ->
+                       withCStringArr0 args $ \cargs -> -- wichSTringArr0 uses UTF-8
     do l "in fexecute"
        public_ffinish sstate    -- Sets nextrowmv to -1
        resptr <- pqexecParams cconn cquery
                  (genericLength args) nullPtr cargs nullPtr nullPtr 0
-       status <- pqresultStatus resptr
-       case status of
-         #{const PGRES_EMPTY_QUERY} ->
-             do l $ "PGRES_EMPTY_QUERY: " ++ squery sstate
-                pqclear_raw resptr
-                swapMVar (coldefmv sstate) []
-                return 0
-         #{const PGRES_COMMAND_OK} ->
-             do l $ "PGRES_COMMAND_OK: " ++ squery sstate
-                rowscs <- pqcmdTuples resptr
-                rows <- peekCString rowscs
-                pqclear_raw resptr
-                swapMVar (coldefmv sstate) []
-                return $ case rows of
-                                   "" -> 0
-                                   x -> read x
-         #{const PGRES_TUPLES_OK} -> 
-             do l $ "PGRES_TUPLES_OK: " ++ squery sstate
-                fgetcoldef resptr >>= swapMVar (coldefmv sstate) 
-                numrows <- pqntuples resptr
-                if numrows < 1
-                   then do pqclear_raw resptr
-                           return 0
-                   else do 
-                        wrappedptr <- withRawConn (dbo sstate) 
-                                      (\rawconn -> wrapstmt resptr rawconn)
-                        fresptr <- newForeignPtr pqclearptr wrappedptr
-                        swapMVar (nextrowmv sstate) 0
-                        swapMVar (stomv sstate) (Just fresptr)
-                        return 0
-         _ -> do l $ "PGRES ERROR: " ++ squery sstate
-                 csstatusmsg <- pqresStatus status
-                 cserrormsg <- pqresultErrorMessage resptr
-                 statusmsg <- peekCString csstatusmsg
-                 errormsg <- peekCString cserrormsg
-                 pqclear_raw resptr
-                 throwDyn $ 
-                          SqlError {seState = "",
-                                    seNativeError = fromIntegral status,
-                                    seErrorMsg = "execute: " ++ statusmsg ++
-                                                 ": " ++ errormsg}
+       handleResultStatus cconn resptr sstate =<< pqresultStatus resptr
+
+{- | Differs from fexecute in that it does not prepare its input
+   query, and the input query may contain multiple statements.  This
+   is useful for issuing DDL or DML commands. -}
+fexecuteRaw :: SState -> IO ()
+fexecuteRaw sstate =
+    withConnLocked (dbo sstate) $ \cconn ->
+        B.useAsCString (BUTF8.fromString (squery sstate)) $ \cquery ->
+            do l "in fexecute"
+               public_ffinish sstate    -- Sets nextrowmv to -1
+               resptr <- pqexec cconn cquery
+               _ <- handleResultStatus cconn resptr sstate =<< pqresultStatus resptr :: IO Int
+               return ()
+
+handleResultStatus :: (Num a, Read a) => Ptr CConn -> Ptr CStmt -> SState -> ResultStatus -> IO a
+handleResultStatus cconn resptr sstate status =
+    case status of
+      #{const PGRES_EMPTY_QUERY} ->
+          do l $ "PGRES_EMPTY_QUERY: " ++ squery sstate
+             pqclear_raw resptr
+             _ <- swapMVar (coldefmv sstate) []
+             return 0
+      #{const PGRES_COMMAND_OK} ->
+          do l $ "PGRES_COMMAND_OK: " ++ squery sstate
+             rowscs <- pqcmdTuples resptr
+             rows <- peekCString rowscs
+             pqclear_raw resptr
+             _ <- swapMVar (coldefmv sstate) []
+             return $ case rows of
+                        "" -> 0
+                        x -> read x
+      #{const PGRES_TUPLES_OK} ->
+          do l $ "PGRES_TUPLES_OK: " ++ squery sstate
+             _ <- fgetcoldef resptr >>= swapMVar (coldefmv sstate)
+             numrows <- pqntuples resptr
+             if numrows < 1 then (pqclear_raw resptr >> return 0) else
+                 do
+                   fresptr <- newForeignPtr pqclearptr resptr
+                   _ <- swapMVar (nextrowmv sstate) 0
+                   _ <- swapMVar (stomv sstate) (Just fresptr)
+                   return 0
+      _ | resptr == nullPtr -> do
+              l $ "PGRES ERROR: " ++ squery sstate
+              errormsg  <- peekCStringUTF8 =<< pqerrorMessage cconn
+              statusmsg <- peekCStringUTF8 =<< pqresStatus status
+
+              throwSqlError $ SqlError { seState = "E"
+                                       , seNativeError = fromIntegral status
+                                       , seErrorMsg = "execute: " ++ statusmsg ++
+                                                      ": " ++ errormsg}
+
+      _ -> do l $ "PGRES ERROR: " ++ squery sstate
+              errormsg  <- peekCStringUTF8 =<< pqresultErrorMessage resptr
+              statusmsg <- peekCStringUTF8 =<< pqresStatus status
+              state     <- peekCStringUTF8 =<<
+                            pqresultErrorField resptr #{const PG_DIAG_SQLSTATE}
+
+              pqclear_raw resptr
+              throwSqlError $ SqlError { seState = state
+                                       , seNativeError = fromIntegral status
+                                       , seErrorMsg = "execute: " ++ statusmsg ++
+                                                      ": " ++ errormsg}
+
+peekCStringUTF8 :: CString -> IO String
+-- Marshal a NUL terminated C string into a Haskell string, decoding it
+-- with UTF8.
+peekCStringUTF8 str
+   | str == nullPtr  = return ""
+   | otherwise       = fmap BUTF8.toString (B.packCString str)
+
+
+
 {- General algorithm: find out how many columns we have, check the type
 of each to see if it's NULL.  If it's not, fetch it as text and return that.
 -}
@@ -147,7 +165,7 @@
 ffetchrow :: SState -> IO (Maybe [SqlValue])
 ffetchrow sstate = modifyMVar (nextrowmv sstate) dofetchrow
     where dofetchrow (-1) = l "ffr -1" >> return ((-1), Nothing)
-          dofetchrow nextrow = modifyMVar (stomv sstate) $ \stmt -> 
+          dofetchrow nextrow = modifyMVar (stomv sstate) $ \stmt ->
              case stmt of
                Nothing -> l "ffr nos" >> return (stmt, ((-1), Nothing))
                Just cmstmt -> withStmt cmstmt $ \cstmt ->
@@ -161,23 +179,26 @@
                                return (Nothing, ((-1), Nothing))
                        else do l "getting stuff"
                                ncols <- pqnfields cstmt
-                               res <- mapM (getCol cstmt nextrow) 
+                               res <- mapM (getCol cstmt nextrow)
                                       [0..(ncols - 1)]
                                return (stmt, (nextrow + 1, Just res))
-          getCol p row icol = 
+          getCol p row icol =
              do isnull <- pqgetisnull p row icol
                 if isnull /= 0
                    then return SqlNull
                    else do text <- pqgetvalue p row icol
                            coltype <- liftM oidToColType $ pqftype p icol
-                           s <- peekCString text
+                           s <- B.packCString text
                            makeSqlValue coltype s
 
+
+
+fgetcoldef :: Ptr CStmt -> IO [(String, SqlColDesc)]
 fgetcoldef cstmt =
     do ncols <- pqnfields cstmt
        mapM desccol [0..(ncols - 1)]
     where desccol i =
-              do colname <- (pqfname cstmt i >>= peekCString)
+              do colname <- peekCStringUTF8 =<< pqfname cstmt i 
                  coltype <- pqftype cstmt i
                  --coloctets <- pqfsize
                  let coldef = oidToColDef coltype
@@ -186,23 +207,24 @@
 -- FIXME: needs a faster algorithm.
 fexecutemany :: SState -> [[SqlValue]] -> IO ()
 fexecutemany sstate arglist =
-    mapM_ (fexecute sstate) arglist >> return ()
+    mapM_ (fexecute sstate :: [SqlValue] -> IO Int) arglist >> return ()
 
 -- Finish and change state
-public_ffinish sstate = 
+public_ffinish :: SState -> IO ()
+public_ffinish sstate =
     do l "public_ffinish"
-       swapMVar (nextrowmv sstate) (-1)
+       _ <- swapMVar (nextrowmv sstate) (-1)
        modifyMVar_ (stomv sstate) worker
     where worker Nothing = return Nothing
           worker (Just sth) = ffinish sth >> return Nothing
 
 ffinish :: Stmt -> IO ()
-ffinish p = withRawStmt p $ pqclear
+ffinish _ = pure ()
 
 foreign import ccall unsafe "libpq-fe.h PQresultStatus"
   pqresultStatus :: (Ptr CStmt) -> IO #{type ExecStatusType}
 
-foreign import ccall unsafe "libpq-fe.h PQexecParams"
+foreign import ccall safe "libpq-fe.h PQexecParams"
   pqexecParams :: (Ptr CConn) -> CString -> CInt ->
                   (Ptr #{type Oid}) ->
                   (Ptr CString) ->
@@ -211,18 +233,15 @@
                   CInt ->
                   IO (Ptr CStmt)
 
-foreign import ccall unsafe "hdbc-postgresql-helper.h PQclear_app"
-  pqclear :: Ptr WrappedCStmt -> IO ()
+foreign import ccall safe "libpq-fe.h PQexec"
+  pqexec :: (Ptr CConn) -> CString -> IO (Ptr CStmt)
 
-foreign import ccall unsafe "hdbc-postgresql-helper.h &PQclear_finalizer"
-  pqclearptr :: FunPtr (Ptr WrappedCStmt -> IO ())
+foreign import ccall unsafe "libpq-fe.h &PQclear"
+  pqclearptr :: FunPtr (Ptr CStmt -> IO ())
 
 foreign import ccall unsafe "libpq-fe.h PQclear"
   pqclear_raw :: Ptr CStmt -> IO ()
 
-foreign import ccall unsafe "hdbc-postgresql-helper.h wrapobjpg"
-  wrapstmt :: Ptr CStmt -> Ptr WrappedCConn -> IO (Ptr WrappedCStmt)
-
 foreign import ccall unsafe "libpq-fe.h PQcmdTuples"
   pqcmdTuples :: Ptr CStmt -> IO CString
 foreign import ccall unsafe "libpq-fe.h PQresStatus"
@@ -231,6 +250,9 @@
 foreign import ccall unsafe "libpq-fe.h PQresultErrorMessage"
   pqresultErrorMessage :: (Ptr CStmt) -> IO CString
 
+foreign import ccall unsafe "libpq-fe.h PQresultErrorField"
+  pqresultErrorField :: (Ptr CStmt) -> CInt -> IO CString
+
 foreign import ccall unsafe "libpq-fe.h PQntuples"
   pqntuples :: Ptr CStmt -> IO CInt
 
@@ -249,23 +271,22 @@
 foreign import ccall unsafe "libpq-fe.h PQftype"
   pqftype :: Ptr CStmt -> CInt -> IO #{type Oid}
 
-
-
 -- SqlValue construction function and helpers
 
 -- Make a SqlValue for the passed column type and string value, where it is assumed that the value represented is not the Sql null value.
 -- The IO Monad is required only to obtain the local timezone for interpreting date/time values without an explicit timezone.
-makeSqlValue :: SqlTypeId -> String -> IO SqlValue
-makeSqlValue sqltypeid strval =
-
-    case sqltypeid of 
+makeSqlValue :: SqlTypeId -> B.ByteString -> IO SqlValue
+makeSqlValue sqltypeid bstrval =
+    let strval = BUTF8.toString bstrval
+    in
+    case sqltypeid of
 
       tid | tid == SqlCharT        ||
             tid == SqlVarCharT     ||
             tid == SqlLongVarCharT ||
             tid == SqlWCharT       ||
             tid == SqlWVarCharT    ||
-            tid == SqlWLongVarCharT  -> return $ SqlString strval
+            tid == SqlWLongVarCharT  -> return $ SqlByteString bstrval
 
       tid | tid == SqlDecimalT ||
             tid == SqlNumericT   -> return $ SqlRational (makeRationalFromDecimal strval)
@@ -279,8 +300,8 @@
       tid | tid == SqlRealT   ||
             tid == SqlFloatT  ||
             tid == SqlDoubleT   -> return $ SqlDouble (read strval)
-      
-      SqlBitT -> return $ case strval of 
+
+      SqlBitT -> return $ case strval of
                    't':_ -> SqlBool True
                    'f':_ -> SqlBool False
                    'T':_ -> SqlBool True -- the rest of these are here "just in case", since they are legal as input
@@ -288,144 +309,75 @@
                    'Y':_ -> SqlBool True
                    "1"   -> SqlBool True
                    _     -> SqlBool False
-      
+
       -- Dates and Date/Times
-      tid | tid == SqlDateT        ||
-            tid == SqlTimestampT   ||
-            tid == SqlUTCDateTimeT   ->
-                do
-                  clockTime <- clockTimeFromISODateAndMaybeTime strval
-                             
-                  case clockTime of TOD epochSecs picos -> return $ SqlEpochTime epochSecs
+      tid | tid == SqlDateT -> return $ SqlLocalDate (fromSql (toSql strval))
+      tid | tid == SqlTimestampWithZoneT -> return $ SqlZonedTime (fromSql (toSql (fixString strval)))
 
+          -- SqlUTCDateTimeT not actually generated by PostgreSQL
 
+      tid | tid == SqlTimestampT   ||
+            tid == SqlUTCDateTimeT   -> return $ SqlLocalTime (fromSql (toSql strval))
+
       -- Times without dates
-      tid | tid == SqlTimeT    || 
-            tid == SqlUTCTimeT   -> return $ SqlTimeDiff $ secsTimeDiffFromISOTime strval
-      
-      -- TODO: There's no proper way to map intervals as understood by postgres currently so we resort to SqlString. 
-      -- E.g. a "1 month" interval is not a specific span of time that could be converted to a SqlTimeDiff.
-      -- A new SqlValue constructor would be needed (wrapping System.Time.TimeDiff) to really handle intervals properly.
-      SqlIntervalT si -> return $ SqlString strval
-      
-      -- TODO: For now we just map the binary types to SqlStrings. New SqlValue constructors are needed to handle these.
+      tid | tid == SqlTimeT    ||
+            tid == SqlUTCTimeT   -> return $ SqlLocalTimeOfDay (fromSql (toSql strval))
+
+      tid | tid == SqlTimeWithZoneT ->
+              (let (a, b) = case (parseTime' defaultTimeLocale "%T%Q %z" timestr,
+                                  parseTime' defaultTimeLocale "%T%Q %z" timestr) of
+                                (Just x, Just y) -> (x, y)
+                                x -> error $ "PostgreSQL Statement.hsc: Couldn't parse " ++ strval ++ " as SqlZonedLocalTimeOfDay: " ++ show x
+                   timestr = fixString strval
+               in return $ SqlZonedLocalTimeOfDay a b)
+
+      SqlIntervalT _ -> return $ SqlDiffTime $ fromRational $
+                         case split ':' strval of
+                           [h, m, s] -> toRational (((read h)::Integer) * 60 * 60 +
+                                                    ((read m)::Integer) * 60) +
+                                        toRational ((read s)::Double)
+                           _ -> error $ "PostgreSQL Statement.hsc: Couldn't parse interval: " ++ strval
+
+      -- TODO: For now we just map the binary types to SqlByteStrings. New SqlValue constructors are needed to handle these.
       tid | tid == SqlBinaryT        ||
-            tid == SqlVarBinaryT     || 
-            tid == SqlLongVarBinaryT    -> return $ SqlString strval
+            tid == SqlVarBinaryT     ||
+            tid == SqlLongVarBinaryT    -> return $ SqlByteString bstrval
 
-      SqlGUIDT -> return $ SqlString strval
+      SqlGUIDT -> return $ SqlByteString bstrval
 
-      SqlUnknownT s -> return $ SqlString strval
+      SqlUnknownT _ -> return $ SqlByteString bstrval
+      _ -> error $ "PostgreSQL Statement.hsc: unknown typeid: " ++ show sqltypeid
 
+-- Convert "15:33:01.536+00" to "15:33:01.536 +0000"
+fixString :: String -> String
+fixString s =
+    let (strbase, zone) = splitAt (length s - 3) s
+    in
+      if (head zone) == '-' || (head zone) == '+'
+         then strbase ++ " " ++ zone ++ "00"
+         else -- It wasn't in the expected format; don't touch.
+              s
 
+
 -- Make a rational number from a decimal string representation of the number.
 makeRationalFromDecimal :: String -> Rational
-makeRationalFromDecimal s = 
+makeRationalFromDecimal s =
     case elemIndex '.' s of
       Nothing -> toRational ((read s)::Integer)
-      Just dotix -> 
+      Just dotix ->
         let (nstr,'.':dstr) = splitAt dotix s
             num = (read $ nstr ++ dstr)::Integer
-            den = 10^(genericLength dstr) :: Integer
+            den = 10^((genericLength dstr) :: Integer)
         in
           num % den
 
-
--- Creates a ClockTime from an ISO-8601 representation of a date or date/time with optional numeric timezone, as output by Postgres.
--- The IO monad is required because local timezone information may need to be fetched if not provided in the input string.
-clockTimeFromISODateAndMaybeTime :: String -> IO ClockTime
-clockTimeFromISODateAndMaybeTime datestr =
-    let
-        (y, '-':month_etc) = head $ reads datestr
-        (mo, '-':day_etc) = head $ reads month_etc
-        (d, maybeTime) = head $ reads day_etc
-        hourParses = reads maybeTime
-        (h, min_etc) = if not (null hourParses) then head hourParses else (0,"")
-        (min, sec_etc) = if not (null $ drop 1 min_etc) then head $ reads (drop 1 min_etc) else (0,"")
-        (sec, maybeTZ) = if not (null $ drop 1 sec_etc) then head $ reads (drop 1 sec_etc) else (0,"")
-        tzParses = reads maybeTZ
-    in
-      do
-        tzoff <-  if not $ null tzParses then return $ 3600 * (fst $ head $ tzParses) else getLocalTimeZoneOffsetSecsForDateTime y mo d h min sec
-
-        if null hourParses 
-          then 
-            return $ toClockTime $ makeCalendarTimeForDate y mo d tzoff
-          else
-            return $ toClockTime $ makeCalendarTimeForDateTime y mo d h min sec tzoff
-
-    where
-      makeCalendarTimeForDate :: Int -> Int -> Int -> Int -> CalendarTime
-      makeCalendarTimeForDate year mon day tzoff =
-          CalendarTime { ctYear = year, ctMonth = makeMonth mon, ctDay = day, 
-                         ctHour = 0, ctMin = 0, ctSec = 0, ctPicosec = 0, 
-                         ctWDay = Sunday, ctYDay = 0, -- bogus but ignored when converting to ClockTime according to the docs in System.Time
-                         ctTZName = "",
-                         ctTZ = tzoff,
-                         ctIsDST = False -- bogus but ignored when converting to ClockTime
-                       }
-
-      makeCalendarTimeForDateTime :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> CalendarTime
-      makeCalendarTimeForDateTime year mon day hour min sec tzoff =
-          CalendarTime { ctYear = year, ctMonth = makeMonth mon, ctDay = day, ctHour = hour, ctMin = min, ctSec = sec,
-                         ctPicosec = 0, 
-                         ctWDay = Sunday, ctYDay = 0, -- bogus but ignored when converting to ClockTime
-                         ctTZName = "",
-                         ctTZ = tzoff,
-                         ctIsDST = False -- bogus but ignored when converting to ClockTime
-                       }
-
-      -- Convert 1->Jan, 2->Feb etc as commonly done on planet Earth (what's with the Month enum instance in System.Time ?)
-      makeMonth :: Int -> Month
-      makeMonth monNum = toEnum (monNum - 1)
-
-
-      getLocalTimeZoneOffsetSecsForDateTime :: Int -> Int -> Int -> Int -> Int -> Int -> IO Int 
-      getLocalTimeZoneOffsetSecsForDateTime y mo d h min s =
-          do
-            -- Convert nominal day and time at GMT to our location to get first guess of our tz offset at required date and time
-            approxLocalCalTime <- toLocalCalTime (makeCalendarTimeForDateTime y mo d h min s 0)
-      
-            -- First guess of the proper timezon offset for this date and time in our location.
-            let firstGuess = makeCalendarTimeForDateTime y mo d h min s (ctTZ approxLocalCalTime)
-      
-            -- Allow up to 6 hours for date/time dependent timezone offset adjustments (Usually should be 0,1, or -1 depending on daylight savings time).
-            let adjustments = map (3600*) $ [0,-1,1] ++ [2..6] ++  [-2,-3..(-6)]
-
-            let adjustedCalTimes = map (\adj -> firstGuess { ctTZ = ctTZ firstGuess + adj }) adjustments
-      
-            successList <- mapM isFixedPointUnderConversionToLocalTime adjustedCalTimes
-
-            case elemIndex True successList of
-              Nothing -> error $ "Could not find proper timezone for date: " ++ 
-                                 show y ++ "-" ++ show mo ++ "-" ++ show d ++ " " ++ show h ++ ":" ++ show min ++ ":" ++ show s
-              Just ix -> return (ctTZ $ adjustedCalTimes!!ix)
-          where
-            toLocalCalTime :: CalendarTime -> IO CalendarTime
-            toLocalCalTime calTime = toCalendarTime $ toClockTime calTime
-      
-            isFixedPointUnderConversionToLocalTime :: CalendarTime -> IO Bool
-            isFixedPointUnderConversionToLocalTime calTime =
-                do
-                  calTime' <- toLocalCalTime calTime
-                  return $ eqParts calTime calTime'
-
-            eqParts :: CalendarTime -> CalendarTime -> Bool
-            eqParts calTime1 calTime2 = ctHour calTime1 == ctHour calTime2 &&
-                                        ctMin calTime1 == ctMin calTime2 &&
-                                        ctSec calTime1 == ctSec calTime2 &&
-                                        ctDay calTime1 == ctDay calTime2 &&
-                                        ctMonth calTime1 == ctMonth calTime2 &&
-                                        ctYear calTime1 == ctYear calTime2
-
-
+split :: Char -> String -> [String]
+split delim inp =
+    lines . map (\x -> if x == delim then '\n' else x) $ inp
 
--- Time values (without dates) are represented as a seconds count
-secsTimeDiffFromISOTime :: String -> Integer
-secsTimeDiffFromISOTime timestr =
-    let
-        (h, min_etc) = head $ reads timestr
-        (min, sec_etc) = if null min_etc || min_etc == ":" then (0,":0") else head $ reads (tail  min_etc)
-        (sec, _) = if null sec_etc || sec_etc == ":" then (0,"") else head $ reads (tail sec_etc)
-    in
-      h * 3600 + 60 * min + sec
+parseTime' :: ParseTime t => TimeLocale -> String -> String -> Maybe t
+#if MIN_TIME_15
+parseTime' = parseTimeM True
+#else
+parseTime' = parseTime
+#endif
diff --git a/Database/HDBC/PostgreSQL/Types.hs b/Database/HDBC/PostgreSQL/Types.hs
--- a/Database/HDBC/PostgreSQL/Types.hs
+++ b/Database/HDBC/PostgreSQL/Types.hs
@@ -1,14 +1,15 @@
 module Database.HDBC.PostgreSQL.Types
 where
 
-import Foreign.ForeignPtr
 import Foreign
+import Control.Concurrent.MVar
 
+type ConnLock = MVar ()
+
 data CConn = CConn
-type WrappedCConn = Ptr CConn
-type Conn = ForeignPtr WrappedCConn
+type Conn = (ConnLock, ForeignPtr CConn)
 
 data CStmt = CStmt
-type WrappedCStmt = Ptr CStmt
-type Stmt = ForeignPtr WrappedCStmt
+type Stmt = ForeignPtr CStmt
+type ResultStatus = Word32
 
diff --git a/Database/HDBC/PostgreSQL/Utils.hsc b/Database/HDBC/PostgreSQL/Utils.hsc
--- a/Database/HDBC/PostgreSQL/Utils.hsc
+++ b/Database/HDBC/PostgreSQL/Utils.hsc
@@ -1,43 +1,35 @@
-{- -*- mode: haskell; -*- 
-Copyright (C) 2005 John Goerzen <jgoerzen@complete.org>
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Lesser General Public
-    License as published by the Free Software Foundation; either
-    version 2.1 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Lesser General Public License for more details.
-
-    You should have received a copy of the GNU Lesser General Public
-    License along with this library; if not, write to the Free Software
-    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
--}
-
 module Database.HDBC.PostgreSQL.Utils where
+
 import Foreign.C.String
 import Foreign.ForeignPtr
 import Foreign.Ptr
+import Database.HDBC(throwSqlError)
 import Database.HDBC.Types
 import Database.HDBC.PostgreSQL.Types
+import Control.Concurrent.MVar
 import Foreign.C.Types
 import Control.Exception
 import Foreign.Storable
 import Foreign.Marshal.Array
 import Foreign.Marshal.Alloc
+import Foreign.Marshal.Utils
 import Data.Word
-
-#include "hdbc-postgresql-helper.h"
+import qualified Data.ByteString.UTF8 as BUTF8
+import qualified Data.ByteString as B
+import qualified Data.ByteString.Char8 as BCHAR8
+#ifndef __HUGS__
+-- Hugs includes this in Data.ByteString
+import qualified Data.ByteString.Unsafe as B
+#endif
 
 raiseError :: String -> Word32 -> (Ptr CConn) -> IO a
 raiseError msg code cconn =
     do rc <- pqerrorMessage cconn
-       str <- peekCString rc
-       throwDyn $ SqlError {seState = "",
-                            seNativeError = fromIntegral code,
-                            seErrorMsg = msg ++ ": " ++ str}
+       bs <- B.packCString rc
+       let str = BUTF8.toString bs
+       throwSqlError $ SqlError {seState = "",
+                                 seNativeError = fromIntegral code,
+                                 seErrorMsg = msg ++ ": " ++ str}
 
 {- This is a little hairy.
 
@@ -51,26 +43,48 @@
 Ditto for statements. -}
 
 withConn :: Conn -> (Ptr CConn -> IO b) -> IO b
-withConn = genericUnwrap
+withConn (_lock,conn) = withForeignPtr conn
 
-withRawConn :: Conn -> (Ptr WrappedCConn -> IO b) -> IO b
-withRawConn = withForeignPtr
+-- Perform the associated action with the connection lock held.
+-- Care must be taken with the use of this as it is *not* re-entrant.  Calling it
+-- a second time in the same thread will cause dead-lock.
+-- (A better approach would be to use RLock from concurrent-extra)
+withConnLocked :: Conn -> (Ptr CConn -> IO b) -> IO b
+withConnLocked c@(lock,_) a = withConn c (\cconn -> withMVar lock (\_ -> a cconn))
 
+withRawConn :: Conn -> (Ptr CConn -> IO b) -> IO b
+withRawConn (_lock,conn) = withForeignPtr conn
+
 withStmt :: Stmt -> (Ptr CStmt -> IO b) -> IO b
-withStmt = genericUnwrap
+withStmt = withForeignPtr
 
-withRawStmt :: Stmt -> (Ptr WrappedCStmt -> IO b) -> IO b
+withRawStmt :: Stmt -> (Ptr CStmt -> IO b) -> IO b
 withRawStmt = withForeignPtr
 
 withCStringArr0 :: [SqlValue] -> (Ptr CString -> IO a) -> IO a
 withCStringArr0 inp action = withAnyArr0 convfunc freefunc inp action
     where convfunc SqlNull = return nullPtr
-          convfunc x = newCString (fromSql x)
+{-
+          convfunc y@(SqlZonedTime _) = convfunc (SqlString $
+                                                "TIMESTAMP WITH TIME ZONE '" ++
+                                                fromSql y ++ "'")
+-}
+          convfunc y@(SqlUTCTime _) = convfunc (SqlZonedTime (fromSql y))
+          convfunc y@(SqlEpochTime _) = convfunc (SqlZonedTime (fromSql y))
+          convfunc (SqlByteString x) = cstrUtf8BString (cleanUpBSNulls x)
+          convfunc x = cstrUtf8BString (fromSql x)
           freefunc x =
               if x == nullPtr
                  then return ()
                  else free x
 
+cleanUpBSNulls :: B.ByteString -> B.ByteString
+cleanUpBSNulls bs | 0 `B.notElem` bs = bs
+                  | otherwise = B.concatMap convfunc bs
+  where convfunc 0 = bsForNull
+        convfunc x = B.singleton x
+        bsForNull = BCHAR8.pack "\\000"
+
 withAnyArr0 :: (a -> IO (Ptr b)) -- ^ Function that transforms input data into pointer
             -> (Ptr b -> IO ())  -- ^ Function that frees generated data
             -> [a]               -- ^ List of input data
@@ -81,13 +95,16 @@
             (\clist -> mapM_ freeact clist)
             (\clist -> withArray0 nullPtr clist action)
 
+cstrUtf8BString :: B.ByteString -> IO CString
+cstrUtf8BString bs = do
+    B.unsafeUseAsCStringLen bs $ \(s,len) -> do
+        res <- mallocBytes (len+1)
+        -- copy in
+        copyBytes res s len
+        -- null terminate
+        poke (plusPtr res len) (0::CChar)
+        -- return ptr
+        return res
 
-genericUnwrap :: ForeignPtr (Ptr a) -> (Ptr a -> IO b) -> IO b
-genericUnwrap fptr action = withForeignPtr fptr (\structptr ->
-    do objptr <- #{peek finalizeonce, encapobj} structptr
-       action objptr
-                                                )
-          
 foreign import ccall unsafe "libpq-fe.h PQerrorMessage"
   pqerrorMessage :: Ptr CConn -> IO CString
-
diff --git a/HDBC-postgresql.buildinfo.in b/HDBC-postgresql.buildinfo.in
deleted file mode 100644
--- a/HDBC-postgresql.buildinfo.in
+++ /dev/null
@@ -1,2 +0,0 @@
-extra-lib-dirs: @PGLIBDIR@
-include-dirs: @PGINCDIR@
diff --git a/HDBC-postgresql.cabal b/HDBC-postgresql.cabal
--- a/HDBC-postgresql.cabal
+++ b/HDBC-postgresql.cabal
@@ -1,23 +1,36 @@
 Name: HDBC-postgresql
-Version: 1.1.6.0
-License: LGPL
-Maintainer: John Goerzen <jgoerzen@complete.org>
+Version: 2.5.0.2
+License: BSD3
+Maintainer: Nicolas Wu <nicolas.wu@gmail.com>, David Johnson <code@dmj.io>
 Author: John Goerzen
-Copyright: Copyright (c) 2005-2008 John Goerzen
-license-file: COPYRIGHT
-extra-source-files: COPYING, hdbc-postgresql-helper.h, pgtypes.h, HDBC-postgresql.buildinfo.in, configure.ac, configure
-extra-tmp-files: config.log, config.status, autom4te.cache, HDBC-postgresql.buildinfo
-homepage: http://software.complete.org/hdbc-postgres
+Copyright: Copyright (c) 2005-2011 John Goerzen
+license-file: LICENSE
+extra-source-files: LICENSE
+                    pgtypes_internal.h
+                    Makefile
+                    README.txt
+                    testsrc/TestTime.hs
+                    CHANGELOG.md
+homepage: http://github.com/hdbc/hdbc-postgresql
 Category: Database
 synopsis: PostgreSQL driver for HDBC
 Description: This package provides a PostgreSQL driver for HDBC
 Stability: Stable
 
 Build-Type: Custom
-Cabal-Version: >=1.2
+Cabal-Version: >=1.10
 
+custom-setup
+  setup-depends: Cabal >= 1.8 && < 3.17, base < 5
+
 Flag splitBase
   description: Choose the new smaller, split-up package.
+Flag buildtests
+  description: Build the executable to run unit tests
+  default: False
+Flag minTime15
+  description: Use time 1.5 or higher.
+  default: True
 
 Library
   Exposed-Modules: Database.HDBC.PostgreSQL
@@ -27,15 +40,57 @@
     Database.HDBC.PostgreSQL.Types,
     Database.HDBC.PostgreSQL.Utils,
     Database.HDBC.PostgreSQL.Parser,
-    Database.HDBC.PostgreSQL.PTypeConv
-  --Extensions: ExistentialQuantification, AllowOverlappingInstances,
-  --    AllowUndecidableInstances, CPP
-  Extensions: ExistentialQuantification, ForeignFunctionInterface
-  Build-Depends: base, mtl, HDBC>=1.1.0, parsec
-  if flag(splitBase)
-    Build-Depends: base >= 3 && < 4, old-time
+    Database.HDBC.PostgreSQL.PTypeConv,
+    Database.HDBC.PostgreSQL.ErrorCodes
+  Build-Depends: base >= 3 && < 5, mtl, HDBC>=2.2.0, parsec, utf8-string,
+                 bytestring, old-time, convertible
+  if flag(minTime15)
+    Build-Depends: time >= 1.5 && < 1.17
+    CPP-Options: -DMIN_TIME_15
   else
-    Build-Depends: base < 3
+    Build-Depends: time < 1.5, old-locale
+  if impl(ghc >= 6.9)
+    Build-Depends: base >= 4
   Extra-Libraries: pq
-  C-Sources: hdbc-postgresql-helper.c
   Include-Dirs: .
+  GHC-Options: -O2 -Wall
+  Default-Language: Haskell2010
+
+Executable runtests
+   if flag(buildtests)
+      Buildable: True
+      Build-Depends: HUnit, QuickCheck, containers,
+                     convertible, parsec, utf8-string,
+                     bytestring, old-time, base >= 4.6 && < 5.0, HDBC>=2.2.6
+      if flag(minTime15)
+        Build-Depends: time >= 1.5 && < 1.17
+        CPP-Options: -DMIN_TIME_15
+      else
+        Build-Depends: time < 1.5, old-locale
+   else
+      Buildable: False
+   Main-Is: runtests.hs
+   Other-Modules: Database.HDBC.PostgreSQL.Connection,
+                  Database.HDBC.PostgreSQL.ConnectionImpl,
+                  Database.HDBC.PostgreSQL.Statement,
+                  Database.HDBC.PostgreSQL.Types,
+                  Database.HDBC.PostgreSQL.Utils,
+                  Database.HDBC.PostgreSQL.Parser,
+                  Database.HDBC.PostgreSQL.PTypeConv,
+                  Database.HDBC.PostgreSQL.ErrorCodes,
+                  SpecificDB,
+                  SpecificDBTests,
+                  TestMisc,
+                  TestSbasics,
+                  TestUtils,
+                  Testbasics,
+                  Tests
+   include-dirs: .
+   Extra-Libraries: pq
+   Hs-Source-Dirs: ., testsrc
+   GHC-Options: -O2 -threaded
+   Default-Language: Haskell2010
+
+source-repository head
+  type:     git
+  location: https://github.com/hdbc/hdbc-postgresql.git
diff --git a/LICENSE b/LICENSE
new file mode 100644
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2005-2011 John Goerzen
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+  list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice, this
+  list of conditions and the following disclaimer in the documentation and/or
+  other materials provided with the distribution.
+
+* Neither the name of John Goerzen nor the names of its
+  contributors may be used to endorse or promote products derived from this
+  software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/Makefile b/Makefile
new file mode 100644
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,36 @@
+all: setup
+	@echo "Please use Cabal to build this package; not make."
+	./setup configure
+	./setup build
+
+setup: Setup.hs
+	ghc --make -package Cabal -o setup Setup.hs
+
+install: setup
+	./setup install
+
+clean:
+	-runghc Setup.hs clean
+	-rm -rf html `find . -name "*.o"` `find . -name "*.hi" | grep -v debian` \
+		`find . -name "*~" | grep -v debian` *.a setup dist testsrc/runtests \
+		local-pkg doctmp
+	-rm -rf testtmp/* testtmp*
+
+.PHONY: test
+test: test-ghc test-hugs
+	@echo ""
+	@echo "All tests pass."
+
+test-hugs: setup
+	@echo " ****** Running hugs tests"
+	./setup configure -f buildtests --hugs --extra-include-dirs=/usr/lib/hugs/include
+	./setup build
+	runhugs -98 +o -P$(PWD)/dist/scratch:$(PWD)/dist/scratch/programs/runtests: \
+		dist/scratch/programs/runtests/Main.hs
+
+test-ghc: setup
+	@echo " ****** Building GHC tests"
+	./setup configure -f buildtests
+	./setup build
+	@echo " ****** Running GHC tests"
+	./dist/build/runtests/runtests
diff --git a/README.txt b/README.txt
new file mode 100644
--- /dev/null
+++ b/README.txt
@@ -0,0 +1,21 @@
+Welcome to HDBC, Haskell Database Connectivity.
+
+This package provides a database backend driver for PostgreSQL.
+
+Please see HDBC itself for documentation on use.
+
+This package provides one function in module Database.HDBC.PostgreSQL:
+
+{- | Connect to a PostgreSQL server.
+
+See <http://www.postgresql.org/docs/8.1/static/libpq.html#LIBPQ-CONNECT> for the meaning
+of the connection string. -}
+connectPostgreSQL :: String -> IO Connection
+
+An example would be:
+dbh <- connectPostgreSQL "host=localhost dbname=testdb user=foo"
+
+DIFFERENCES FROM HDBC STANDARD
+------------------------------
+
+None known at this time.
diff --git a/Setup.hs b/Setup.hs
new file mode 100644
--- /dev/null
+++ b/Setup.hs
@@ -0,0 +1,77 @@
+#!/usr/bin/env runhaskell
+{-# LANGUAGE CPP, MultiParamTypeClasses, FlexibleInstances #-}
+
+import Distribution.Simple
+import Distribution.PackageDescription
+import Distribution.Version
+
+import Distribution.Simple.LocalBuildInfo
+import Distribution.Simple.Program
+import Distribution.Verbosity
+#if MIN_VERSION_Cabal(3,14,0)
+import Distribution.Utils.Path
+#endif
+
+import Data.Char (isSpace)
+import Data.List (dropWhile,reverse)
+import Data.String (fromString)
+
+import Control.Monad
+
+main = defaultMainWithHooks simpleUserHooks {
+  hookedPrograms = [pgconfigProgram],
+
+  confHook = \pkg flags -> do
+    lbi <- confHook simpleUserHooks pkg flags
+    bi <- psqlBuildInfo lbi
+    
+    return lbi {
+      localPkgDescr = updatePackageDescription
+                        (Just bi, [(fromString "runtests", bi)]) (localPkgDescr lbi)
+    } 
+}
+
+-- 'ConstOrId' is a @Cabal-1.16@ vs @Cabal-1.18@ compatibility hack,
+-- 'programFindLocation' has a new (unused in this case)
+-- parameter. 'ConstOrId' adds this parameter when types say it is
+-- mandatory.
+class FindProgramLocation a b where
+    constOrId :: a -> b
+
+instance FindProgramLocation (IO (Maybe FilePath)) (IO (Maybe FilePath)) where
+    constOrId = id
+
+instance FindProgramLocation (IO (Maybe FilePath)) (ProgramSearchPath -> IO (Maybe FilePath)) where
+    constOrId = const
+
+instance FindProgramLocation (IO (Maybe FilePath)) (ProgramSearchPath -> IO (Maybe (FilePath, [FilePath]))) where
+    constOrId x = liftM (fmap (\x -> (x, []))) . const x
+
+pgconfigProgram = (simpleProgram "pgconfig or pg_config") {
+    programFindLocation = \verbosity searchPath -> do
+      pgconfig  <- findProgramOnSearchPath verbosity searchPath "pgconfig"
+      pg_config <- findProgramOnSearchPath verbosity searchPath "pg_config"
+      return (pgconfig `mplus` pg_config)
+  }
+
+psqlBuildInfo :: LocalBuildInfo -> IO BuildInfo
+psqlBuildInfo lbi = do
+  (pgconfigProg, _) <- requireProgram verbosity
+                         pgconfigProgram (withPrograms lbi)
+  let pgconfig = getProgramOutput verbosity pgconfigProg
+
+  incDir <- pgconfig ["--includedir"]
+  libDir <- pgconfig ["--libdir"]
+
+  return emptyBuildInfo {
+    extraLibDirs = [toPath $ strip libDir],
+    includeDirs  = [toPath $ strip incDir]
+  }
+  where
+#if MIN_VERSION_Cabal(3,14,0)
+    toPath = makeSymbolicPath
+#else
+    toPath = id
+#endif
+    verbosity = normal -- honestly, this is a hack
+    strip x = dropWhile isSpace $ reverse $ dropWhile isSpace $ reverse x
diff --git a/Setup.lhs b/Setup.lhs
deleted file mode 100644
--- a/Setup.lhs
+++ /dev/null
@@ -1,8 +0,0 @@
-#!/usr/bin/env runhaskell
-
-\begin{code}
-
-import Distribution.Simple
-main = defaultMainWithHooks defaultUserHooks
-
-\end{code}
diff --git a/configure b/configure
deleted file mode 100644
--- a/configure
+++ /dev/null
@@ -1,2683 +0,0 @@
-#! /bin/sh
-# Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.61 for HDBC-postgresql package 1.1.
-#
-# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
-# 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
-# This configure script is free software; the Free Software Foundation
-# gives unlimited permission to copy, distribute and modify it.
-## --------------------- ##
-## M4sh Initialization.  ##
-## --------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in
-  *posix*) set -o posix ;;
-esac
-
-fi
-
-
-
-
-# PATH needs CR
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  echo "#! /bin/sh" >conf$$.sh
-  echo  "exit 0"   >>conf$$.sh
-  chmod +x conf$$.sh
-  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
-    PATH_SEPARATOR=';'
-  else
-    PATH_SEPARATOR=:
-  fi
-  rm -f conf$$.sh
-fi
-
-# Support unset when possible.
-if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
-  as_unset=unset
-else
-  as_unset=false
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-as_nl='
-'
-IFS=" ""	$as_nl"
-
-# Find who we are.  Look in the path if we contain no directory separator.
-case $0 in
-  *[\\/]* ) as_myself=$0 ;;
-  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-done
-IFS=$as_save_IFS
-
-     ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
-  as_myself=$0
-fi
-if test ! -f "$as_myself"; then
-  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
-  { (exit 1); exit 1; }
-fi
-
-# Work around bugs in pre-3.0 UWIN ksh.
-for as_var in ENV MAIL MAILPATH
-do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-for as_var in \
-  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
-  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
-  LC_TELEPHONE LC_TIME
-do
-  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
-    eval $as_var=C; export $as_var
-  else
-    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-  fi
-done
-
-# Required to use basename.
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
-  as_basename=basename
-else
-  as_basename=false
-fi
-
-
-# Name of the executable.
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-
-# CDPATH.
-$as_unset CDPATH
-
-
-if test "x$CONFIG_SHELL" = x; then
-  if (eval ":") 2>/dev/null; then
-  as_have_required=yes
-else
-  as_have_required=no
-fi
-
-  if test $as_have_required = yes && 	 (eval ":
-(as_func_return () {
-  (exit \$1)
-}
-as_func_success () {
-  as_func_return 0
-}
-as_func_failure () {
-  as_func_return 1
-}
-as_func_ret_success () {
-  return 0
-}
-as_func_ret_failure () {
-  return 1
-}
-
-exitcode=0
-if as_func_success; then
-  :
-else
-  exitcode=1
-  echo as_func_success failed.
-fi
-
-if as_func_failure; then
-  exitcode=1
-  echo as_func_failure succeeded.
-fi
-
-if as_func_ret_success; then
-  :
-else
-  exitcode=1
-  echo as_func_ret_success failed.
-fi
-
-if as_func_ret_failure; then
-  exitcode=1
-  echo as_func_ret_failure succeeded.
-fi
-
-if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
-  :
-else
-  exitcode=1
-  echo positional parameters were not saved.
-fi
-
-test \$exitcode = 0) || { (exit 1); exit 1; }
-
-(
-  as_lineno_1=\$LINENO
-  as_lineno_2=\$LINENO
-  test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" &&
-  test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; }
-") 2> /dev/null; then
-  :
-else
-  as_candidate_shells=
-    as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  case $as_dir in
-	 /*)
-	   for as_base in sh bash ksh sh5; do
-	     as_candidate_shells="$as_candidate_shells $as_dir/$as_base"
-	   done;;
-       esac
-done
-IFS=$as_save_IFS
-
-
-      for as_shell in $as_candidate_shells $SHELL; do
-	 # Try only shells that exist, to save several forks.
-	 if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
-		{ ("$as_shell") 2> /dev/null <<\_ASEOF
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in
-  *posix*) set -o posix ;;
-esac
-
-fi
-
-
-:
-_ASEOF
-}; then
-  CONFIG_SHELL=$as_shell
-	       as_have_required=yes
-	       if { "$as_shell" 2> /dev/null <<\_ASEOF
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in
-  *posix*) set -o posix ;;
-esac
-
-fi
-
-
-:
-(as_func_return () {
-  (exit $1)
-}
-as_func_success () {
-  as_func_return 0
-}
-as_func_failure () {
-  as_func_return 1
-}
-as_func_ret_success () {
-  return 0
-}
-as_func_ret_failure () {
-  return 1
-}
-
-exitcode=0
-if as_func_success; then
-  :
-else
-  exitcode=1
-  echo as_func_success failed.
-fi
-
-if as_func_failure; then
-  exitcode=1
-  echo as_func_failure succeeded.
-fi
-
-if as_func_ret_success; then
-  :
-else
-  exitcode=1
-  echo as_func_ret_success failed.
-fi
-
-if as_func_ret_failure; then
-  exitcode=1
-  echo as_func_ret_failure succeeded.
-fi
-
-if ( set x; as_func_ret_success y && test x = "$1" ); then
-  :
-else
-  exitcode=1
-  echo positional parameters were not saved.
-fi
-
-test $exitcode = 0) || { (exit 1); exit 1; }
-
-(
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; }
-
-_ASEOF
-}; then
-  break
-fi
-
-fi
-
-      done
-
-      if test "x$CONFIG_SHELL" != x; then
-  for as_var in BASH_ENV ENV
-        do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-        done
-        export CONFIG_SHELL
-        exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
-fi
-
-
-    if test $as_have_required = no; then
-  echo This script requires a shell more modern than all the
-      echo shells that I found on your system.  Please install a
-      echo modern shell, or manually run the script under such a
-      echo shell if you do have one.
-      { (exit 1); exit 1; }
-fi
-
-
-fi
-
-fi
-
-
-
-(eval "as_func_return () {
-  (exit \$1)
-}
-as_func_success () {
-  as_func_return 0
-}
-as_func_failure () {
-  as_func_return 1
-}
-as_func_ret_success () {
-  return 0
-}
-as_func_ret_failure () {
-  return 1
-}
-
-exitcode=0
-if as_func_success; then
-  :
-else
-  exitcode=1
-  echo as_func_success failed.
-fi
-
-if as_func_failure; then
-  exitcode=1
-  echo as_func_failure succeeded.
-fi
-
-if as_func_ret_success; then
-  :
-else
-  exitcode=1
-  echo as_func_ret_success failed.
-fi
-
-if as_func_ret_failure; then
-  exitcode=1
-  echo as_func_ret_failure succeeded.
-fi
-
-if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
-  :
-else
-  exitcode=1
-  echo positional parameters were not saved.
-fi
-
-test \$exitcode = 0") || {
-  echo No shell found that supports shell functions.
-  echo Please tell autoconf@gnu.org about your system,
-  echo including any error possibly output before this
-  echo message
-}
-
-
-
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
-
-  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
-  # uniformly replaced by the line number.  The first 'sed' inserts a
-  # line-number line after each line using $LINENO; the second 'sed'
-  # does the real work.  The second script uses 'N' to pair each
-  # line-number line with the line containing $LINENO, and appends
-  # trailing '-' during substitution so that $LINENO is not a special
-  # case at line end.
-  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
-  # scripts with optimization help from Paolo Bonzini.  Blame Lee
-  # E. McMahon (1931-1989) for sed's syntax.  :-)
-  sed -n '
-    p
-    /[$]LINENO/=
-  ' <$as_myself |
-    sed '
-      s/[$]LINENO.*/&-/
-      t lineno
-      b
-      :lineno
-      N
-      :loop
-      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
-      t loop
-      s/-\n.*//
-    ' >$as_me.lineno &&
-  chmod +x "$as_me.lineno" ||
-    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
-   { (exit 1); exit 1; }; }
-
-  # Don't try to exec as it changes $[0], causing all sort of problems
-  # (the dirname of $[0] is not the place where we might find the
-  # original and so on.  Autoconf is especially sensitive to this).
-  . "./$as_me.lineno"
-  # Exit status is that of the last command.
-  exit
-}
-
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
-  as_dirname=dirname
-else
-  as_dirname=false
-fi
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in
--n*)
-  case `echo 'x\c'` in
-  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
-  *)   ECHO_C='\c';;
-  esac;;
-*)
-  ECHO_N='-n';;
-esac
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
-  rm -f conf$$.dir/conf$$.file
-else
-  rm -f conf$$.dir
-  mkdir conf$$.dir
-fi
-echo >conf$$.file
-if ln -s conf$$.file conf$$ 2>/dev/null; then
-  as_ln_s='ln -s'
-  # ... but there are two gotchas:
-  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
-  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
-  # In both cases, we have to default to `cp -p'.
-  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
-    as_ln_s='cp -p'
-elif ln conf$$.file conf$$ 2>/dev/null; then
-  as_ln_s=ln
-else
-  as_ln_s='cp -p'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-if mkdir -p . 2>/dev/null; then
-  as_mkdir_p=:
-else
-  test -d ./-p && rmdir ./-p
-  as_mkdir_p=false
-fi
-
-if test -x / >/dev/null 2>&1; then
-  as_test_x='test -x'
-else
-  if ls -dL / >/dev/null 2>&1; then
-    as_ls_L_option=L
-  else
-    as_ls_L_option=
-  fi
-  as_test_x='
-    eval sh -c '\''
-      if test -d "$1"; then
-        test -d "$1/.";
-      else
-	case $1 in
-        -*)set "./$1";;
-	esac;
-	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
-	???[sx]*):;;*)false;;esac;fi
-    '\'' sh
-  '
-fi
-as_executable_p=$as_test_x
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-
-exec 7<&0 </dev/null 6>&1
-
-# Name of the host.
-# hostname on some systems (SVR3.2, Linux) returns a bogus exit status,
-# so uname gets run too.
-ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
-
-#
-# Initializations.
-#
-ac_default_prefix=/usr/local
-ac_clean_files=
-ac_config_libobj_dir=.
-LIBOBJS=
-cross_compiling=no
-subdirs=
-MFLAGS=
-MAKEFLAGS=
-SHELL=${CONFIG_SHELL-/bin/sh}
-
-# Identity of this package.
-PACKAGE_NAME='HDBC-postgresql package'
-PACKAGE_TARNAME='hdbc-postgresql-package'
-PACKAGE_VERSION='1.1'
-PACKAGE_STRING='HDBC-postgresql package 1.1'
-PACKAGE_BUGREPORT=''
-
-ac_unique_file="HDBC-postgresql.cabal"
-ac_subst_vars='SHELL
-PATH_SEPARATOR
-PACKAGE_NAME
-PACKAGE_TARNAME
-PACKAGE_VERSION
-PACKAGE_STRING
-PACKAGE_BUGREPORT
-exec_prefix
-prefix
-program_transform_name
-bindir
-sbindir
-libexecdir
-datarootdir
-datadir
-sysconfdir
-sharedstatedir
-localstatedir
-includedir
-oldincludedir
-docdir
-infodir
-htmldir
-dvidir
-pdfdir
-psdir
-libdir
-localedir
-mandir
-DEFS
-ECHO_C
-ECHO_N
-ECHO_T
-LIBS
-build_alias
-host_alias
-target_alias
-pgconfig
-PGINCDIR
-PGLIBDIR
-LIBOBJS
-LTLIBOBJS'
-ac_subst_files=''
-      ac_precious_vars='build_alias
-host_alias
-target_alias'
-
-
-# Initialize some variables set by options.
-ac_init_help=
-ac_init_version=false
-# The variables have the same names as the options, with
-# dashes changed to underlines.
-cache_file=/dev/null
-exec_prefix=NONE
-no_create=
-no_recursion=
-prefix=NONE
-program_prefix=NONE
-program_suffix=NONE
-program_transform_name=s,x,x,
-silent=
-site=
-srcdir=
-verbose=
-x_includes=NONE
-x_libraries=NONE
-
-# Installation directory options.
-# These are left unexpanded so users can "make install exec_prefix=/foo"
-# and all the variables that are supposed to be based on exec_prefix
-# by default will actually change.
-# Use braces instead of parens because sh, perl, etc. also accept them.
-# (The list follows the same order as the GNU Coding Standards.)
-bindir='${exec_prefix}/bin'
-sbindir='${exec_prefix}/sbin'
-libexecdir='${exec_prefix}/libexec'
-datarootdir='${prefix}/share'
-datadir='${datarootdir}'
-sysconfdir='${prefix}/etc'
-sharedstatedir='${prefix}/com'
-localstatedir='${prefix}/var'
-includedir='${prefix}/include'
-oldincludedir='/usr/include'
-docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
-infodir='${datarootdir}/info'
-htmldir='${docdir}'
-dvidir='${docdir}'
-pdfdir='${docdir}'
-psdir='${docdir}'
-libdir='${exec_prefix}/lib'
-localedir='${datarootdir}/locale'
-mandir='${datarootdir}/man'
-
-ac_prev=
-ac_dashdash=
-for ac_option
-do
-  # If the previous option needs an argument, assign it.
-  if test -n "$ac_prev"; then
-    eval $ac_prev=\$ac_option
-    ac_prev=
-    continue
-  fi
-
-  case $ac_option in
-  *=*)	ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
-  *)	ac_optarg=yes ;;
-  esac
-
-  # Accept the important Cygnus configure options, so we can diagnose typos.
-
-  case $ac_dashdash$ac_option in
-  --)
-    ac_dashdash=yes ;;
-
-  -bindir | --bindir | --bindi | --bind | --bin | --bi)
-    ac_prev=bindir ;;
-  -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*)
-    bindir=$ac_optarg ;;
-
-  -build | --build | --buil | --bui | --bu)
-    ac_prev=build_alias ;;
-  -build=* | --build=* | --buil=* | --bui=* | --bu=*)
-    build_alias=$ac_optarg ;;
-
-  -cache-file | --cache-file | --cache-fil | --cache-fi \
-  | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c)
-    ac_prev=cache_file ;;
-  -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \
-  | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*)
-    cache_file=$ac_optarg ;;
-
-  --config-cache | -C)
-    cache_file=config.cache ;;
-
-  -datadir | --datadir | --datadi | --datad)
-    ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=*)
-    datadir=$ac_optarg ;;
-
-  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
-  | --dataroo | --dataro | --datar)
-    ac_prev=datarootdir ;;
-  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
-  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
-    datarootdir=$ac_optarg ;;
-
-  -disable-* | --disable-*)
-    ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
-   { (exit 1); exit 1; }; }
-    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
-    eval enable_$ac_feature=no ;;
-
-  -docdir | --docdir | --docdi | --doc | --do)
-    ac_prev=docdir ;;
-  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
-    docdir=$ac_optarg ;;
-
-  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
-    ac_prev=dvidir ;;
-  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
-    dvidir=$ac_optarg ;;
-
-  -enable-* | --enable-*)
-    ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid feature name: $ac_feature" >&2
-   { (exit 1); exit 1; }; }
-    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
-    eval enable_$ac_feature=\$ac_optarg ;;
-
-  -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
-  | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
-  | --exec | --exe | --ex)
-    ac_prev=exec_prefix ;;
-  -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \
-  | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \
-  | --exec=* | --exe=* | --ex=*)
-    exec_prefix=$ac_optarg ;;
-
-  -gas | --gas | --ga | --g)
-    # Obsolete; use --with-gas.
-    with_gas=yes ;;
-
-  -help | --help | --hel | --he | -h)
-    ac_init_help=long ;;
-  -help=r* | --help=r* | --hel=r* | --he=r* | -hr*)
-    ac_init_help=recursive ;;
-  -help=s* | --help=s* | --hel=s* | --he=s* | -hs*)
-    ac_init_help=short ;;
-
-  -host | --host | --hos | --ho)
-    ac_prev=host_alias ;;
-  -host=* | --host=* | --hos=* | --ho=*)
-    host_alias=$ac_optarg ;;
-
-  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
-    ac_prev=htmldir ;;
-  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
-  | --ht=*)
-    htmldir=$ac_optarg ;;
-
-  -includedir | --includedir | --includedi | --included | --include \
-  | --includ | --inclu | --incl | --inc)
-    ac_prev=includedir ;;
-  -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \
-  | --includ=* | --inclu=* | --incl=* | --inc=*)
-    includedir=$ac_optarg ;;
-
-  -infodir | --infodir | --infodi | --infod | --info | --inf)
-    ac_prev=infodir ;;
-  -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*)
-    infodir=$ac_optarg ;;
-
-  -libdir | --libdir | --libdi | --libd)
-    ac_prev=libdir ;;
-  -libdir=* | --libdir=* | --libdi=* | --libd=*)
-    libdir=$ac_optarg ;;
-
-  -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \
-  | --libexe | --libex | --libe)
-    ac_prev=libexecdir ;;
-  -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \
-  | --libexe=* | --libex=* | --libe=*)
-    libexecdir=$ac_optarg ;;
-
-  -localedir | --localedir | --localedi | --localed | --locale)
-    ac_prev=localedir ;;
-  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
-    localedir=$ac_optarg ;;
-
-  -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst | --locals)
-    ac_prev=localstatedir ;;
-  -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
-    localstatedir=$ac_optarg ;;
-
-  -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
-    ac_prev=mandir ;;
-  -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*)
-    mandir=$ac_optarg ;;
-
-  -nfp | --nfp | --nf)
-    # Obsolete; use --without-fp.
-    with_fp=no ;;
-
-  -no-create | --no-create | --no-creat | --no-crea | --no-cre \
-  | --no-cr | --no-c | -n)
-    no_create=yes ;;
-
-  -no-recursion | --no-recursion | --no-recursio | --no-recursi \
-  | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r)
-    no_recursion=yes ;;
-
-  -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \
-  | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \
-  | --oldin | --oldi | --old | --ol | --o)
-    ac_prev=oldincludedir ;;
-  -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \
-  | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \
-  | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*)
-    oldincludedir=$ac_optarg ;;
-
-  -prefix | --prefix | --prefi | --pref | --pre | --pr | --p)
-    ac_prev=prefix ;;
-  -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*)
-    prefix=$ac_optarg ;;
-
-  -program-prefix | --program-prefix | --program-prefi | --program-pref \
-  | --program-pre | --program-pr | --program-p)
-    ac_prev=program_prefix ;;
-  -program-prefix=* | --program-prefix=* | --program-prefi=* \
-  | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*)
-    program_prefix=$ac_optarg ;;
-
-  -program-suffix | --program-suffix | --program-suffi | --program-suff \
-  | --program-suf | --program-su | --program-s)
-    ac_prev=program_suffix ;;
-  -program-suffix=* | --program-suffix=* | --program-suffi=* \
-  | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*)
-    program_suffix=$ac_optarg ;;
-
-  -program-transform-name | --program-transform-name \
-  | --program-transform-nam | --program-transform-na \
-  | --program-transform-n | --program-transform- \
-  | --program-transform | --program-transfor \
-  | --program-transfo | --program-transf \
-  | --program-trans | --program-tran \
-  | --progr-tra | --program-tr | --program-t)
-    ac_prev=program_transform_name ;;
-  -program-transform-name=* | --program-transform-name=* \
-  | --program-transform-nam=* | --program-transform-na=* \
-  | --program-transform-n=* | --program-transform-=* \
-  | --program-transform=* | --program-transfor=* \
-  | --program-transfo=* | --program-transf=* \
-  | --program-trans=* | --program-tran=* \
-  | --progr-tra=* | --program-tr=* | --program-t=*)
-    program_transform_name=$ac_optarg ;;
-
-  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
-    ac_prev=pdfdir ;;
-  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
-    pdfdir=$ac_optarg ;;
-
-  -psdir | --psdir | --psdi | --psd | --ps)
-    ac_prev=psdir ;;
-  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
-    psdir=$ac_optarg ;;
-
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil)
-    silent=yes ;;
-
-  -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb)
-    ac_prev=sbindir ;;
-  -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \
-  | --sbi=* | --sb=*)
-    sbindir=$ac_optarg ;;
-
-  -sharedstatedir | --sharedstatedir | --sharedstatedi \
-  | --sharedstated | --sharedstate | --sharedstat | --sharedsta \
-  | --sharedst | --shareds | --shared | --share | --shar \
-  | --sha | --sh)
-    ac_prev=sharedstatedir ;;
-  -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \
-  | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \
-  | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \
-  | --sha=* | --sh=*)
-    sharedstatedir=$ac_optarg ;;
-
-  -site | --site | --sit)
-    ac_prev=site ;;
-  -site=* | --site=* | --sit=*)
-    site=$ac_optarg ;;
-
-  -srcdir | --srcdir | --srcdi | --srcd | --src | --sr)
-    ac_prev=srcdir ;;
-  -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*)
-    srcdir=$ac_optarg ;;
-
-  -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \
-  | --syscon | --sysco | --sysc | --sys | --sy)
-    ac_prev=sysconfdir ;;
-  -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \
-  | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*)
-    sysconfdir=$ac_optarg ;;
-
-  -target | --target | --targe | --targ | --tar | --ta | --t)
-    ac_prev=target_alias ;;
-  -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*)
-    target_alias=$ac_optarg ;;
-
-  -v | -verbose | --verbose | --verbos | --verbo | --verb)
-    verbose=yes ;;
-
-  -version | --version | --versio | --versi | --vers | -V)
-    ac_init_version=: ;;
-
-  -with-* | --with-*)
-    ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid package name: $ac_package" >&2
-   { (exit 1); exit 1; }; }
-    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
-    eval with_$ac_package=\$ac_optarg ;;
-
-  -without-* | --without-*)
-    ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid package name: $ac_package" >&2
-   { (exit 1); exit 1; }; }
-    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
-    eval with_$ac_package=no ;;
-
-  --x)
-    # Obsolete; use --with-x.
-    with_x=yes ;;
-
-  -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \
-  | --x-incl | --x-inc | --x-in | --x-i)
-    ac_prev=x_includes ;;
-  -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \
-  | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*)
-    x_includes=$ac_optarg ;;
-
-  -x-libraries | --x-libraries | --x-librarie | --x-librari \
-  | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l)
-    ac_prev=x_libraries ;;
-  -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \
-  | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*)
-    x_libraries=$ac_optarg ;;
-
-  -*) { echo "$as_me: error: unrecognized option: $ac_option
-Try \`$0 --help' for more information." >&2
-   { (exit 1); exit 1; }; }
-    ;;
-
-  *=*)
-    ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='`
-    # Reject names that are not valid shell variable names.
-    expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null &&
-      { echo "$as_me: error: invalid variable name: $ac_envvar" >&2
-   { (exit 1); exit 1; }; }
-    eval $ac_envvar=\$ac_optarg
-    export $ac_envvar ;;
-
-  *)
-    # FIXME: should be removed in autoconf 3.0.
-    echo "$as_me: WARNING: you should use --build, --host, --target" >&2
-    expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
-      echo "$as_me: WARNING: invalid host type: $ac_option" >&2
-    : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}
-    ;;
-
-  esac
-done
-
-if test -n "$ac_prev"; then
-  ac_option=--`echo $ac_prev | sed 's/_/-/g'`
-  { echo "$as_me: error: missing argument to $ac_option" >&2
-   { (exit 1); exit 1; }; }
-fi
-
-# Be sure to have absolute directory names.
-for ac_var in	exec_prefix prefix bindir sbindir libexecdir datarootdir \
-		datadir sysconfdir sharedstatedir localstatedir includedir \
-		oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
-		libdir localedir mandir
-do
-  eval ac_val=\$$ac_var
-  case $ac_val in
-    [\\/$]* | ?:[\\/]* )  continue;;
-    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
-  esac
-  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
-   { (exit 1); exit 1; }; }
-done
-
-# There might be people who depend on the old broken behavior: `$host'
-# used to hold the argument of --host etc.
-# FIXME: To remove some day.
-build=$build_alias
-host=$host_alias
-target=$target_alias
-
-# FIXME: To remove some day.
-if test "x$host_alias" != x; then
-  if test "x$build_alias" = x; then
-    cross_compiling=maybe
-    echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host.
-    If a cross compiler is detected then cross compile mode will be used." >&2
-  elif test "x$build_alias" != "x$host_alias"; then
-    cross_compiling=yes
-  fi
-fi
-
-ac_tool_prefix=
-test -n "$host_alias" && ac_tool_prefix=$host_alias-
-
-test "$silent" = yes && exec 6>/dev/null
-
-
-ac_pwd=`pwd` && test -n "$ac_pwd" &&
-ac_ls_di=`ls -di .` &&
-ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
-  { echo "$as_me: error: Working directory cannot be determined" >&2
-   { (exit 1); exit 1; }; }
-test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
-  { echo "$as_me: error: pwd does not report name of working directory" >&2
-   { (exit 1); exit 1; }; }
-
-
-# Find the source files, if location was not specified.
-if test -z "$srcdir"; then
-  ac_srcdir_defaulted=yes
-  # Try the directory containing this script, then the parent directory.
-  ac_confdir=`$as_dirname -- "$0" ||
-$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$0" : 'X\(//\)[^/]' \| \
-	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-echo X"$0" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)[^/].*/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-  srcdir=$ac_confdir
-  if test ! -r "$srcdir/$ac_unique_file"; then
-    srcdir=..
-  fi
-else
-  ac_srcdir_defaulted=no
-fi
-if test ! -r "$srcdir/$ac_unique_file"; then
-  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
-  { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2
-   { (exit 1); exit 1; }; }
-fi
-ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
-ac_abs_confdir=`(
-	cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2
-   { (exit 1); exit 1; }; }
-	pwd)`
-# When building in place, set srcdir=.
-if test "$ac_abs_confdir" = "$ac_pwd"; then
-  srcdir=.
-fi
-# Remove unnecessary trailing slashes from srcdir.
-# Double slashes in file names in object file debugging info
-# mess up M-x gdb in Emacs.
-case $srcdir in
-*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
-esac
-for ac_var in $ac_precious_vars; do
-  eval ac_env_${ac_var}_set=\${${ac_var}+set}
-  eval ac_env_${ac_var}_value=\$${ac_var}
-  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
-  eval ac_cv_env_${ac_var}_value=\$${ac_var}
-done
-
-#
-# Report the --help message.
-#
-if test "$ac_init_help" = "long"; then
-  # Omit some internal or obsolete options to make the list less imposing.
-  # This message is too long to be a string in the A/UX 3.1 sh.
-  cat <<_ACEOF
-\`configure' configures HDBC-postgresql package 1.1 to adapt to many kinds of systems.
-
-Usage: $0 [OPTION]... [VAR=VALUE]...
-
-To assign environment variables (e.g., CC, CFLAGS...), specify them as
-VAR=VALUE.  See below for descriptions of some of the useful variables.
-
-Defaults for the options are specified in brackets.
-
-Configuration:
-  -h, --help              display this help and exit
-      --help=short        display options specific to this package
-      --help=recursive    display the short help of all the included packages
-  -V, --version           display version information and exit
-  -q, --quiet, --silent   do not print \`checking...' messages
-      --cache-file=FILE   cache test results in FILE [disabled]
-  -C, --config-cache      alias for \`--cache-file=config.cache'
-  -n, --no-create         do not create output files
-      --srcdir=DIR        find the sources in DIR [configure dir or \`..']
-
-Installation directories:
-  --prefix=PREFIX         install architecture-independent files in PREFIX
-			  [$ac_default_prefix]
-  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
-			  [PREFIX]
-
-By default, \`make install' will install all the files in
-\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc.  You can specify
-an installation prefix other than \`$ac_default_prefix' using \`--prefix',
-for instance \`--prefix=\$HOME'.
-
-For better control, use the options below.
-
-Fine tuning of the installation directories:
-  --bindir=DIR           user executables [EPREFIX/bin]
-  --sbindir=DIR          system admin executables [EPREFIX/sbin]
-  --libexecdir=DIR       program executables [EPREFIX/libexec]
-  --sysconfdir=DIR       read-only single-machine data [PREFIX/etc]
-  --sharedstatedir=DIR   modifiable architecture-independent data [PREFIX/com]
-  --localstatedir=DIR    modifiable single-machine data [PREFIX/var]
-  --libdir=DIR           object code libraries [EPREFIX/lib]
-  --includedir=DIR       C header files [PREFIX/include]
-  --oldincludedir=DIR    C header files for non-gcc [/usr/include]
-  --datarootdir=DIR      read-only arch.-independent data root [PREFIX/share]
-  --datadir=DIR          read-only architecture-independent data [DATAROOTDIR]
-  --infodir=DIR          info documentation [DATAROOTDIR/info]
-  --localedir=DIR        locale-dependent data [DATAROOTDIR/locale]
-  --mandir=DIR           man documentation [DATAROOTDIR/man]
-  --docdir=DIR           documentation root [DATAROOTDIR/doc/hdbc-postgresql-package]
-  --htmldir=DIR          html documentation [DOCDIR]
-  --dvidir=DIR           dvi documentation [DOCDIR]
-  --pdfdir=DIR           pdf documentation [DOCDIR]
-  --psdir=DIR            ps documentation [DOCDIR]
-_ACEOF
-
-  cat <<\_ACEOF
-_ACEOF
-fi
-
-if test -n "$ac_init_help"; then
-  case $ac_init_help in
-     short | recursive ) echo "Configuration of HDBC-postgresql package 1.1:";;
-   esac
-  cat <<\_ACEOF
-
-_ACEOF
-ac_status=$?
-fi
-
-if test "$ac_init_help" = "recursive"; then
-  # If there are subdirs, report their specific --help.
-  for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
-    test -d "$ac_dir" || continue
-    ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
-  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
-  # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
-  case $ac_top_builddir_sub in
-  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
-  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
-  esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
-  .)  # We are building in place.
-    ac_srcdir=.
-    ac_top_srcdir=$ac_top_builddir_sub
-    ac_abs_top_srcdir=$ac_pwd ;;
-  [\\/]* | ?:[\\/]* )  # Absolute name.
-    ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir
-    ac_abs_top_srcdir=$srcdir ;;
-  *) # Relative name.
-    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_build_prefix$srcdir
-    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
-    cd "$ac_dir" || { ac_status=$?; continue; }
-    # Check for guested configure.
-    if test -f "$ac_srcdir/configure.gnu"; then
-      echo &&
-      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
-    elif test -f "$ac_srcdir/configure"; then
-      echo &&
-      $SHELL "$ac_srcdir/configure" --help=recursive
-    else
-      echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
-    fi || ac_status=$?
-    cd "$ac_pwd" || { ac_status=$?; break; }
-  done
-fi
-
-test -n "$ac_init_help" && exit $ac_status
-if $ac_init_version; then
-  cat <<\_ACEOF
-HDBC-postgresql package configure 1.1
-generated by GNU Autoconf 2.61
-
-Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
-2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
-This configure script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it.
-_ACEOF
-  exit
-fi
-cat >config.log <<_ACEOF
-This file contains any messages produced by compilers while
-running configure, to aid debugging if configure makes a mistake.
-
-It was created by HDBC-postgresql package $as_me 1.1, which was
-generated by GNU Autoconf 2.61.  Invocation command line was
-
-  $ $0 $@
-
-_ACEOF
-exec 5>>config.log
-{
-cat <<_ASUNAME
-## --------- ##
-## Platform. ##
-## --------- ##
-
-hostname = `(hostname || uname -n) 2>/dev/null | sed 1q`
-uname -m = `(uname -m) 2>/dev/null || echo unknown`
-uname -r = `(uname -r) 2>/dev/null || echo unknown`
-uname -s = `(uname -s) 2>/dev/null || echo unknown`
-uname -v = `(uname -v) 2>/dev/null || echo unknown`
-
-/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown`
-/bin/uname -X     = `(/bin/uname -X) 2>/dev/null     || echo unknown`
-
-/bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
-/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
-/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
-/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
-/bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
-/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
-/bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
-
-_ASUNAME
-
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  echo "PATH: $as_dir"
-done
-IFS=$as_save_IFS
-
-} >&5
-
-cat >&5 <<_ACEOF
-
-
-## ----------- ##
-## Core tests. ##
-## ----------- ##
-
-_ACEOF
-
-
-# Keep a trace of the command line.
-# Strip out --no-create and --no-recursion so they do not pile up.
-# Strip out --silent because we don't want to record it for future runs.
-# Also quote any args containing shell meta-characters.
-# Make two passes to allow for proper duplicate-argument suppression.
-ac_configure_args=
-ac_configure_args0=
-ac_configure_args1=
-ac_must_keep_next=false
-for ac_pass in 1 2
-do
-  for ac_arg
-  do
-    case $ac_arg in
-    -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;;
-    -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-    | -silent | --silent | --silen | --sile | --sil)
-      continue ;;
-    *\'*)
-      ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
-    esac
-    case $ac_pass in
-    1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;;
-    2)
-      ac_configure_args1="$ac_configure_args1 '$ac_arg'"
-      if test $ac_must_keep_next = true; then
-	ac_must_keep_next=false # Got value, back to normal.
-      else
-	case $ac_arg in
-	  *=* | --config-cache | -C | -disable-* | --disable-* \
-	  | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \
-	  | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \
-	  | -with-* | --with-* | -without-* | --without-* | --x)
-	    case "$ac_configure_args0 " in
-	      "$ac_configure_args1"*" '$ac_arg' "* ) continue ;;
-	    esac
-	    ;;
-	  -* ) ac_must_keep_next=true ;;
-	esac
-      fi
-      ac_configure_args="$ac_configure_args '$ac_arg'"
-      ;;
-    esac
-  done
-done
-$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; }
-$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; }
-
-# When interrupted or exit'd, cleanup temporary files, and complete
-# config.log.  We remove comments because anyway the quotes in there
-# would cause problems or look ugly.
-# WARNING: Use '\'' to represent an apostrophe within the trap.
-# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
-trap 'exit_status=$?
-  # Save into config.log some information that might help in debugging.
-  {
-    echo
-
-    cat <<\_ASBOX
-## ---------------- ##
-## Cache variables. ##
-## ---------------- ##
-_ASBOX
-    echo
-    # The following way of writing the cache mishandles newlines in values,
-(
-  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
-    eval ac_val=\$$ac_var
-    case $ac_val in #(
-    *${as_nl}*)
-      case $ac_var in #(
-      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
-echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
-      esac
-      case $ac_var in #(
-      _ | IFS | as_nl) ;; #(
-      *) $as_unset $ac_var ;;
-      esac ;;
-    esac
-  done
-  (set) 2>&1 |
-    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
-    *${as_nl}ac_space=\ *)
-      sed -n \
-	"s/'\''/'\''\\\\'\'''\''/g;
-	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
-      ;; #(
-    *)
-      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
-      ;;
-    esac |
-    sort
-)
-    echo
-
-    cat <<\_ASBOX
-## ----------------- ##
-## Output variables. ##
-## ----------------- ##
-_ASBOX
-    echo
-    for ac_var in $ac_subst_vars
-    do
-      eval ac_val=\$$ac_var
-      case $ac_val in
-      *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
-      esac
-      echo "$ac_var='\''$ac_val'\''"
-    done | sort
-    echo
-
-    if test -n "$ac_subst_files"; then
-      cat <<\_ASBOX
-## ------------------- ##
-## File substitutions. ##
-## ------------------- ##
-_ASBOX
-      echo
-      for ac_var in $ac_subst_files
-      do
-	eval ac_val=\$$ac_var
-	case $ac_val in
-	*\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
-	esac
-	echo "$ac_var='\''$ac_val'\''"
-      done | sort
-      echo
-    fi
-
-    if test -s confdefs.h; then
-      cat <<\_ASBOX
-## ----------- ##
-## confdefs.h. ##
-## ----------- ##
-_ASBOX
-      echo
-      cat confdefs.h
-      echo
-    fi
-    test "$ac_signal" != 0 &&
-      echo "$as_me: caught signal $ac_signal"
-    echo "$as_me: exit $exit_status"
-  } >&5
-  rm -f core *.core core.conftest.* &&
-    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
-    exit $exit_status
-' 0
-for ac_signal in 1 2 13 15; do
-  trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal
-done
-ac_signal=0
-
-# confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -f -r conftest* confdefs.h
-
-# Predefined preprocessor variables.
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_NAME "$PACKAGE_NAME"
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_TARNAME "$PACKAGE_TARNAME"
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_VERSION "$PACKAGE_VERSION"
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_STRING "$PACKAGE_STRING"
-_ACEOF
-
-
-cat >>confdefs.h <<_ACEOF
-#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT"
-_ACEOF
-
-
-# Let the site file select an alternate cache file if it wants to.
-# Prefer explicitly selected file to automatically selected ones.
-if test -n "$CONFIG_SITE"; then
-  set x "$CONFIG_SITE"
-elif test "x$prefix" != xNONE; then
-  set x "$prefix/share/config.site" "$prefix/etc/config.site"
-else
-  set x "$ac_default_prefix/share/config.site" \
-	"$ac_default_prefix/etc/config.site"
-fi
-shift
-for ac_site_file
-do
-  if test -r "$ac_site_file"; then
-    { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5
-echo "$as_me: loading site script $ac_site_file" >&6;}
-    sed 's/^/| /' "$ac_site_file" >&5
-    . "$ac_site_file"
-  fi
-done
-
-if test -r "$cache_file"; then
-  # Some versions of bash will fail to source /dev/null (special
-  # files actually), so we avoid doing that.
-  if test -f "$cache_file"; then
-    { echo "$as_me:$LINENO: loading cache $cache_file" >&5
-echo "$as_me: loading cache $cache_file" >&6;}
-    case $cache_file in
-      [\\/]* | ?:[\\/]* ) . "$cache_file";;
-      *)                      . "./$cache_file";;
-    esac
-  fi
-else
-  { echo "$as_me:$LINENO: creating cache $cache_file" >&5
-echo "$as_me: creating cache $cache_file" >&6;}
-  >$cache_file
-fi
-
-# Check that the precious variables saved in the cache have kept the same
-# value.
-ac_cache_corrupted=false
-for ac_var in $ac_precious_vars; do
-  eval ac_old_set=\$ac_cv_env_${ac_var}_set
-  eval ac_new_set=\$ac_env_${ac_var}_set
-  eval ac_old_val=\$ac_cv_env_${ac_var}_value
-  eval ac_new_val=\$ac_env_${ac_var}_value
-  case $ac_old_set,$ac_new_set in
-    set,)
-      { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
-echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;}
-      ac_cache_corrupted=: ;;
-    ,set)
-      { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5
-echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;}
-      ac_cache_corrupted=: ;;
-    ,);;
-    *)
-      if test "x$ac_old_val" != "x$ac_new_val"; then
-	{ echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5
-echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;}
-	{ echo "$as_me:$LINENO:   former value:  $ac_old_val" >&5
-echo "$as_me:   former value:  $ac_old_val" >&2;}
-	{ echo "$as_me:$LINENO:   current value: $ac_new_val" >&5
-echo "$as_me:   current value: $ac_new_val" >&2;}
-	ac_cache_corrupted=:
-      fi;;
-  esac
-  # Pass precious variables to config.status.
-  if test "$ac_new_set" = set; then
-    case $ac_new_val in
-    *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
-    *) ac_arg=$ac_var=$ac_new_val ;;
-    esac
-    case " $ac_configure_args " in
-      *" '$ac_arg' "*) ;; # Avoid dups.  Use of quotes ensures accuracy.
-      *) ac_configure_args="$ac_configure_args '$ac_arg'" ;;
-    esac
-  fi
-done
-if $ac_cache_corrupted; then
-  { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5
-echo "$as_me: error: changes in the environment can compromise the build" >&2;}
-  { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5
-echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;}
-   { (exit 1); exit 1; }; }
-fi
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-
-# Safety check: Ensure that we are in the correct source directory.
-
-
-# Extract the first word of "pg_config", so it can be a program name with args.
-set dummy pg_config; ac_word=$2
-{ echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
-if test "${ac_cv_path_pgconfig+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  case $pgconfig in
-  [\\/]* | ?:[\\/]*)
-  ac_cv_path_pgconfig="$pgconfig" # Let the user override the test with a path.
-  ;;
-  *)
-  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
-    ac_cv_path_pgconfig="$as_dir/$ac_word$ac_exec_ext"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-IFS=$as_save_IFS
-
-  ;;
-esac
-fi
-pgconfig=$ac_cv_path_pgconfig
-if test -n "$pgconfig"; then
-  { echo "$as_me:$LINENO: result: $pgconfig" >&5
-echo "${ECHO_T}$pgconfig" >&6; }
-else
-  { echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6; }
-fi
-
-
-if test  -z "$pgconfig" ; then
-    { { echo "$as_me:$LINENO: error: pg_config executable not found. Make sure pg_config is in your path" >&5
-echo "$as_me: error: pg_config executable not found. Make sure pg_config is in your path" >&2;}
-   { (exit 1); exit 1; }; }
-else
-    { echo "$as_me:$LINENO: checking PostgreSQL header dir" >&5
-echo $ECHO_N "checking PostgreSQL header dir... $ECHO_C" >&6; }
-    PGINCDIR=`${pgconfig} --includedir`
-    { echo "$as_me:$LINENO: result: $PGINCDIR" >&5
-echo "${ECHO_T}$PGINCDIR" >&6; }
-    { echo "$as_me:$LINENO: checking PostgreSQL library dir" >&5
-echo $ECHO_N "checking PostgreSQL library dir... $ECHO_C" >&6; }
-    PGLIBDIR=`${pgconfig} --libdir`
-    { echo "$as_me:$LINENO: result: $PGLIBDIR" >&5
-echo "${ECHO_T}$PGLIBDIR" >&6; }
-fi
-
-
-
-ac_config_files="$ac_config_files HDBC-postgresql.buildinfo"
-
-cat >confcache <<\_ACEOF
-# This file is a shell script that caches the results of configure
-# tests run on this system so they can be shared between configure
-# scripts and configure runs, see configure's option --config-cache.
-# It is not useful on other systems.  If it contains results you don't
-# want to keep, you may remove or edit it.
-#
-# config.status only pays attention to the cache file if you give it
-# the --recheck option to rerun configure.
-#
-# `ac_cv_env_foo' variables (set or unset) will be overridden when
-# loading this file, other *unset* `ac_cv_foo' will be assigned the
-# following values.
-
-_ACEOF
-
-# The following way of writing the cache mishandles newlines in values,
-# but we know of no workaround that is simple, portable, and efficient.
-# So, we kill variables containing newlines.
-# Ultrix sh set writes to stderr and can't be redirected directly,
-# and sets the high bit in the cache file unless we assign to the vars.
-(
-  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
-    eval ac_val=\$$ac_var
-    case $ac_val in #(
-    *${as_nl}*)
-      case $ac_var in #(
-      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
-echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
-      esac
-      case $ac_var in #(
-      _ | IFS | as_nl) ;; #(
-      *) $as_unset $ac_var ;;
-      esac ;;
-    esac
-  done
-
-  (set) 2>&1 |
-    case $as_nl`(ac_space=' '; set) 2>&1` in #(
-    *${as_nl}ac_space=\ *)
-      # `set' does not quote correctly, so add quotes (double-quote
-      # substitution turns \\\\ into \\, and sed turns \\ into \).
-      sed -n \
-	"s/'/'\\\\''/g;
-	  s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
-      ;; #(
-    *)
-      # `set' quotes correctly as required by POSIX, so do not add quotes.
-      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
-      ;;
-    esac |
-    sort
-) |
-  sed '
-     /^ac_cv_env_/b end
-     t clear
-     :clear
-     s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
-     t end
-     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
-     :end' >>confcache
-if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
-  if test -w "$cache_file"; then
-    test "x$cache_file" != "x/dev/null" &&
-      { echo "$as_me:$LINENO: updating cache $cache_file" >&5
-echo "$as_me: updating cache $cache_file" >&6;}
-    cat confcache >$cache_file
-  else
-    { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5
-echo "$as_me: not updating unwritable cache $cache_file" >&6;}
-  fi
-fi
-rm -f confcache
-
-test "x$prefix" = xNONE && prefix=$ac_default_prefix
-# Let make expand exec_prefix.
-test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
-
-# Transform confdefs.h into DEFS.
-# Protect against shell expansion while executing Makefile rules.
-# Protect against Makefile macro expansion.
-#
-# If the first sed substitution is executed (which looks for macros that
-# take arguments), then branch to the quote section.  Otherwise,
-# look for a macro that doesn't take arguments.
-ac_script='
-t clear
-:clear
-s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 (][^	 (]*([^)]*)\)[	 ]*\(.*\)/-D\1=\2/g
-t quote
-s/^[	 ]*#[	 ]*define[	 ][	 ]*\([^	 ][^	 ]*\)[	 ]*\(.*\)/-D\1=\2/g
-t quote
-b any
-:quote
-s/[	 `~#$^&*(){}\\|;'\''"<>?]/\\&/g
-s/\[/\\&/g
-s/\]/\\&/g
-s/\$/$$/g
-H
-:any
-${
-	g
-	s/^\n//
-	s/\n/ /g
-	p
-}
-'
-DEFS=`sed -n "$ac_script" confdefs.h`
-
-
-ac_libobjs=
-ac_ltlibobjs=
-for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
-  # 1. Remove the extension, and $U if already installed.
-  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
-  ac_i=`echo "$ac_i" | sed "$ac_script"`
-  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
-  #    will be set to the directory where LIBOBJS objects are built.
-  ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext"
-  ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo'
-done
-LIBOBJS=$ac_libobjs
-
-LTLIBOBJS=$ac_ltlibobjs
-
-
-
-: ${CONFIG_STATUS=./config.status}
-ac_clean_files_save=$ac_clean_files
-ac_clean_files="$ac_clean_files $CONFIG_STATUS"
-{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5
-echo "$as_me: creating $CONFIG_STATUS" >&6;}
-cat >$CONFIG_STATUS <<_ACEOF
-#! $SHELL
-# Generated by $as_me.
-# Run this file to recreate the current configuration.
-# Compiler output produced by configure, useful for debugging
-# configure, is in config.log if it exists.
-
-debug=false
-ac_cs_recheck=false
-ac_cs_silent=false
-SHELL=\${CONFIG_SHELL-$SHELL}
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-## --------------------- ##
-## M4sh Initialization.  ##
-## --------------------- ##
-
-# Be more Bourne compatible
-DUALCASE=1; export DUALCASE # for MKS sh
-if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
-  emulate sh
-  NULLCMD=:
-  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
-  # is contrary to our usage.  Disable this feature.
-  alias -g '${1+"$@"}'='"$@"'
-  setopt NO_GLOB_SUBST
-else
-  case `(set -o) 2>/dev/null` in
-  *posix*) set -o posix ;;
-esac
-
-fi
-
-
-
-
-# PATH needs CR
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
-
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  echo "#! /bin/sh" >conf$$.sh
-  echo  "exit 0"   >>conf$$.sh
-  chmod +x conf$$.sh
-  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
-    PATH_SEPARATOR=';'
-  else
-    PATH_SEPARATOR=:
-  fi
-  rm -f conf$$.sh
-fi
-
-# Support unset when possible.
-if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
-  as_unset=unset
-else
-  as_unset=false
-fi
-
-
-# IFS
-# We need space, tab and new line, in precisely that order.  Quoting is
-# there to prevent editors from complaining about space-tab.
-# (If _AS_PATH_WALK were called with IFS unset, it would disable word
-# splitting by setting IFS to empty value.)
-as_nl='
-'
-IFS=" ""	$as_nl"
-
-# Find who we are.  Look in the path if we contain no directory separator.
-case $0 in
-  *[\\/]* ) as_myself=$0 ;;
-  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-done
-IFS=$as_save_IFS
-
-     ;;
-esac
-# We did not find ourselves, most probably we were run as `sh COMMAND'
-# in which case we are not to be found in the path.
-if test "x$as_myself" = x; then
-  as_myself=$0
-fi
-if test ! -f "$as_myself"; then
-  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
-  { (exit 1); exit 1; }
-fi
-
-# Work around bugs in pre-3.0 UWIN ksh.
-for as_var in ENV MAIL MAILPATH
-do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-done
-PS1='$ '
-PS2='> '
-PS4='+ '
-
-# NLS nuisances.
-for as_var in \
-  LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \
-  LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \
-  LC_TELEPHONE LC_TIME
-do
-  if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
-    eval $as_var=C; export $as_var
-  else
-    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
-  fi
-done
-
-# Required to use basename.
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
-  as_basename=basename
-else
-  as_basename=false
-fi
-
-
-# Name of the executable.
-as_me=`$as_basename -- "$0" ||
-$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
-	 X"$0" : 'X\(//\)$' \| \
-	 X"$0" : 'X\(/\)' \| . 2>/dev/null ||
-echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\/\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-
-# CDPATH.
-$as_unset CDPATH
-
-
-
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
-
-  # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
-  # uniformly replaced by the line number.  The first 'sed' inserts a
-  # line-number line after each line using $LINENO; the second 'sed'
-  # does the real work.  The second script uses 'N' to pair each
-  # line-number line with the line containing $LINENO, and appends
-  # trailing '-' during substitution so that $LINENO is not a special
-  # case at line end.
-  # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
-  # scripts with optimization help from Paolo Bonzini.  Blame Lee
-  # E. McMahon (1931-1989) for sed's syntax.  :-)
-  sed -n '
-    p
-    /[$]LINENO/=
-  ' <$as_myself |
-    sed '
-      s/[$]LINENO.*/&-/
-      t lineno
-      b
-      :lineno
-      N
-      :loop
-      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
-      t loop
-      s/-\n.*//
-    ' >$as_me.lineno &&
-  chmod +x "$as_me.lineno" ||
-    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
-   { (exit 1); exit 1; }; }
-
-  # Don't try to exec as it changes $[0], causing all sort of problems
-  # (the dirname of $[0] is not the place where we might find the
-  # original and so on.  Autoconf is especially sensitive to this).
-  . "./$as_me.lineno"
-  # Exit status is that of the last command.
-  exit
-}
-
-
-if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
-  as_dirname=dirname
-else
-  as_dirname=false
-fi
-
-ECHO_C= ECHO_N= ECHO_T=
-case `echo -n x` in
--n*)
-  case `echo 'x\c'` in
-  *c*) ECHO_T='	';;	# ECHO_T is single tab character.
-  *)   ECHO_C='\c';;
-  esac;;
-*)
-  ECHO_N='-n';;
-esac
-
-if expr a : '\(a\)' >/dev/null 2>&1 &&
-   test "X`expr 00001 : '.*\(...\)'`" = X001; then
-  as_expr=expr
-else
-  as_expr=false
-fi
-
-rm -f conf$$ conf$$.exe conf$$.file
-if test -d conf$$.dir; then
-  rm -f conf$$.dir/conf$$.file
-else
-  rm -f conf$$.dir
-  mkdir conf$$.dir
-fi
-echo >conf$$.file
-if ln -s conf$$.file conf$$ 2>/dev/null; then
-  as_ln_s='ln -s'
-  # ... but there are two gotchas:
-  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
-  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
-  # In both cases, we have to default to `cp -p'.
-  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
-    as_ln_s='cp -p'
-elif ln conf$$.file conf$$ 2>/dev/null; then
-  as_ln_s=ln
-else
-  as_ln_s='cp -p'
-fi
-rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
-rmdir conf$$.dir 2>/dev/null
-
-if mkdir -p . 2>/dev/null; then
-  as_mkdir_p=:
-else
-  test -d ./-p && rmdir ./-p
-  as_mkdir_p=false
-fi
-
-if test -x / >/dev/null 2>&1; then
-  as_test_x='test -x'
-else
-  if ls -dL / >/dev/null 2>&1; then
-    as_ls_L_option=L
-  else
-    as_ls_L_option=
-  fi
-  as_test_x='
-    eval sh -c '\''
-      if test -d "$1"; then
-        test -d "$1/.";
-      else
-	case $1 in
-        -*)set "./$1";;
-	esac;
-	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
-	???[sx]*):;;*)false;;esac;fi
-    '\'' sh
-  '
-fi
-as_executable_p=$as_test_x
-
-# Sed expression to map a string onto a valid CPP name.
-as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
-
-# Sed expression to map a string onto a valid variable name.
-as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
-
-
-exec 6>&1
-
-# Save the log message, to keep $[0] and so on meaningful, and to
-# report actual input values of CONFIG_FILES etc. instead of their
-# values after options handling.
-ac_log="
-This file was extended by HDBC-postgresql package $as_me 1.1, which was
-generated by GNU Autoconf 2.61.  Invocation command line was
-
-  CONFIG_FILES    = $CONFIG_FILES
-  CONFIG_HEADERS  = $CONFIG_HEADERS
-  CONFIG_LINKS    = $CONFIG_LINKS
-  CONFIG_COMMANDS = $CONFIG_COMMANDS
-  $ $0 $@
-
-on `(hostname || uname -n) 2>/dev/null | sed 1q`
-"
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<_ACEOF
-# Files that config.status was made for.
-config_files="$ac_config_files"
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-ac_cs_usage="\
-\`$as_me' instantiates files from templates according to the
-current configuration.
-
-Usage: $0 [OPTIONS] [FILE]...
-
-  -h, --help       print this help, then exit
-  -V, --version    print version number and configuration settings, then exit
-  -q, --quiet      do not print progress messages
-  -d, --debug      don't remove temporary files
-      --recheck    update $as_me by reconfiguring in the same conditions
-  --file=FILE[:TEMPLATE]
-		   instantiate the configuration file FILE
-
-Configuration files:
-$config_files
-
-Report bugs to <bug-autoconf@gnu.org>."
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
-ac_cs_version="\\
-HDBC-postgresql package config.status 1.1
-configured by $0, generated by GNU Autoconf 2.61,
-  with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\"
-
-Copyright (C) 2006 Free Software Foundation, Inc.
-This config.status script is free software; the Free Software Foundation
-gives unlimited permission to copy, distribute and modify it."
-
-ac_pwd='$ac_pwd'
-srcdir='$srcdir'
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-# If no file are specified by the user, then we need to provide default
-# value.  By we need to know if files were specified by the user.
-ac_need_defaults=:
-while test $# != 0
-do
-  case $1 in
-  --*=*)
-    ac_option=`expr "X$1" : 'X\([^=]*\)='`
-    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
-    ac_shift=:
-    ;;
-  *)
-    ac_option=$1
-    ac_optarg=$2
-    ac_shift=shift
-    ;;
-  esac
-
-  case $ac_option in
-  # Handling of the options.
-  -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
-    ac_cs_recheck=: ;;
-  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
-    echo "$ac_cs_version"; exit ;;
-  --debug | --debu | --deb | --de | --d | -d )
-    debug=: ;;
-  --file | --fil | --fi | --f )
-    $ac_shift
-    CONFIG_FILES="$CONFIG_FILES $ac_optarg"
-    ac_need_defaults=false;;
-  --he | --h |  --help | --hel | -h )
-    echo "$ac_cs_usage"; exit ;;
-  -q | -quiet | --quiet | --quie | --qui | --qu | --q \
-  | -silent | --silent | --silen | --sile | --sil | --si | --s)
-    ac_cs_silent=: ;;
-
-  # This is an error.
-  -*) { echo "$as_me: error: unrecognized option: $1
-Try \`$0 --help' for more information." >&2
-   { (exit 1); exit 1; }; } ;;
-
-  *) ac_config_targets="$ac_config_targets $1"
-     ac_need_defaults=false ;;
-
-  esac
-  shift
-done
-
-ac_configure_extra_args=
-
-if $ac_cs_silent; then
-  exec 6>/dev/null
-  ac_configure_extra_args="$ac_configure_extra_args --silent"
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
-if \$ac_cs_recheck; then
-  echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6
-  CONFIG_SHELL=$SHELL
-  export CONFIG_SHELL
-  exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
-fi
-
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
-exec 5>>config.log
-{
-  echo
-  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
-## Running $as_me. ##
-_ASBOX
-  echo "$ac_log"
-} >&5
-
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-
-# Handling of arguments.
-for ac_config_target in $ac_config_targets
-do
-  case $ac_config_target in
-    "HDBC-postgresql.buildinfo") CONFIG_FILES="$CONFIG_FILES HDBC-postgresql.buildinfo" ;;
-
-  *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5
-echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
-   { (exit 1); exit 1; }; };;
-  esac
-done
-
-
-# If the user did not use the arguments to specify the items to instantiate,
-# then the envvar interface is used.  Set only those that are not.
-# We use the long form for the default assignment because of an extremely
-# bizarre bug on SunOS 4.1.3.
-if $ac_need_defaults; then
-  test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files
-fi
-
-# Have a temporary directory for convenience.  Make it in the build tree
-# simply because there is no reason against having it here, and in addition,
-# creating and moving files from /tmp can sometimes cause problems.
-# Hook for its removal unless debugging.
-# Note that there is a small window in which the directory will not be cleaned:
-# after its creation but before its name has been assigned to `$tmp'.
-$debug ||
-{
-  tmp=
-  trap 'exit_status=$?
-  { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
-' 0
-  trap '{ (exit 1); exit 1; }' 1 2 13 15
-}
-# Create a (secure) tmp directory for tmp files.
-
-{
-  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
-  test -n "$tmp" && test -d "$tmp"
-}  ||
-{
-  tmp=./conf$$-$RANDOM
-  (umask 077 && mkdir "$tmp")
-} ||
-{
-   echo "$me: cannot create a temporary directory in ." >&2
-   { (exit 1); exit 1; }
-}
-
-#
-# Set up the sed scripts for CONFIG_FILES section.
-#
-
-# No need to generate the scripts if there are no CONFIG_FILES.
-# This happens for instance when ./config.status config.h
-if test -n "$CONFIG_FILES"; then
-
-_ACEOF
-
-
-
-ac_delim='%!_!# '
-for ac_last_try in false false false false false :; do
-  cat >conf$$subs.sed <<_ACEOF
-SHELL!$SHELL$ac_delim
-PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim
-PACKAGE_NAME!$PACKAGE_NAME$ac_delim
-PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim
-PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim
-PACKAGE_STRING!$PACKAGE_STRING$ac_delim
-PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim
-exec_prefix!$exec_prefix$ac_delim
-prefix!$prefix$ac_delim
-program_transform_name!$program_transform_name$ac_delim
-bindir!$bindir$ac_delim
-sbindir!$sbindir$ac_delim
-libexecdir!$libexecdir$ac_delim
-datarootdir!$datarootdir$ac_delim
-datadir!$datadir$ac_delim
-sysconfdir!$sysconfdir$ac_delim
-sharedstatedir!$sharedstatedir$ac_delim
-localstatedir!$localstatedir$ac_delim
-includedir!$includedir$ac_delim
-oldincludedir!$oldincludedir$ac_delim
-docdir!$docdir$ac_delim
-infodir!$infodir$ac_delim
-htmldir!$htmldir$ac_delim
-dvidir!$dvidir$ac_delim
-pdfdir!$pdfdir$ac_delim
-psdir!$psdir$ac_delim
-libdir!$libdir$ac_delim
-localedir!$localedir$ac_delim
-mandir!$mandir$ac_delim
-DEFS!$DEFS$ac_delim
-ECHO_C!$ECHO_C$ac_delim
-ECHO_N!$ECHO_N$ac_delim
-ECHO_T!$ECHO_T$ac_delim
-LIBS!$LIBS$ac_delim
-build_alias!$build_alias$ac_delim
-host_alias!$host_alias$ac_delim
-target_alias!$target_alias$ac_delim
-pgconfig!$pgconfig$ac_delim
-PGINCDIR!$PGINCDIR$ac_delim
-PGLIBDIR!$PGLIBDIR$ac_delim
-LIBOBJS!$LIBOBJS$ac_delim
-LTLIBOBJS!$LTLIBOBJS$ac_delim
-_ACEOF
-
-  if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 42; then
-    break
-  elif $ac_last_try; then
-    { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
-echo "$as_me: error: could not make $CONFIG_STATUS" >&2;}
-   { (exit 1); exit 1; }; }
-  else
-    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
-  fi
-done
-
-ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed`
-if test -n "$ac_eof"; then
-  ac_eof=`echo "$ac_eof" | sort -nru | sed 1q`
-  ac_eof=`expr $ac_eof + 1`
-fi
-
-cat >>$CONFIG_STATUS <<_ACEOF
-cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end
-_ACEOF
-sed '
-s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g
-s/^/s,@/; s/!/@,|#_!!_#|/
-:n
-t n
-s/'"$ac_delim"'$/,g/; t
-s/$/\\/; p
-N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n
-' >>$CONFIG_STATUS <conf$$subs.sed
-rm -f conf$$subs.sed
-cat >>$CONFIG_STATUS <<_ACEOF
-:end
-s/|#_!!_#|//g
-CEOF$ac_eof
-_ACEOF
-
-
-# VPATH may cause trouble with some makes, so we remove $(srcdir),
-# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and
-# trailing colons and then remove the whole line if VPATH becomes empty
-# (actually we leave an empty line to preserve line numbers).
-if test "x$srcdir" = x.; then
-  ac_vpsub='/^[	 ]*VPATH[	 ]*=/{
-s/:*\$(srcdir):*/:/
-s/:*\${srcdir}:*/:/
-s/:*@srcdir@:*/:/
-s/^\([^=]*=[	 ]*\):*/\1/
-s/:*$//
-s/^[^=]*=[	 ]*$//
-}'
-fi
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-fi # test -n "$CONFIG_FILES"
-
-
-for ac_tag in  :F $CONFIG_FILES
-do
-  case $ac_tag in
-  :[FHLC]) ac_mode=$ac_tag; continue;;
-  esac
-  case $ac_mode$ac_tag in
-  :[FHL]*:*);;
-  :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5
-echo "$as_me: error: Invalid tag $ac_tag." >&2;}
-   { (exit 1); exit 1; }; };;
-  :[FH]-) ac_tag=-:-;;
-  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
-  esac
-  ac_save_IFS=$IFS
-  IFS=:
-  set x $ac_tag
-  IFS=$ac_save_IFS
-  shift
-  ac_file=$1
-  shift
-
-  case $ac_mode in
-  :L) ac_source=$1;;
-  :[FH])
-    ac_file_inputs=
-    for ac_f
-    do
-      case $ac_f in
-      -) ac_f="$tmp/stdin";;
-      *) # Look for the file first in the build tree, then in the source tree
-	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
-	 # because $ac_f cannot contain `:'.
-	 test -f "$ac_f" ||
-	   case $ac_f in
-	   [\\/$]*) false;;
-	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
-	   esac ||
-	   { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5
-echo "$as_me: error: cannot find input file: $ac_f" >&2;}
-   { (exit 1); exit 1; }; };;
-      esac
-      ac_file_inputs="$ac_file_inputs $ac_f"
-    done
-
-    # Let's still pretend it is `configure' which instantiates (i.e., don't
-    # use $as_me), people would be surprised to read:
-    #    /* config.h.  Generated by config.status.  */
-    configure_input="Generated from "`IFS=:
-	  echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure."
-    if test x"$ac_file" != x-; then
-      configure_input="$ac_file.  $configure_input"
-      { echo "$as_me:$LINENO: creating $ac_file" >&5
-echo "$as_me: creating $ac_file" >&6;}
-    fi
-
-    case $ac_tag in
-    *:-:* | *:-) cat >"$tmp/stdin";;
-    esac
-    ;;
-  esac
-
-  ac_dir=`$as_dirname -- "$ac_file" ||
-$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$ac_file" : 'X\(//\)[^/]' \| \
-	 X"$ac_file" : 'X\(//\)$' \| \
-	 X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
-echo X"$ac_file" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)[^/].*/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-  { as_dir="$ac_dir"
-  case $as_dir in #(
-  -*) as_dir=./$as_dir;;
-  esac
-  test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
-    as_dirs=
-    while :; do
-      case $as_dir in #(
-      *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
-      *) as_qdir=$as_dir;;
-      esac
-      as_dirs="'$as_qdir' $as_dirs"
-      as_dir=`$as_dirname -- "$as_dir" ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-	 X"$as_dir" : 'X\(//\)[^/]' \| \
-	 X"$as_dir" : 'X\(//\)$' \| \
-	 X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
-echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)[^/].*/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\/\)$/{
-	    s//\1/
-	    q
-	  }
-	  /^X\(\/\).*/{
-	    s//\1/
-	    q
-	  }
-	  s/.*/./; q'`
-      test -d "$as_dir" && break
-    done
-    test -z "$as_dirs" || eval "mkdir $as_dirs"
-  } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
-echo "$as_me: error: cannot create directory $as_dir" >&2;}
-   { (exit 1); exit 1; }; }; }
-  ac_builddir=.
-
-case "$ac_dir" in
-.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
-*)
-  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
-  # A ".." for each directory in $ac_dir_suffix.
-  ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
-  case $ac_top_builddir_sub in
-  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
-  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
-  esac ;;
-esac
-ac_abs_top_builddir=$ac_pwd
-ac_abs_builddir=$ac_pwd$ac_dir_suffix
-# for backward compatibility:
-ac_top_builddir=$ac_top_build_prefix
-
-case $srcdir in
-  .)  # We are building in place.
-    ac_srcdir=.
-    ac_top_srcdir=$ac_top_builddir_sub
-    ac_abs_top_srcdir=$ac_pwd ;;
-  [\\/]* | ?:[\\/]* )  # Absolute name.
-    ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir
-    ac_abs_top_srcdir=$srcdir ;;
-  *) # Relative name.
-    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_build_prefix$srcdir
-    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
-esac
-ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
-
-
-  case $ac_mode in
-  :F)
-  #
-  # CONFIG_FILE
-  #
-
-_ACEOF
-
-cat >>$CONFIG_STATUS <<\_ACEOF
-# If the template does not know about datarootdir, expand it.
-# FIXME: This hack should be removed a few years after 2.60.
-ac_datarootdir_hack=; ac_datarootdir_seen=
-
-case `sed -n '/datarootdir/ {
-  p
-  q
-}
-/@datadir@/p
-/@docdir@/p
-/@infodir@/p
-/@localedir@/p
-/@mandir@/p
-' $ac_file_inputs` in
-*datarootdir*) ac_datarootdir_seen=yes;;
-*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
-  { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
-echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
-_ACEOF
-cat >>$CONFIG_STATUS <<_ACEOF
-  ac_datarootdir_hack='
-  s&@datadir@&$datadir&g
-  s&@docdir@&$docdir&g
-  s&@infodir@&$infodir&g
-  s&@localedir@&$localedir&g
-  s&@mandir@&$mandir&g
-    s&\\\${datarootdir}&$datarootdir&g' ;;
-esac
-_ACEOF
-
-# Neutralize VPATH when `$srcdir' = `.'.
-# Shell code in configure.ac might set extrasub.
-# FIXME: do we really want to maintain this feature?
-cat >>$CONFIG_STATUS <<_ACEOF
-  sed "$ac_vpsub
-$extrasub
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
-:t
-/@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-s&@configure_input@&$configure_input&;t t
-s&@top_builddir@&$ac_top_builddir_sub&;t t
-s&@srcdir@&$ac_srcdir&;t t
-s&@abs_srcdir@&$ac_abs_srcdir&;t t
-s&@top_srcdir@&$ac_top_srcdir&;t t
-s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
-s&@builddir@&$ac_builddir&;t t
-s&@abs_builddir@&$ac_abs_builddir&;t t
-s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
-$ac_datarootdir_hack
-" $ac_file_inputs | sed -f "$tmp/subs-1.sed" >$tmp/out
-
-test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
-  { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
-  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
-  { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined.  Please make sure it is defined." >&5
-echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
-which seems to be undefined.  Please make sure it is defined." >&2;}
-
-  rm -f "$tmp/stdin"
-  case $ac_file in
-  -) cat "$tmp/out"; rm -f "$tmp/out";;
-  *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;;
-  esac
- ;;
-
-
-
-  esac
-
-done # for ac_tag
-
-
-{ (exit 0); exit 0; }
-_ACEOF
-chmod +x $CONFIG_STATUS
-ac_clean_files=$ac_clean_files_save
-
-
-# configure is writing to config.log, and then calls config.status.
-# config.status does its own redirection, appending to config.log.
-# Unfortunately, on DOS this fails, as config.log is still kept open
-# by configure, so config.status won't be able to write to it; its
-# output is simply discarded.  So we exec the FD to /dev/null,
-# effectively closing config.log, so it can be properly (re)opened and
-# appended to by config.status.  When coming back to configure, we
-# need to make the FD available again.
-if test "$no_create" != yes; then
-  ac_cs_success=:
-  ac_config_status_args=
-  test "$silent" = yes &&
-    ac_config_status_args="$ac_config_status_args --quiet"
-  exec 5>/dev/null
-  $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false
-  exec 5>>config.log
-  # Use ||, not &&, to avoid exiting from the if with $? = 1, which
-  # would make configure fail if this is the last instruction.
-  $ac_cs_success || { (exit 1); exit 1; }
-fi
-
diff --git a/configure.ac b/configure.ac
deleted file mode 100644
--- a/configure.ac
+++ /dev/null
@@ -1,21 +0,0 @@
-AC_INIT([HDBC-postgresql package], [1.1])
-
-# Safety check: Ensure that we are in the correct source directory.
-AC_CONFIG_SRCDIR([HDBC-postgresql.cabal])
-
-AC_PATH_PROG(pgconfig,pg_config)
-if test [ -z "$pgconfig" ]; then
-    AC_MSG_ERROR([pg_config executable not found. Make sure pg_config is in your path])
-else
-    AC_MSG_CHECKING([PostgreSQL header dir])
-    PGINCDIR=`${pgconfig} --includedir`
-    AC_MSG_RESULT([$PGINCDIR])
-    AC_MSG_CHECKING([PostgreSQL library dir])
-    PGLIBDIR=`${pgconfig} --libdir`
-    AC_MSG_RESULT([$PGLIBDIR])
-fi
-
-AC_SUBST([PGINCDIR])
-AC_SUBST([PGLIBDIR])
-AC_CONFIG_FILES([HDBC-postgresql.buildinfo])
-AC_OUTPUT
diff --git a/hdbc-postgresql-helper.c b/hdbc-postgresql-helper.c
deleted file mode 100644
--- a/hdbc-postgresql-helper.c
+++ /dev/null
@@ -1,64 +0,0 @@
-#include <libpq-fe.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include "hdbc-postgresql-helper.h"
-
-/* Things can't finalize more than once.  
-We'd like to let people call them from the app.
-Yet we'd also like to be able to have a ForeignPtr finalize them.
-
-So, here's a little wrapper for things. */
-
-void PQfinish_conditional_finalizer(finalizeonce *conn);
-
-finalizeonce *wrapobjpg(void *obj, finalizeonce *parentobj) {
-  finalizeonce *newobj;
-  newobj = malloc(sizeof(finalizeonce));
-  if (newobj == NULL) {
-    fprintf(stderr, "HDBC: could not allocate wrapper!\n");
-    return NULL;
-  }
-  newobj->isfinalized = 0;
-  newobj->refcount = 1;
-  newobj->encapobj = obj;
-  newobj->parent = parentobj;
-  if (parentobj != NULL) 
-    parentobj->refcount++;
-  return newobj;
-}
-  
-void PQfinish_app(finalizeonce *conn) {
-  if (conn->isfinalized)
-    return;
-  PQfinish((PGconn *) (conn->encapobj));
-  conn->isfinalized = 1;
-}
-
-void PQfinish_finalizer(finalizeonce *conn) {
-  (conn->refcount)--;
-  PQfinish_conditional_finalizer(conn);
-}
-
-void PQfinish_conditional_finalizer(finalizeonce *conn) {
-  if (conn->refcount < 1) {
-    PQfinish_app(conn);
-    free(conn);
-  }
-}
-
-void PQclear_app(finalizeonce *res) {
-  if (res->isfinalized)
-    return;
-  PQclear((PGresult *) (res->encapobj));
-  res->isfinalized = 1;
-}
-
-void PQclear_finalizer(finalizeonce *res) {
-  PQclear_app(res);
-  (res->refcount)--;            /* Not really important since this is never a 
-                                   parent */
-  (res->parent->refcount)--;
-  PQfinish_conditional_finalizer(res->parent);
-  free(res);
-}
-
diff --git a/hdbc-postgresql-helper.h b/hdbc-postgresql-helper.h
deleted file mode 100644
--- a/hdbc-postgresql-helper.h
+++ /dev/null
@@ -1,16 +0,0 @@
-#include <libpq-fe.h>
-
-typedef struct TAG_finalizeonce {
-  void *encapobj;
-  int refcount;
-  int isfinalized;
-  struct TAG_finalizeonce *parent;
-} finalizeonce;
-
-extern finalizeonce *wrapobjpg(void *obj, finalizeonce *parentobj);
-
-extern void PQfinish_app(finalizeonce *conn);
-extern void PQfinish_finalizer(finalizeonce *conn);
-
-extern void PQclear_app(finalizeonce *res);
-extern void PQclear_finalizer(finalizeonce *res);
diff --git a/pgtypes.h b/pgtypes.h
deleted file mode 100644
--- a/pgtypes.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/* File:			pgtypes.h
- *
- * Description:		See "pgtypes.c"
- *
- * Comments:		See "notice.txt" for copyright and license information.
- *
- */
-
-#ifndef __PGTYPES_H__
-#define __PGTYPES_H__
-
-/* the type numbers are defined by the OID's of the types' rows */
-/* in table pg_type */
-
-
-#if 0
-#define PG_TYPE_LO				????	/* waiting for permanent type */
-#endif
-
-#define PG_TYPE_BOOL			16
-#define PG_TYPE_BYTEA			17
-#define PG_TYPE_CHAR			18
-#define PG_TYPE_NAME			19
-#define PG_TYPE_INT8			20
-#define PG_TYPE_INT2			21
-#define PG_TYPE_INT2VECTOR		22
-#define PG_TYPE_INT4			23
-#define PG_TYPE_REGPROC			24
-#define PG_TYPE_TEXT			25
-#define PG_TYPE_OID				26
-#define PG_TYPE_TID				27
-#define PG_TYPE_XID				28
-#define PG_TYPE_CID				29
-#define PG_TYPE_OIDVECTOR		30
-#define PG_TYPE_SET				32
-#define PG_TYPE_CHAR2			409
-#define PG_TYPE_CHAR4			410
-#define PG_TYPE_CHAR8			411
-#define PG_TYPE_POINT			600
-#define PG_TYPE_LSEG			601
-#define PG_TYPE_PATH			602
-#define PG_TYPE_BOX				603
-#define PG_TYPE_POLYGON			604
-#define PG_TYPE_FILENAME		605
-#define PG_TYPE_FLOAT4			700
-#define PG_TYPE_FLOAT8			701
-#define PG_TYPE_ABSTIME			702
-#define PG_TYPE_RELTIME			703
-#define PG_TYPE_TINTERVAL		704
-#define PG_TYPE_UNKNOWN			705
-#define PG_TYPE_MONEY			790
-#define PG_TYPE_OIDINT2			810
-#define PG_TYPE_OIDINT4			910
-#define PG_TYPE_OIDNAME			911
-#define PG_TYPE_BPCHAR			1042
-#define PG_TYPE_VARCHAR			1043
-#define PG_TYPE_DATE			1082
-#define PG_TYPE_TIME			1083
-#define PG_TYPE_TIMESTAMP_NO_TMZONE	1114		/* since 7.2 */
-#define PG_TYPE_DATETIME		1184
-#define PG_TYPE_TIME_WITH_TMZONE	1266		/* since 7.1 */
-#define PG_TYPE_TIMESTAMP		1296	/* deprecated since 7.0 */
-#define PG_TYPE_NUMERIC			1700
-#define INTERNAL_ASIS_TYPE		(-9999)
-
-#endif
diff --git a/pgtypes_internal.h b/pgtypes_internal.h
new file mode 100644
--- /dev/null
+++ b/pgtypes_internal.h
@@ -0,0 +1,77 @@
+/* File:			pgtypes.h
+ *
+ * Description:		See "pgtypes.c"
+ *
+ * Comments:		See "notice.txt" for copyright and license information.
+ *
+ */
+
+#ifndef __PGTYPES_H__
+#define __PGTYPES_H__
+
+/* the type numbers are defined by the OID's of the types' rows */
+/* in table pg_type */
+
+
+#ifdef NOT_USED
+#define PG_TYPE_LO				????	/* waiting for permanent type */
+#endif
+
+#define	MS_ACCESS_SERIAL		"int identity"
+#define PG_TYPE_BOOL			16
+#define PG_TYPE_BYTEA			17
+#define PG_TYPE_CHAR			18
+#define PG_TYPE_NAME			19
+#define PG_TYPE_INT8			20
+#define PG_TYPE_INT2			21
+#define PG_TYPE_INT2VECTOR		22
+#define PG_TYPE_INT4			23
+#define PG_TYPE_REGPROC			24
+#define PG_TYPE_TEXT			25
+#define PG_TYPE_OID				26
+#define PG_TYPE_TID				27
+#define PG_TYPE_XID				28
+#define PG_TYPE_CID				29
+#define PG_TYPE_OIDVECTOR		30
+#define PG_TYPE_SET				32
+#define PG_TYPE_XML			142
+#define PG_TYPE_XMLARRAY		143
+#define PG_TYPE_CHAR2			409
+#define PG_TYPE_CHAR4			410
+#define PG_TYPE_CHAR8			411
+#define PG_TYPE_POINT			600
+#define PG_TYPE_LSEG			601
+#define PG_TYPE_PATH			602
+#define PG_TYPE_BOX				603
+#define PG_TYPE_POLYGON			604
+#define PG_TYPE_FILENAME		605
+#define PG_TYPE_CIDR			650
+#define PG_TYPE_FLOAT4			700
+#define PG_TYPE_FLOAT8			701
+#define PG_TYPE_ABSTIME			702
+#define PG_TYPE_RELTIME			703
+#define PG_TYPE_TINTERVAL		704
+#define PG_TYPE_UNKNOWN			705
+#define PG_TYPE_MONEY			790
+#define PG_TYPE_OIDINT2			810
+#define PG_TYPE_MACADDR			829
+#define PG_TYPE_INET			869
+#define PG_TYPE_OIDINT4			910
+#define PG_TYPE_OIDNAME			911
+#define PG_TYPE_TEXTARRAY		1009
+#define PG_TYPE_BPCHARARRAY		1014
+#define PG_TYPE_VARCHARARRAY		1015
+#define PG_TYPE_BPCHAR			1042
+#define PG_TYPE_VARCHAR			1043
+#define PG_TYPE_DATE			1082
+#define PG_TYPE_TIME			1083
+#define PG_TYPE_TIMESTAMP_NO_TMZONE	1114		/* since 7.2 */
+#define PG_TYPE_DATETIME		1184
+#define PG_TYPE_TIME_WITH_TMZONE	1266		/* since 7.1 */
+#define PG_TYPE_TIMESTAMP		1296	/* deprecated since 7.0 */
+#define PG_TYPE_NUMERIC			1700
+#define PG_TYPE_RECORD			2249
+#define PG_TYPE_VOID			2278
+#define INTERNAL_ASIS_TYPE		(-9999)
+
+#endif
diff --git a/testsrc/SpecificDB.hs b/testsrc/SpecificDB.hs
new file mode 100644
--- /dev/null
+++ b/testsrc/SpecificDB.hs
@@ -0,0 +1,25 @@
+module SpecificDB where
+import Database.HDBC
+import Database.HDBC.PostgreSQL
+import Database.HDBC.PostgreSQL.Parser(convertSQL)
+import Test.HUnit
+
+connectDB = 
+    handleSqlError (do dbh <- connectPostgreSQL ""
+                       run dbh "SET client_min_messages=WARNING" []
+                       return dbh)
+
+dateTimeTypeOfSqlValue :: SqlValue -> String
+dateTimeTypeOfSqlValue (SqlLocalDate _) = "date"
+dateTimeTypeOfSqlValue (SqlLocalTimeOfDay _) = "time without time zone"
+dateTimeTypeOfSqlValue (SqlZonedLocalTimeOfDay _ _) = "time with time zone"
+dateTimeTypeOfSqlValue (SqlLocalTime _) = "timestamp without time zone"
+dateTimeTypeOfSqlValue (SqlZonedTime _) = "timestamp with time zone"
+dateTimeTypeOfSqlValue (SqlUTCTime _) = "timestamp with time zone"
+dateTimeTypeOfSqlValue (SqlDiffTime _) = "interval"
+dateTimeTypeOfSqlValue (SqlPOSIXTime _) = "numeric"
+dateTimeTypeOfSqlValue (SqlEpochTime _) = "integer"
+dateTimeTypeOfSqlValue (SqlTimeDiff _) = "interval"
+dateTimeTypeOfSqlValue _ = "text"
+
+supportsFracTime = True
diff --git a/testsrc/SpecificDBTests.hs b/testsrc/SpecificDBTests.hs
new file mode 100644
--- /dev/null
+++ b/testsrc/SpecificDBTests.hs
@@ -0,0 +1,24 @@
+module SpecificDBTests where
+import Database.HDBC
+import Database.HDBC.PostgreSQL
+import Database.HDBC.PostgreSQL.Parser(convertSQL)
+import Test.HUnit
+
+testp inp exp = TestCase $
+    case convertSQL inp of
+      Right x -> assertEqual "" exp x
+      Left y -> assertFailure $ show y
+
+tests = TestList 
+        [TestLabel "empty" (testp "" ""),
+         TestLabel "simple" (testp "SELECT a from b WHERE c = ?"
+                                   "SELECT a from b WHERE c = $1"),
+         TestLabel "multi" (testp "INSERT INTO foo VALUES (?,?)"
+                                  "INSERT INTO foo VALUES ($1,$2)"),
+         TestLabel "literal" (testp "INSERT INTO foo VALUES ('?', '''?')"
+                                    "INSERT INTO foo VALUES ('?', '''?')"),
+         TestLabel "torture" 
+           (testp "-- really?\n-- yes'?\nINSERT INTO ? VALUES ('', ?, \"?asd\", '?\\'?', '?''?', /* foo? */ /* foo /* bar */ ? */ ?)"
+                  "-- really?\n-- yes'?\nINSERT INTO $1 VALUES ('', $2, \"?asd\", '?\\'?', '?''?', /* foo? */ /* foo /* bar */ ? */ $3)")
+           ] 
+                  
diff --git a/testsrc/TestMisc.hs b/testsrc/TestMisc.hs
new file mode 100644
--- /dev/null
+++ b/testsrc/TestMisc.hs
@@ -0,0 +1,180 @@
+module TestMisc(tests, setup) where
+import Test.HUnit
+import Database.HDBC
+import TestUtils
+import System.IO
+import Control.Exception
+import Data.Char
+import Control.Monad
+import qualified Data.Map as Map
+
+rowdata = 
+    [[SqlInt32 0, toSql "Testing", SqlNull],
+     [SqlInt32 1, toSql "Foo", SqlInt32 5],
+     [SqlInt32 2, toSql "Bar", SqlInt32 9]]
+
+colnames = ["testid", "teststring", "testint"]
+alrows :: [[(String, SqlValue)]]
+alrows = map (zip colnames) rowdata
+
+setup f = dbTestCase $ \dbh ->
+   do run dbh "CREATE TABLE hdbctest2 (testid INTEGER PRIMARY KEY NOT NULL, teststring TEXT, testint INTEGER)" []
+      sth <- prepare dbh "INSERT INTO hdbctest2 VALUES (?, ?, ?)"
+      executeMany sth rowdata
+      commit dbh
+      finally (f dbh)
+              (do run dbh "DROP TABLE hdbctest2" []
+                  commit dbh
+              )
+
+cloneTest dbh a =
+    do dbh2 <- clone dbh
+       finally (handleSqlError (a dbh2))
+               (handleSqlError (disconnect dbh2))
+
+testgetColumnNames = setup $ \dbh ->
+   do sth <- prepare dbh "SELECT * from hdbctest2"
+      execute sth []
+      cols <- getColumnNames sth
+      finish sth
+      ["testid", "teststring", "testint"] @=? map (map toLower) cols
+
+testdescribeResult = setup $ \dbh -> when (not ((hdbcDriverName dbh) `elem`
+                                               ["sqlite3"])) $
+   do sth <- prepare dbh "SELECT * from hdbctest2"
+      execute sth []
+      cols <- describeResult sth
+      ["testid", "teststring", "testint"] @=? map (map toLower . fst) cols
+      let coldata = map snd cols
+      assertBool "r0 type" (colType (coldata !! 0) `elem`
+                            [SqlBigIntT, SqlIntegerT])
+      assertBool "r1 type" (colType (coldata !! 1) `elem`
+                            [SqlVarCharT, SqlLongVarCharT])
+      assertBool "r2 type" (colType (coldata !! 2) `elem`
+                            [SqlBigIntT, SqlIntegerT])
+      finish sth
+
+testdescribeTable = setup $ \dbh -> when (not ((hdbcDriverName dbh) `elem`
+                                               ["sqlite3"])) $
+   do cols <- describeTable dbh "hdbctest2"
+      ["testid", "teststring", "testint"] @=? map (map toLower . fst) cols
+      let coldata = map snd cols
+      assertBool "r0 type" (colType (coldata !! 0) `elem`
+                            [SqlBigIntT, SqlIntegerT])
+      assertEqual "r0 nullable" (Just False) (colNullable (coldata !! 0))
+      assertBool "r1 type" (colType (coldata !! 1) `elem`
+                            [SqlVarCharT, SqlLongVarCharT])
+      assertEqual "r1 nullable" (Just True) (colNullable (coldata !! 1))
+      assertBool "r2 type" (colType (coldata !! 2) `elem`
+                           [SqlBigIntT, SqlIntegerT])
+      assertEqual "r2 nullable" (Just True) (colNullable (coldata !! 2))
+
+testquickQuery = setup $ \dbh ->
+    do results <- quickQuery dbh "SELECT * from hdbctest2 ORDER BY testid" []
+       rowdata @=? results
+
+testfetchRowAL = setup $ \dbh ->
+    do sth <- prepare dbh "SELECT * from hdbctest2 ORDER BY testid" 
+       execute sth []
+       fetchRowAL sth >>= (Just (head alrows) @=?)
+       fetchRowAL sth >>= (Just (alrows !! 1) @=?)
+       fetchRowAL sth >>= (Just (alrows !! 2) @=?)
+       fetchRowAL sth >>= (Nothing @=?)
+       finish sth
+
+testfetchRowMap = setup $ \dbh ->
+    do sth <- prepare dbh "SELECT * from hdbctest2 ORDER BY testid" 
+       execute sth []
+       fetchRowMap sth >>= (Just (Map.fromList $ head alrows) @=?)
+       fetchRowMap sth >>= (Just (Map.fromList $ alrows !! 1) @=?)
+       fetchRowMap sth >>= (Just (Map.fromList $ alrows !! 2) @=?)
+       fetchRowMap sth >>= (Nothing @=?)
+       finish sth
+
+testfetchAllRowsAL = setup $ \dbh ->
+    do sth <- prepare dbh "SELECT * from hdbctest2 ORDER BY testid"
+       execute sth []
+       fetchAllRowsAL sth >>= (alrows @=?)
+
+testfetchAllRowsMap = setup $ \dbh ->
+    do sth <- prepare dbh "SELECT * from hdbctest2 ORDER BY testid"
+       execute sth []
+       fetchAllRowsMap sth >>= (map (Map.fromList) alrows @=?)
+
+testexception = setup $ \dbh ->
+    catchSql (do sth <- prepare dbh "SELECT invalidcol FROM hdbctest2"
+                 execute sth []
+                 assertFailure "No exception was raised"
+             )
+             (\e -> commit dbh)
+
+testrowcount = setup $ \dbh ->
+    do r <- run dbh "UPDATE hdbctest2 SET testint = 25 WHERE testid = 20" []
+       assertEqual "UPDATE with no change" 0 r
+       r <- run dbh "UPDATE hdbctest2 SET testint = 26 WHERE testid = 0" []
+       assertEqual "UPDATE with 1 change" 1 r
+       r <- run dbh "UPDATE hdbctest2 SET testint = 27 WHERE testid <> 0" []
+       assertEqual "UPDATE with 2 changes" 2 r
+       commit dbh
+       res <- quickQuery dbh "SELECT * from hdbctest2 ORDER BY testid" []
+       assertEqual "final results"
+         [[SqlInt32 0, toSql "Testing", SqlInt32 26],
+          [SqlInt32 1, toSql "Foo", SqlInt32 27],
+          [SqlInt32 2, toSql "Bar", SqlInt32 27]] res
+                       
+{- Since we might be running against a live DB, we can't look at a specific
+list here (though a SpecificDB test case may be able to).  We can ensure
+that our test table is, or is not, present, as appropriate. -}
+                                      
+testgetTables1 = setup $ \dbh ->
+    do r <- getTables dbh
+       True @=? "hdbctest2" `elem` r
+
+testgetTables2 = dbTestCase $ \dbh ->
+    do r <- getTables dbh
+       False @=? "hdbctest2" `elem` r
+
+testclone = setup $ \dbho -> cloneTest dbho $ \dbh ->
+    do results <- quickQuery dbh "SELECT * from hdbctest2 ORDER BY testid" []
+       rowdata @=? results
+
+testnulls = setup $ \dbh ->
+    do let dn = hdbcDriverName dbh
+       when (not (dn `elem` ["postgresql", "odbc"])) (
+          do sth <- prepare dbh "INSERT INTO hdbctest2 VALUES (?, ?, ?)"
+             executeMany sth rows
+             finish sth
+             res <- quickQuery dbh "SELECT * from hdbctest2 WHERE testid > 99 ORDER BY testid" []
+             seq (length res) rows @=? res
+                                             )
+    where rows = [[SqlInt32 100, SqlString "foo\NULbar", SqlNull],
+                  [SqlInt32 101, SqlString "bar\NUL", SqlNull],
+                  [SqlInt32 102, SqlString "\NUL", SqlNull],
+                  [SqlInt32 103, SqlString "\xFF", SqlNull],
+                  [SqlInt32 104, SqlString "regular", SqlNull]]
+       
+testunicode = setup $ \dbh ->
+      do sth <- prepare dbh "INSERT INTO hdbctest2 VALUES (?, ?, ?)"
+         executeMany sth rows
+         finish sth
+         res <- quickQuery dbh "SELECT * from hdbctest2 WHERE testid > 99 ORDER BY testid" []
+         seq (length res) rows @=? res
+    where rows = [[SqlInt32 100, SqlString "foo\x263a", SqlNull],
+                  [SqlInt32 101, SqlString "bar\x00A3", SqlNull],
+                  [SqlInt32 102, SqlString (take 263 (repeat 'a')), SqlNull]]
+
+tests = TestList [TestLabel "getColumnNames" testgetColumnNames,
+                  TestLabel "describeResult" testdescribeResult,
+                  TestLabel "describeTable" testdescribeTable,
+                  TestLabel "quickQuery" testquickQuery,
+                  TestLabel "fetchRowAL" testfetchRowAL,
+                  TestLabel "fetchRowMap" testfetchRowMap,
+                  TestLabel "fetchAllRowsAL" testfetchAllRowsAL,
+                  TestLabel "fetchAllRowsMap" testfetchAllRowsMap,
+                  TestLabel "sql exception" testexception,
+                  TestLabel "clone" testclone,
+                  TestLabel "update rowcount" testrowcount,
+                  TestLabel "get tables1" testgetTables1,
+                  TestLabel "get tables2" testgetTables2,
+                  TestLabel "nulls" testnulls,
+                  TestLabel "unicode" testunicode]
diff --git a/testsrc/TestSbasics.hs b/testsrc/TestSbasics.hs
new file mode 100644
--- /dev/null
+++ b/testsrc/TestSbasics.hs
@@ -0,0 +1,184 @@
+module TestSbasics(tests) where
+import Test.HUnit
+import Data.Convertible (convert)
+import Data.List
+import Data.Time (UTCTime(UTCTime), fromGregorian)
+import Database.HDBC
+import TestUtils
+import System.IO
+import Control.Exception
+
+openClosedb = sqlTestCase $ 
+    do dbh <- connectDB
+       disconnect dbh
+
+multiFinish = dbTestCase (\dbh ->
+    do sth <- prepare dbh "SELECT 1 + 1"
+       sExecute sth []
+       finish sth
+       finish sth
+       finish sth
+                          )
+
+runRawTest = dbTestCase (\dbh ->
+    do runRaw dbh "CREATE TABLE valid1 (a int); CREATE TABLE valid2 (a int)"
+       tables <- getTables dbh
+       assertBool "valid1 table not created!" ("valid1" `elem` tables)
+       assertBool "valid2 table not created!" ("valid2" `elem` tables)
+                        )
+
+runRawErrorTest = dbTestCase (\dbh ->
+    let expected = "ERROR:  syntax error at or near \"INVALID\""
+    in do err <- (runRaw dbh "CREATE TABLE valid1 (a int); INVALID" >> return "No error") `catchSql`
+                 (return . seErrorMsg)
+          assertBool "Error message inappropriate" (expected `isInfixOf` err)
+          rollback dbh
+          tables <- getTables dbh
+          assertBool "valid1 table created!" (not $ "valid1" `elem` tables)
+                             )
+
+
+basicQueries = dbTestCase (\dbh ->
+    do sth <- prepare dbh "SELECT 1 + 1"
+       sExecute sth []
+       sFetchRow sth >>= (assertEqual "row 1" (Just [Just "2"]))
+       sFetchRow sth >>= (assertEqual "last row" Nothing)
+                          )
+    
+createTable = dbTestCase (\dbh ->
+    do sRun dbh "CREATE TABLE hdbctest1 (testname VARCHAR(20), testid INTEGER, testint INTEGER, testtext TEXT)" []
+       commit dbh
+                         )
+
+dropTable = dbTestCase (\dbh ->
+    do sRun dbh "DROP TABLE hdbctest1" []
+       commit dbh
+                       )
+
+runReplace = dbTestCase (\dbh ->
+    do sRun dbh "INSERT INTO hdbctest1 VALUES (?, ?, ?, ?)" r1
+       sRun dbh "INSERT INTO hdbctest1 VALUES (?, ?, 2, ?)" r2
+       commit dbh
+       sth <- prepare dbh "SELECT * FROM hdbctest1 WHERE testname = 'runReplace' ORDER BY testid"
+       sExecute sth []
+       sFetchRow sth >>= (assertEqual "r1" (Just r1))
+       sFetchRow sth >>= (assertEqual "r2" (Just [Just "runReplace", Just "2",
+                                                 Just "2", Nothing]))
+       sFetchRow sth >>= (assertEqual "lastrow" Nothing)
+                       )
+    where r1 = [Just "runReplace", Just "1", Just "1234", Just "testdata"]
+          r2 = [Just "runReplace", Just "2", Nothing]
+
+executeReplace = dbTestCase (\dbh ->
+    do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('executeReplace',?,?,?)"
+       sExecute sth [Just "1", Just "1234", Just "Foo"]
+       sExecute sth [Just "2", Nothing, Just "Bar"]
+       commit dbh
+       sth <- prepare dbh "SELECT * FROM hdbctest1 WHERE testname = ? ORDER BY testid"
+       sExecute sth [Just "executeReplace"]
+       sFetchRow sth >>= (assertEqual "r1" 
+                         (Just $ map Just ["executeReplace", "1", "1234", 
+                                           "Foo"]))
+       sFetchRow sth >>= (assertEqual "r2"
+                         (Just [Just "executeReplace", Just "2", Nothing,
+                                Just "Bar"]))
+       sFetchRow sth >>= (assertEqual "lastrow" Nothing)
+                            )
+
+testExecuteMany = dbTestCase (\dbh ->
+    do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('multi',?,?,?)"
+       sExecuteMany sth rows
+       commit dbh
+       sth <- prepare dbh "SELECT testid, testint, testtext FROM hdbctest1 WHERE testname = 'multi'"
+       sExecute sth []
+       mapM_ (\r -> sFetchRow sth >>= (assertEqual "" (Just r))) rows
+       sFetchRow sth >>= (assertEqual "lastrow" Nothing)
+                          )
+    where rows = [map Just ["1", "1234", "foo"],
+                  map Just ["2", "1341", "bar"],
+                  [Just "3", Nothing, Nothing]]
+
+testsFetchAllRows = dbTestCase (\dbh ->
+    do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('sFetchAllRows', ?, NULL, NULL)"
+       sExecuteMany sth rows
+       commit dbh
+       sth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'sFetchAllRows' ORDER BY testid"
+       sExecute sth []
+       results <- sFetchAllRows sth
+       assertEqual "" rows results
+                               )
+    where rows = map (\x -> [Just . show $ x]) [1..9]
+
+basicTransactions = dbTestCase (\dbh ->
+    do assertBool "Connected database does not support transactions; skipping transaction test" (dbTransactionSupport dbh)
+       sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('basicTransactions', ?, NULL, NULL)"
+       sExecute sth [Just "0"]
+       commit dbh
+       qrysth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'basicTransactions' ORDER BY testid"
+       sExecute qrysth []
+       sFetchAllRows qrysth >>= (assertEqual "initial commit" [[Just "0"]])
+
+       -- Now try a rollback
+       sExecuteMany sth rows
+       rollback dbh
+       sExecute qrysth []
+       sFetchAllRows qrysth >>= (assertEqual "rollback" [[Just "0"]])
+
+       -- Now try another commit
+       sExecuteMany sth rows
+       commit dbh
+       sExecute qrysth []
+       sFetchAllRows qrysth >>= (assertEqual "final commit" ([Just "0"]:rows))
+                               )
+    where rows = map (\x -> [Just . show $ x]) [1..9]
+
+testWithTransaction = dbTestCase (\dbh ->
+    do assertBool "Connected database does not support transactions; skipping transaction test" (dbTransactionSupport dbh)
+       sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('withTransaction', ?, NULL, NULL)"
+       sExecute sth [Just "0"]
+       commit dbh
+       qrysth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'withTransaction' ORDER BY testid"
+       sExecute qrysth []
+       sFetchAllRows qrysth >>= (assertEqual "initial commit" [[Just "0"]])
+       
+       -- Let's try a rollback.
+       catch (withTransaction dbh (\_ -> do sExecuteMany sth rows
+                                            fail "Foo"))
+             (\SomeException{} -> return ())
+       sExecute qrysth []
+       sFetchAllRows qrysth >>= (assertEqual "rollback" [[Just "0"]])
+
+       -- And now a commit.
+       withTransaction dbh (\_ -> sExecuteMany sth rows)
+       sExecute qrysth []
+       sFetchAllRows qrysth >>= (assertEqual "final commit" ([Just "0"]:rows))
+                               )
+    where rows = map (\x -> [Just . show $ x]) [1..9]
+       
+testFirstCentury = dbTestCase $ \dbh ->
+  do -- we use UTC to avoid Local Mean Time which the 'time' library can't handle
+     runRaw dbh "SET TIMEZONE TO 'UTC';"
+     select <- prepare dbh "SELECT ? :: timestamptz;"
+     let time = UTCTime (fromGregorian 99 12 25) 0
+     execute select [toSql (convert time :: SqlValue)]
+     result <- fetchAllRows select
+     assertEqual "first century year can roundtrip"
+                 time (fromSql $ head $ head result)
+
+tests = TestList
+        [
+         TestLabel "openClosedb" openClosedb,
+         TestLabel "multiFinish" multiFinish,
+         TestLabel "runRawTest" runRawTest,
+         TestLabel "runRawErrorTest" runRawErrorTest,
+         TestLabel "basicQueries" basicQueries,
+         TestLabel "createTable" createTable,
+         TestLabel "runReplace" runReplace,
+         TestLabel "executeReplace" executeReplace,
+         TestLabel "executeMany" testExecuteMany,
+         TestLabel "sFetchAllRows" testsFetchAllRows,
+         TestLabel "basicTransactions" basicTransactions,
+         TestLabel "withTransaction" testWithTransaction,
+         TestLabel "dropTable" dropTable,
+         TestLabel "firstCentury" testFirstCentury
+         ]
diff --git a/testsrc/TestTime.hs b/testsrc/TestTime.hs
new file mode 100644
--- /dev/null
+++ b/testsrc/TestTime.hs
@@ -0,0 +1,119 @@
+{-# LANGUAGE FlexibleContexts, CPP #-}
+
+module TestTime(tests) where
+import Test.HUnit
+import Database.HDBC
+import TestUtils
+import Control.Exception
+import Data.Time (UTCTime, Day, NominalDiffTime)
+import Data.Time.LocalTime
+import Data.Time.Clock.POSIX
+import Data.Maybe
+import Data.Convertible
+import SpecificDB
+#ifdef MIN_TIME_15
+import Data.Time (parseTimeM, defaultTimeLocale)
+#else
+import Data.Time (parseTime)
+import System.Locale(defaultTimeLocale)
+#endif
+import Database.HDBC.Locale (iso8601DateFormat)
+import qualified System.Time as ST
+
+instance Eq ZonedTime where
+    a == b = zonedTimeToUTC a == zonedTimeToUTC b
+
+testZonedTime :: ZonedTime
+testZonedTime = fromJust $ parseTime' defaultTimeLocale (iso8601DateFormat (Just "%T %z"))
+                 "1989-08-01 15:33:01 -0500"
+
+testZonedTimeFrac :: ZonedTime
+testZonedTimeFrac = fromJust $ parseTime' defaultTimeLocale (iso8601DateFormat (Just "%T%Q %z"))
+                    "1989-08-01 15:33:01.536 -0500"
+
+
+rowdata t = [[SqlInt32 100, toSql t, SqlNull]]
+
+testDTType :: (Convertible SqlValue a, Show b, Eq b) =>
+    a
+    -> (a -> SqlValue)
+    -> (a -> b)
+    -> Test
+testDTType inputdata convToSqlValue toComparable = dbTestCase $ \dbh ->
+    do run dbh ("CREATE TABLE hdbctesttime (testid INTEGER PRIMARY KEY NOT NULL, testvalue " ++ dateTimeTypeOfSqlValue value ++ ")") []
+       commit dbh
+       finally (testIt dbh) (do commit dbh
+                                run dbh "DROP TABLE hdbctesttime" []
+                                commit dbh
+                            )
+    where testIt dbh =
+              do run dbh "INSERT INTO hdbctesttime (testid, testvalue) VALUES (?, ?)"
+                     [iToSql 5, value]
+                 commit dbh
+                 r <- quickQuery' dbh "SELECT testid, testvalue FROM hdbctesttime" []
+                 case r of
+                   [[testidsv, testvaluesv]] -> 
+                       do assertEqual "testid" (5::Int) (fromSql testidsv)
+                          assertEqual "testvalue"
+                                (toComparable inputdata)
+                                (toComparable$ fromSql testvaluesv)
+          value = convToSqlValue inputdata
+
+mkTest label inputdata convfunc toComparable =
+    TestLabel label (testDTType inputdata convfunc toComparable)
+
+tests = TestList $
+    ((TestLabel "Non-frac" $ testIt testZonedTime) :
+     if supportsFracTime then [TestLabel "Frac" $ testIt testZonedTimeFrac] else [])
+
+testIt baseZonedTime =
+  TestList [ mkTest "Day"            baseDay            toSql      id
+           , mkTest "TimeOfDay"      baseTimeOfDay      toSql      id
+           , mkTest "ZonedTimeOfDay" baseZonedTimeOfDay toSql      id
+           , mkTest "LocalTime"      baseLocalTime      toSql      id
+           , mkTest "ZonedTime"      baseZonedTime      toSql      id
+           , mkTest "UTCTime"        baseUTCTime        toSql      id
+           , mkTest "DiffTime"       baseDiffTime       toSql      id
+           , mkTest "POSIXTime"      basePOSIXTime      posixToSql id
+           , mkTest "ClockTime"      baseClockTime      toSql      id
+           , mkTest "CalendarTime"   baseCalendarTime   toSql      ST.toClockTime
+           , mkTest "TimeDiff"       baseTimeDiff       toSql      id
+           ]
+ where
+      baseDay :: Day
+      baseDay = localDay baseLocalTime
+
+      baseTimeOfDay :: TimeOfDay
+      baseTimeOfDay = localTimeOfDay baseLocalTime
+
+      baseZonedTimeOfDay :: (TimeOfDay, TimeZone)
+      baseZonedTimeOfDay = fromSql (SqlZonedTime baseZonedTime)
+
+      baseLocalTime :: LocalTime
+      baseLocalTime = zonedTimeToLocalTime baseZonedTime
+
+      baseUTCTime :: UTCTime
+      baseUTCTime = convert baseZonedTime
+
+      baseDiffTime :: NominalDiffTime
+      baseDiffTime = basePOSIXTime
+
+      basePOSIXTime :: POSIXTime
+      basePOSIXTime = convert baseZonedTime
+
+      baseTimeDiff :: ST.TimeDiff
+      baseTimeDiff = convert baseDiffTime
+
+      -- No fractional parts for these two
+
+      baseClockTime :: ST.ClockTime
+      baseClockTime = convert testZonedTime
+
+      baseCalendarTime :: ST.CalendarTime
+      baseCalendarTime = convert testZonedTime
+
+#if MIN_TIME_15
+parseTime' = parseTimeM True
+#else
+parseTime' = parseTime
+#endif
diff --git a/testsrc/TestUtils.hs b/testsrc/TestUtils.hs
new file mode 100644
--- /dev/null
+++ b/testsrc/TestUtils.hs
@@ -0,0 +1,25 @@
+module TestUtils(connectDB, sqlTestCase, dbTestCase, printDBInfo) where
+import Database.HDBC
+import Test.HUnit
+import Control.Exception
+import SpecificDB(connectDB)
+
+sqlTestCase a = 
+    TestCase (handleSqlError a)
+
+dbTestCase a =
+    TestCase (do dbh <- connectDB
+                 finally (handleSqlError (a dbh))
+                         (handleSqlError (disconnect dbh))
+             )
+
+printDBInfo = handleSqlError $
+    do dbh <- connectDB
+       putStrLn "+-------------------------------------------------------------------------"
+       putStrLn $ "| Testing HDBC database module: " ++ hdbcDriverName dbh ++
+                ", bound to client: " ++ hdbcClientVer dbh
+       putStrLn $ "| Proxied driver: " ++ proxiedClientName dbh ++
+                ", bound to version: " ++ proxiedClientVer dbh
+       putStrLn $ "| Connected to server version: " ++ dbServerVer dbh
+       putStrLn "+-------------------------------------------------------------------------\n"
+       disconnect dbh
diff --git a/testsrc/Testbasics.hs b/testsrc/Testbasics.hs
new file mode 100644
--- /dev/null
+++ b/testsrc/Testbasics.hs
@@ -0,0 +1,168 @@
+module Testbasics(tests) where
+import Test.HUnit
+import Database.HDBC
+import TestUtils
+import System.IO
+import Control.Exception
+
+openClosedb = sqlTestCase $ 
+    do dbh <- connectDB
+       disconnect dbh
+
+multiFinish = dbTestCase (\dbh ->
+    do sth <- prepare dbh "SELECT 1 + 1"
+       r <- execute sth []
+       assertEqual "basic count" 0 r
+       finish sth
+       finish sth
+       finish sth
+                          )
+
+basicQueries = dbTestCase (\dbh ->
+    do sth <- prepare dbh "SELECT 1 + 1"
+       execute sth [] >>= (0 @=?)
+       r <- fetchAllRows sth
+       assertEqual "converted from" [["2"]] (map (map fromSql) r)
+       assertEqual "int32 compare" [[SqlInt32 2]] r
+       assertEqual "iToSql compare" [[iToSql 2]] r
+       assertEqual "num compare" [[toSql (2::Int)]] r
+       assertEqual "nToSql compare" [[nToSql (2::Int)]] r
+       assertEqual "string compare" [[SqlString "2"]] r
+                          )
+    
+createTable = dbTestCase (\dbh ->
+    do run dbh "CREATE TABLE hdbctest1 (testname VARCHAR(20), testid INTEGER, testint INTEGER, testtext TEXT)" []
+       commit dbh
+                         )
+
+dropTable = dbTestCase (\dbh ->
+    do run dbh "DROP TABLE hdbctest1" []
+       commit dbh
+                       )
+
+runReplace = dbTestCase (\dbh ->
+    do r <- run dbh "INSERT INTO hdbctest1 VALUES (?, ?, ?, ?)" r1
+       assertEqual "insert retval" 1 r
+       run dbh "INSERT INTO hdbctest1 VALUES (?, ?, ?, ?)" r2
+       commit dbh
+       sth <- prepare dbh "SELECT * FROM hdbctest1 WHERE testname = 'runReplace' ORDER BY testid"
+       rv2 <- execute sth []
+       assertEqual "select retval" 0 rv2
+       r <- fetchAllRows sth
+       assertEqual "" [r1, r2] r
+                       )
+    where r1 = [toSql "runReplace", iToSql 1, iToSql 1234, SqlString "testdata"] 
+          r2 = [toSql "runReplace", iToSql 2, iToSql 2, SqlNull]
+
+executeReplace = dbTestCase (\dbh ->
+    do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('executeReplace',?,?,?)"
+       execute sth [iToSql 1, iToSql 1234, toSql "Foo"]
+       execute sth [SqlInt32 2, SqlNull, toSql "Bar"]
+       commit dbh
+       sth <- prepare dbh "SELECT * FROM hdbctest1 WHERE testname = ? ORDER BY testid"
+       execute sth [SqlString "executeReplace"]
+       r <- fetchAllRows sth
+       assertEqual "result"
+                   [[toSql "executeReplace", iToSql 1, toSql "1234",
+                     toSql "Foo"],
+                    [toSql "executeReplace", iToSql 2, SqlNull,
+                     toSql "Bar"]]
+                   r
+                            )
+
+testExecuteMany = dbTestCase (\dbh ->
+    do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('multi',?,?,?)"
+       executeMany sth rows
+       commit dbh
+       sth <- prepare dbh "SELECT testid, testint, testtext FROM hdbctest1 WHERE testname = 'multi'"
+       execute sth []
+       r <- fetchAllRows sth
+       assertEqual "" rows r
+                          )
+    where rows = [map toSql ["1", "1234", "foo"],
+                  map toSql ["2", "1341", "bar"],
+                  [toSql "3", SqlNull, SqlNull]]
+
+testFetchAllRows = dbTestCase (\dbh ->
+    do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('sFetchAllRows', ?, NULL, NULL)"
+       executeMany sth rows
+       commit dbh
+       sth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'sFetchAllRows' ORDER BY testid"
+       execute sth []
+       results <- fetchAllRows sth
+       assertEqual "" rows results
+                               )
+    where rows = map (\x -> [iToSql x]) [1..9]
+
+testFetchAllRows' = dbTestCase (\dbh ->
+    do sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('sFetchAllRows2', ?, NULL, NULL)"
+       executeMany sth rows
+       commit dbh
+       sth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'sFetchAllRows2' ORDER BY testid"
+       execute sth []
+       results <- fetchAllRows' sth
+       assertEqual "" rows results
+                               )
+    where rows = map (\x -> [iToSql x]) [1..9]
+
+basicTransactions = dbTestCase (\dbh ->
+    do assertBool "Connected database does not support transactions; skipping transaction test" (dbTransactionSupport dbh)
+       sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('basicTransactions', ?, NULL, NULL)"
+       execute sth [iToSql 0]
+       commit dbh
+       qrysth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'basicTransactions' ORDER BY testid"
+       execute qrysth []
+       fetchAllRows qrysth >>= (assertEqual "initial commit" [[toSql "0"]])
+
+       -- Now try a rollback
+       executeMany sth rows
+       rollback dbh
+       execute qrysth []
+       fetchAllRows qrysth >>= (assertEqual "rollback" [[toSql "0"]])
+
+       -- Now try another commit
+       executeMany sth rows
+       commit dbh
+       execute qrysth []
+       fetchAllRows qrysth >>= (assertEqual "final commit" ([SqlString "0"]:rows))
+                               )
+    where rows = map (\x -> [iToSql $ x]) [1..9]
+
+testWithTransaction = dbTestCase (\dbh ->
+    do assertBool "Connected database does not support transactions; skipping transaction test" (dbTransactionSupport dbh)
+       sth <- prepare dbh "INSERT INTO hdbctest1 VALUES ('withTransaction', ?, NULL, NULL)"
+       execute sth [toSql "0"]
+       commit dbh
+       qrysth <- prepare dbh "SELECT testid FROM hdbctest1 WHERE testname = 'withTransaction' ORDER BY testid"
+       execute qrysth []
+       fetchAllRows qrysth >>= (assertEqual "initial commit" [[toSql "0"]])
+       
+       -- Let's try a rollback.
+       catch (withTransaction dbh (\_ -> do executeMany sth rows
+                                            fail "Foo"))
+             (\SomeException{} -> return ())
+       execute qrysth []
+       fetchAllRows qrysth >>= (assertEqual "rollback" [[SqlString "0"]])
+
+       -- And now a commit.
+       withTransaction dbh (\_ -> executeMany sth rows)
+       execute qrysth []
+       fetchAllRows qrysth >>= (assertEqual "final commit" ([iToSql 0]:rows))
+                               )
+    where rows = map (\x -> [iToSql x]) [1..9]
+       
+tests = TestList
+        [
+         TestLabel "openClosedb" openClosedb,
+         TestLabel "multiFinish" multiFinish,
+         TestLabel "basicQueries" basicQueries,
+         TestLabel "createTable" createTable,
+         TestLabel "runReplace" runReplace,
+         TestLabel "executeReplace" executeReplace,
+         TestLabel "executeMany" testExecuteMany,
+         TestLabel "fetchAllRows" testFetchAllRows,
+         TestLabel "fetchAllRows'" testFetchAllRows',
+         TestLabel "basicTransactions" basicTransactions,
+         TestLabel "withTransaction" testWithTransaction,
+         TestLabel "dropTable" dropTable
+         ]
diff --git a/testsrc/Tests.hs b/testsrc/Tests.hs
new file mode 100644
--- /dev/null
+++ b/testsrc/Tests.hs
@@ -0,0 +1,19 @@
+{- arch-tag: Tests main file
+-}
+
+module Tests(tests) where
+import Test.HUnit
+import qualified Testbasics
+import qualified TestSbasics
+import qualified SpecificDBTests
+import qualified TestMisc
+import qualified TestTime
+
+test1 = TestCase ("x" @=? "x")
+
+tests = TestList [TestLabel "test1" test1,
+                  TestLabel "String basics" TestSbasics.tests,
+                  TestLabel "SqlValue basics" Testbasics.tests,
+                  TestLabel "SpecificDB" SpecificDBTests.tests,
+                  TestLabel "Misc tests" TestMisc.tests,
+                  TestLabel "Time tests" TestTime.tests]
diff --git a/testsrc/runtests.hs b/testsrc/runtests.hs
new file mode 100644
--- /dev/null
+++ b/testsrc/runtests.hs
@@ -0,0 +1,12 @@
+{- arch-tag: Test runner
+-}
+
+module Main where 
+
+import Test.HUnit
+import Tests
+import TestUtils
+
+main = do printDBInfo
+          runTestTT tests
+
