changeset 11394:9aee227e296c octave-forge

Populated new database package with initial postgresql interface.
author i7tiol
date Wed, 16 Jan 2013 06:17:06 +0000
parents 9d08a26e57b5
children 2198c4408ed0
files main/database/COPYING main/database/DESCRIPTION main/database/INDEX main/database/NEWS main/database/doc/README main/database/doc/README-postgresql main/database/doc/dev-postgresql/conversions.tex main/database/doc/dev-postgresql/timeformats.txt main/database/inst/__all_db_opts__.m main/database/inst/getdbopts.m main/database/inst/pq_connect.m main/database/inst/setdbopts.m main/database/src/Makefile.in main/database/src/__pq_connect__.cc main/database/src/autogen.sh main/database/src/command.cc main/database/src/command.h main/database/src/configure.ac main/database/src/converters.cc main/database/src/converters.h main/database/src/converters_arr_comp.cc main/database/src/pq_close.cc main/database/src/pq_connection.cc main/database/src/pq_connection.h main/database/src/pq_exec.cc main/database/src/pq_lo.cc main/database/src/pq_update_types.cc
diffstat 27 files changed, 5066 insertions(+), 16 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/COPYING	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,719 @@
+Appendix G GNU GENERAL PUBLIC LICENSE
+*************************************
+
+                        Version 3, 29 June 2007
+
+     Copyright (C) 2007 Free Software Foundation, Inc. `http://fsf.org/'
+
+     Everyone is permitted to copy and distribute verbatim copies of this
+     license document, but changing it is not allowed.
+
+Preamble
+========
+
+The GNU General Public License is a free, copyleft license for software
+and other kinds of works.
+
+   The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains
+free software for all its users.  We, the Free Software Foundation, use
+the GNU General Public License for most of our software; it applies
+also to any other work released this way by its authors.  You can apply
+it to your programs, too.
+
+   When we speak of free software, we are referring to freedom, 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
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+   To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you
+have certain responsibilities if you distribute copies of the software,
+or if you modify it: responsibilities to respect the freedom of others.
+
+   For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+   Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+   For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+   Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the
+manufacturer can do so.  This is fundamentally incompatible with the
+aim of protecting users' freedom to change the software.  The
+systematic pattern of such abuse occurs in the area of products for
+individuals to use, which is precisely where it is most unacceptable.
+Therefore, we have designed this version of the GPL to prohibit the
+practice for those products.  If such problems arise substantially in
+other domains, we stand ready to extend this provision to those domains
+in future versions of the GPL, as needed to protect the freedom of
+users.
+
+   Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+   The precise terms and conditions for copying, distribution and
+modification follow.
+
+TERMS AND CONDITIONS
+====================
+
+  0. Definitions.
+
+     "This License" refers to version 3 of the GNU General Public
+     License.
+
+     "Copyright" also means copyright-like laws that apply to other
+     kinds of works, such as semiconductor masks.
+
+     "The Program" refers to any copyrightable work licensed under this
+     License.  Each licensee is addressed as "you".  "Licensees" and
+     "recipients" may be individuals or organizations.
+
+     To "modify" a work means to copy from or adapt all or part of the
+     work in a fashion requiring copyright permission, other than the
+     making of an exact copy.  The resulting work is called a "modified
+     version" of the earlier work or a work "based on" the earlier work.
+
+     A "covered work" means either the unmodified Program or a work
+     based on the Program.
+
+     To "propagate" a work means to do anything with it that, without
+     permission, would make you directly or secondarily liable for
+     infringement under applicable copyright law, except executing it
+     on a computer or modifying a private copy.  Propagation includes
+     copying, distribution (with or without modification), making
+     available to the public, and in some countries other activities as
+     well.
+
+     To "convey" a work means any kind of propagation that enables other
+     parties to make or receive copies.  Mere interaction with a user
+     through a computer network, with no transfer of a copy, is not
+     conveying.
+
+     An interactive user interface displays "Appropriate Legal Notices"
+     to the extent that it includes a convenient and prominently visible
+     feature that (1) displays an appropriate copyright notice, and (2)
+     tells the user that there is no warranty for the work (except to
+     the extent that warranties are provided), that licensees may
+     convey the work under this License, and how to view a copy of this
+     License.  If the interface presents a list of user commands or
+     options, such as a menu, a prominent item in the list meets this
+     criterion.
+
+  1. Source Code.
+
+     The "source code" for a work means the preferred form of the work
+     for making modifications to it.  "Object code" means any
+     non-source form of a work.
+
+     A "Standard Interface" means an interface that either is an
+     official standard defined by a recognized standards body, or, in
+     the case of interfaces specified for a particular programming
+     language, one that is widely used among developers working in that
+     language.
+
+     The "System Libraries" of an executable work include anything,
+     other than the work as a whole, that (a) is included in the normal
+     form of packaging a Major Component, but which is not part of that
+     Major Component, and (b) serves only to enable use of the work
+     with that Major Component, or to implement a Standard Interface
+     for which an implementation is available to the public in source
+     code form.  A "Major Component", in this context, means a major
+     essential component (kernel, window system, and so on) of the
+     specific operating system (if any) on which the executable work
+     runs, or a compiler used to produce the work, or an object code
+     interpreter used to run it.
+
+     The "Corresponding Source" for a work in object code form means all
+     the source code needed to generate, install, and (for an executable
+     work) run the object code and to modify the work, including
+     scripts to control those activities.  However, it does not include
+     the work's System Libraries, or general-purpose tools or generally
+     available free programs which are used unmodified in performing
+     those activities but which are not part of the work.  For example,
+     Corresponding Source includes interface definition files
+     associated with source files for the work, and the source code for
+     shared libraries and dynamically linked subprograms that the work
+     is specifically designed to require, such as by intimate data
+     communication or control flow between those subprograms and other
+     parts of the work.
+
+     The Corresponding Source need not include anything that users can
+     regenerate automatically from other parts of the Corresponding
+     Source.
+
+     The Corresponding Source for a work in source code form is that
+     same work.
+
+  2. Basic Permissions.
+
+     All rights granted under this License are granted for the term of
+     copyright on the Program, and are irrevocable provided the stated
+     conditions are met.  This License explicitly affirms your unlimited
+     permission to run the unmodified Program.  The output from running
+     a covered work is covered by this License only if the output,
+     given its content, constitutes a covered work.  This License
+     acknowledges your rights of fair use or other equivalent, as
+     provided by copyright law.
+
+     You may make, run and propagate covered works that you do not
+     convey, without conditions so long as your license otherwise
+     remains in force.  You may convey covered works to others for the
+     sole purpose of having them make modifications exclusively for
+     you, or provide you with facilities for running those works,
+     provided that you comply with the terms of this License in
+     conveying all material for which you do not control copyright.
+     Those thus making or running the covered works for you must do so
+     exclusively on your behalf, under your direction and control, on
+     terms that prohibit them from making any copies of your
+     copyrighted material outside their relationship with you.
+
+     Conveying under any other circumstances is permitted solely under
+     the conditions stated below.  Sublicensing is not allowed; section
+     10 makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+     No covered work shall be deemed part of an effective technological
+     measure under any applicable law fulfilling obligations under
+     article 11 of the WIPO copyright treaty adopted on 20 December
+     1996, or similar laws prohibiting or restricting circumvention of
+     such measures.
+
+     When you convey a covered work, you waive any legal power to forbid
+     circumvention of technological measures to the extent such
+     circumvention is effected by exercising rights under this License
+     with respect to the covered work, and you disclaim any intention
+     to limit operation or modification of the work as a means of
+     enforcing, against the work's users, your or third parties' legal
+     rights to forbid circumvention of technological measures.
+
+  4. Conveying Verbatim Copies.
+
+     You may convey verbatim copies of the Program's source code as you
+     receive it, in any medium, provided that you conspicuously and
+     appropriately publish on each copy an appropriate copyright notice;
+     keep intact all notices stating that this License and any
+     non-permissive terms added in accord with section 7 apply to the
+     code; keep intact all notices of the absence of any warranty; and
+     give all recipients a copy of this License along with the Program.
+
+     You may charge any price or no price for each copy that you convey,
+     and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+     You may convey a work based on the Program, or the modifications to
+     produce it from the Program, in the form of source code under the
+     terms of section 4, provided that you also meet all of these
+     conditions:
+
+       a. The work must carry prominent notices stating that you
+          modified it, and giving a relevant date.
+
+       b. The work must carry prominent notices stating that it is
+          released under this License and any conditions added under
+          section 7.  This requirement modifies the requirement in
+          section 4 to "keep intact all notices".
+
+       c. You must license the entire work, as a whole, under this
+          License to anyone who comes into possession of a copy.  This
+          License will therefore apply, along with any applicable
+          section 7 additional terms, to the whole of the work, and all
+          its parts, regardless of how they are packaged.  This License
+          gives no permission to license the work in any other way, but
+          it does not invalidate such permission if you have separately
+          received it.
+
+       d. If the work has interactive user interfaces, each must display
+          Appropriate Legal Notices; however, if the Program has
+          interactive interfaces that do not display Appropriate Legal
+          Notices, your work need not make them do so.
+
+     A compilation of a covered work with other separate and independent
+     works, which are not by their nature extensions of the covered
+     work, and which are not combined with it such as to form a larger
+     program, in or on a volume of a storage or distribution medium, is
+     called an "aggregate" if the compilation and its resulting
+     copyright are not used to limit the access or legal rights of the
+     compilation's users beyond what the individual works permit.
+     Inclusion of a covered work in an aggregate does not cause this
+     License to apply to the other parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+     You may convey a covered work in object code form under the terms
+     of sections 4 and 5, provided that you also convey the
+     machine-readable Corresponding Source under the terms of this
+     License, in one of these ways:
+
+       a. Convey the object code in, or embodied in, a physical product
+          (including a physical distribution medium), accompanied by the
+          Corresponding Source fixed on a durable physical medium
+          customarily used for software interchange.
+
+       b. Convey the object code in, or embodied in, a physical product
+          (including a physical distribution medium), accompanied by a
+          written offer, valid for at least three years and valid for
+          as long as you offer spare parts or customer support for that
+          product model, to give anyone who possesses the object code
+          either (1) a copy of the Corresponding Source for all the
+          software in the product that is covered by this License, on a
+          durable physical medium customarily used for software
+          interchange, for a price no more than your reasonable cost of
+          physically performing this conveying of source, or (2) access
+          to copy the Corresponding Source from a network server at no
+          charge.
+
+       c. Convey individual copies of the object code with a copy of
+          the written offer to provide the Corresponding Source.  This
+          alternative is allowed only occasionally and noncommercially,
+          and only if you received the object code with such an offer,
+          in accord with subsection 6b.
+
+       d. Convey the object code by offering access from a designated
+          place (gratis or for a charge), and offer equivalent access
+          to the Corresponding Source in the same way through the same
+          place at no further charge.  You need not require recipients
+          to copy the Corresponding Source along with the object code.
+          If the place to copy the object code is a network server, the
+          Corresponding Source may be on a different server (operated
+          by you or a third party) that supports equivalent copying
+          facilities, provided you maintain clear directions next to
+          the object code saying where to find the Corresponding Source.
+          Regardless of what server hosts the Corresponding Source, you
+          remain obligated to ensure that it is available for as long
+          as needed to satisfy these requirements.
+
+       e. Convey the object code using peer-to-peer transmission,
+          provided you inform other peers where the object code and
+          Corresponding Source of the work are being offered to the
+          general public at no charge under subsection 6d.
+
+
+     A separable portion of the object code, whose source code is
+     excluded from the Corresponding Source as a System Library, need
+     not be included in conveying the object code work.
+
+     A "User Product" is either (1) a "consumer product", which means
+     any tangible personal property which is normally used for personal,
+     family, or household purposes, or (2) anything designed or sold for
+     incorporation into a dwelling.  In determining whether a product
+     is a consumer product, doubtful cases shall be resolved in favor of
+     coverage.  For a particular product received by a particular user,
+     "normally used" refers to a typical or common use of that class of
+     product, regardless of the status of the particular user or of the
+     way in which the particular user actually uses, or expects or is
+     expected to use, the product.  A product is a consumer product
+     regardless of whether the product has substantial commercial,
+     industrial or non-consumer uses, unless such uses represent the
+     only significant mode of use of the product.
+
+     "Installation Information" for a User Product means any methods,
+     procedures, authorization keys, or other information required to
+     install and execute modified versions of a covered work in that
+     User Product from a modified version of its Corresponding Source.
+     The information must suffice to ensure that the continued
+     functioning of the modified object code is in no case prevented or
+     interfered with solely because modification has been made.
+
+     If you convey an object code work under this section in, or with,
+     or specifically for use in, a User Product, and the conveying
+     occurs as part of a transaction in which the right of possession
+     and use of the User Product is transferred to the recipient in
+     perpetuity or for a fixed term (regardless of how the transaction
+     is characterized), the Corresponding Source conveyed under this
+     section must be accompanied by the Installation Information.  But
+     this requirement does not apply if neither you nor any third party
+     retains the ability to install modified object code on the User
+     Product (for example, the work has been installed in ROM).
+
+     The requirement to provide Installation Information does not
+     include a requirement to continue to provide support service,
+     warranty, or updates for a work that has been modified or
+     installed by the recipient, or for the User Product in which it
+     has been modified or installed.  Access to a network may be denied
+     when the modification itself materially and adversely affects the
+     operation of the network or violates the rules and protocols for
+     communication across the network.
+
+     Corresponding Source conveyed, and Installation Information
+     provided, in accord with this section must be in a format that is
+     publicly documented (and with an implementation available to the
+     public in source code form), and must require no special password
+     or key for unpacking, reading or copying.
+
+  7. Additional Terms.
+
+     "Additional permissions" are terms that supplement the terms of
+     this License by making exceptions from one or more of its
+     conditions.  Additional permissions that are applicable to the
+     entire Program shall be treated as though they were included in
+     this License, to the extent that they are valid under applicable
+     law.  If additional permissions apply only to part of the Program,
+     that part may be used separately under those permissions, but the
+     entire Program remains governed by this License without regard to
+     the additional permissions.
+
+     When you convey a copy of a covered work, you may at your option
+     remove any additional permissions from that copy, or from any part
+     of it.  (Additional permissions may be written to require their own
+     removal in certain cases when you modify the work.)  You may place
+     additional permissions on material, added by you to a covered work,
+     for which you have or can give appropriate copyright permission.
+
+     Notwithstanding any other provision of this License, for material
+     you add to a covered work, you may (if authorized by the copyright
+     holders of that material) supplement the terms of this License
+     with terms:
+
+       a. Disclaiming warranty or limiting liability differently from
+          the terms of sections 15 and 16 of this License; or
+
+       b. Requiring preservation of specified reasonable legal notices
+          or author attributions in that material or in the Appropriate
+          Legal Notices displayed by works containing it; or
+
+       c. Prohibiting misrepresentation of the origin of that material,
+          or requiring that modified versions of such material be
+          marked in reasonable ways as different from the original
+          version; or
+
+       d. Limiting the use for publicity purposes of names of licensors
+          or authors of the material; or
+
+       e. Declining to grant rights under trademark law for use of some
+          trade names, trademarks, or service marks; or
+
+       f. Requiring indemnification of licensors and authors of that
+          material by anyone who conveys the material (or modified
+          versions of it) with contractual assumptions of liability to
+          the recipient, for any liability that these contractual
+          assumptions directly impose on those licensors and authors.
+
+     All other non-permissive additional terms are considered "further
+     restrictions" within the meaning of section 10.  If the Program as
+     you received it, or any part of it, contains a notice stating that
+     it is governed by this License along with a term that is a further
+     restriction, you may remove that term.  If a license document
+     contains a further restriction but permits relicensing or
+     conveying under this License, you may add to a covered work
+     material governed by the terms of that license document, provided
+     that the further restriction does not survive such relicensing or
+     conveying.
+
+     If you add terms to a covered work in accord with this section, you
+     must place, in the relevant source files, a statement of the
+     additional terms that apply to those files, or a notice indicating
+     where to find the applicable terms.
+
+     Additional terms, permissive or non-permissive, may be stated in
+     the form of a separately written license, or stated as exceptions;
+     the above requirements apply either way.
+
+  8. Termination.
+
+     You may not propagate or modify a covered work except as expressly
+     provided under this License.  Any attempt otherwise to propagate or
+     modify it is void, and will automatically terminate your rights
+     under this License (including any patent licenses granted under
+     the third paragraph of section 11).
+
+     However, if you cease all violation of this License, then your
+     license from a particular copyright holder is reinstated (a)
+     provisionally, unless and until the copyright holder explicitly
+     and finally terminates your license, and (b) permanently, if the
+     copyright holder fails to notify you of the violation by some
+     reasonable means prior to 60 days after the cessation.
+
+     Moreover, your license from a particular copyright holder is
+     reinstated permanently if the copyright holder notifies you of the
+     violation by some reasonable means, this is the first time you have
+     received notice of violation of this License (for any work) from
+     that copyright holder, and you cure the violation prior to 30 days
+     after your receipt of the notice.
+
+     Termination of your rights under this section does not terminate
+     the licenses of parties who have received copies or rights from
+     you under this License.  If your rights have been terminated and
+     not permanently reinstated, you do not qualify to receive new
+     licenses for the same material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+     You are not required to accept this License in order to receive or
+     run a copy of the Program.  Ancillary propagation of a covered work
+     occurring solely as a consequence of using peer-to-peer
+     transmission to receive a copy likewise does not require
+     acceptance.  However, nothing other than this License grants you
+     permission to propagate or modify any covered work.  These actions
+     infringe copyright if you do not accept this License.  Therefore,
+     by modifying or propagating a covered work, you indicate your
+     acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+     Each time you convey a covered work, the recipient automatically
+     receives a license from the original licensors, to run, modify and
+     propagate that work, subject to this License.  You are not
+     responsible for enforcing compliance by third parties with this
+     License.
+
+     An "entity transaction" is a transaction transferring control of an
+     organization, or substantially all assets of one, or subdividing an
+     organization, or merging organizations.  If propagation of a
+     covered work results from an entity transaction, each party to that
+     transaction who receives a copy of the work also receives whatever
+     licenses to the work the party's predecessor in interest had or
+     could give under the previous paragraph, plus a right to
+     possession of the Corresponding Source of the work from the
+     predecessor in interest, if the predecessor has it or can get it
+     with reasonable efforts.
+
+     You may not impose any further restrictions on the exercise of the
+     rights granted or affirmed under this License.  For example, you
+     may not impose a license fee, royalty, or other charge for
+     exercise of rights granted under this License, and you may not
+     initiate litigation (including a cross-claim or counterclaim in a
+     lawsuit) alleging that any patent claim is infringed by making,
+     using, selling, offering for sale, or importing the Program or any
+     portion of it.
+
+ 11. Patents.
+
+     A "contributor" is a copyright holder who authorizes use under this
+     License of the Program or a work on which the Program is based.
+     The work thus licensed is called the contributor's "contributor
+     version".
+
+     A contributor's "essential patent claims" are all patent claims
+     owned or controlled by the contributor, whether already acquired or
+     hereafter acquired, that would be infringed by some manner,
+     permitted by this License, of making, using, or selling its
+     contributor version, but do not include claims that would be
+     infringed only as a consequence of further modification of the
+     contributor version.  For purposes of this definition, "control"
+     includes the right to grant patent sublicenses in a manner
+     consistent with the requirements of this License.
+
+     Each contributor grants you a non-exclusive, worldwide,
+     royalty-free patent license under the contributor's essential
+     patent claims, to make, use, sell, offer for sale, import and
+     otherwise run, modify and propagate the contents of its
+     contributor version.
+
+     In the following three paragraphs, a "patent license" is any
+     express agreement or commitment, however denominated, not to
+     enforce a patent (such as an express permission to practice a
+     patent or covenant not to sue for patent infringement).  To
+     "grant" such a patent license to a party means to make such an
+     agreement or commitment not to enforce a patent against the party.
+
+     If you convey a covered work, knowingly relying on a patent
+     license, and the Corresponding Source of the work is not available
+     for anyone to copy, free of charge and under the terms of this
+     License, through a publicly available network server or other
+     readily accessible means, then you must either (1) cause the
+     Corresponding Source to be so available, or (2) arrange to deprive
+     yourself of the benefit of the patent license for this particular
+     work, or (3) arrange, in a manner consistent with the requirements
+     of this License, to extend the patent license to downstream
+     recipients.  "Knowingly relying" means you have actual knowledge
+     that, but for the patent license, your conveying the covered work
+     in a country, or your recipient's use of the covered work in a
+     country, would infringe one or more identifiable patents in that
+     country that you have reason to believe are valid.
+
+     If, pursuant to or in connection with a single transaction or
+     arrangement, you convey, or propagate by procuring conveyance of, a
+     covered work, and grant a patent license to some of the parties
+     receiving the covered work authorizing them to use, propagate,
+     modify or convey a specific copy of the covered work, then the
+     patent license you grant is automatically extended to all
+     recipients of the covered work and works based on it.
+
+     A patent license is "discriminatory" if it does not include within
+     the scope of its coverage, prohibits the exercise of, or is
+     conditioned on the non-exercise of one or more of the rights that
+     are specifically granted under this License.  You may not convey a
+     covered work if you are a party to an arrangement with a third
+     party that is in the business of distributing software, under
+     which you make payment to the third party based on the extent of
+     your activity of conveying the work, and under which the third
+     party grants, to any of the parties who would receive the covered
+     work from you, a discriminatory patent license (a) in connection
+     with copies of the covered work conveyed by you (or copies made
+     from those copies), or (b) primarily for and in connection with
+     specific products or compilations that contain the covered work,
+     unless you entered into that arrangement, or that patent license
+     was granted, prior to 28 March 2007.
+
+     Nothing in this License shall be construed as excluding or limiting
+     any implied license or other defenses to infringement that may
+     otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+     If 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 convey a covered work so as to satisfy
+     simultaneously your obligations under this License and any other
+     pertinent obligations, then as a consequence you may not convey it
+     at all.  For example, if you agree to terms that obligate you to
+     collect a royalty for further conveying from those to whom you
+     convey the Program, the only way you could satisfy both those
+     terms and this License would be to refrain entirely from conveying
+     the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+     Notwithstanding any other provision of this License, you have
+     permission to link or combine any covered work with a work licensed
+     under version 3 of the GNU Affero General Public License into a
+     single combined work, and to convey the resulting work.  The terms
+     of this License will continue to apply to the part which is the
+     covered work, but the special requirements of the GNU Affero
+     General Public License, section 13, concerning interaction through
+     a network will apply to the combination as such.
+
+ 14. Revised Versions of this License.
+
+     The Free Software Foundation may publish revised and/or new
+     versions of the GNU 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
+     Program specifies that a certain numbered version of the GNU
+     General Public License "or any later version" applies to it, you
+     have the option of following the terms and conditions either of
+     that numbered version or of any later version published by the
+     Free Software Foundation.  If the Program does not specify a
+     version number of the GNU General Public License, you may choose
+     any version ever published by the Free Software Foundation.
+
+     If the Program specifies that a proxy can decide which future
+     versions of the GNU General Public License can be used, that
+     proxy's public statement of acceptance of a version permanently
+     authorizes you to choose that version for the Program.
+
+     Later license versions may give you additional or different
+     permissions.  However, no additional obligations are imposed on any
+     author or copyright holder as a result of your choosing to follow a
+     later version.
+
+ 15. Disclaimer of Warranty.
+
+     THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+     APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE
+     COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU.
+     SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
+     NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+     IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+     WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES
+     AND/OR CONVEYS THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER
+     PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF
+     THE POSSIBILITY OF SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+     If the disclaimer of warranty and limitation of liability provided
+     above cannot be given local legal effect according to their terms,
+     reviewing courts shall apply local law that most closely
+     approximates an absolute waiver of all civil liability in
+     connection with the Program, unless a warranty or assumption of
+     liability accompanies a copy of the Program in return for a fee.
+
+
+END OF TERMS AND CONDITIONS
+===========================
+
+How to Apply These Terms to Your New Programs
+=============================================
+
+If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these
+terms.
+
+   To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state 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 PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
+     Copyright (C) YEAR NAME OF AUTHOR
+
+     This program is free software: you can redistribute it and/or modify
+     it under the terms of the GNU General Public License as published by
+     the Free Software Foundation, either version 3 of the License, or (at
+     your option) any later version.
+
+     This program 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
+     General Public License for more details.
+
+     You should have received a copy of the GNU General Public License
+     along with this program.  If not, see `http://www.gnu.org/licenses/'.
+
+   Also add information on how to contact you by electronic and paper
+mail.
+
+   If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+     PROGRAM Copyright (C) YEAR NAME OF AUTHOR
+     This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+     This is free software, and you are welcome to redistribute it
+     under certain conditions; type `show c' for details.
+
+   The hypothetical commands `show w' and `show c' should show the
+appropriate parts of the General Public License.  Of course, your
+program's commands might be different; for a GUI interface, you would
+use an "about box".
+
+   You should also get your employer (if you work as a programmer) or
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  For more information on this, and how to apply and follow
+the GNU GPL, see `http://www.gnu.org/licenses/'.
+
+   The GNU General Public License does not permit incorporating your
+program into proprietary programs.  If your program is a subroutine
+library, you may consider it more useful to permit linking proprietary
+applications with the library.  If this is what you want to do, use the
+GNU Lesser General Public License instead of this License.  But first,
+please read `http://www.gnu.org/philosophy/why-not-lgpl.html'.
--- a/main/database/DESCRIPTION	Wed Jan 16 05:52:13 2013 +0000
+++ b/main/database/DESCRIPTION	Wed Jan 16 06:17:06 2013 +0000
@@ -1,18 +1,10 @@
 Name: database
-Version: 1.0.4
-Date: 2009-01-09
-Author: Xavier Delacour <xavier.delacour@gmail.com>
-Maintainer: The Octave Community
-Title: Bindings for postgres, mysql, sqlite, and standard ODBC
-Description: These are bindings that allow SQL queries and other database
- operations on postgres, mysql, sqlite, and standard ODBC databases from within
- Octave. A simplified interface that is uniform across all database types is
- provided, as well as the entire C client API for each database (libpq,
- libmysqlclient, etc).
-Depends: octave (>= 2.9.12)
+Version: 1.99.0
+Date: 2013-01-16
+Author: Olaf Till <i7tiol@t-online.de>
+Maintainer: Olaf Till <i7tiol@t-online.de>
+Title: Database.
+Description: Interface to SQL databases, currently only postgresql using libpq.
+Depends: octave (>= 3.6.2)
 Autoload: yes
-SystemRequirements: swig, postgresql-8.2, postgresql-client-8.2, mysql-common,
- mysql-client-5.0, mysql-server-5.0, libmysqlclient15-dev, sqlite3,
- libsqlite3-dev, unixodbc-bin, unixodbc-dev, odbc-postgresql.
-License: BSD, GPL2
-Url: http://octave.sf.net
+License: GPLv3
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/INDEX	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,14 @@
+postgesql >> Postgresql.
+Connection
+ pq_connect
+ pq_close
+ pq_update_types
+Command execution
+ pq_exec_params
+Large objects
+ pq_lo_import
+ pq_lo_export
+ pq_lo_unlink
+Option setting
+ setdbopts
+ getdbopts
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/NEWS	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,54 @@
+no release yet, initial commit database 1.99.0:
+-----------------------------------------------
+
+Postgresql interface implemented. Copy of README-postgresql:
+
+
+Functions:
+
+
+pq_connect: connect to a postgresql database,
+
+pq_exec_params: execute an SQL command with optional parameters and
+                return result,
+
+pq_update_types: used if defined types change during connection time.
+
+pq_lo_import: import large object from client side
+
+pq_lo_export: export large object to client side
+
+pq_lo_unlink: delete large object
+
+
+Features:
+
+
+- number of connections not limited,
+
+- mapping of postgresql types to Octave types in data exchange in both
+  directions,
+
+- arbitrarily deeply nested composite- and array-types,
+
+- binary data transfer,
+
+- reads postgresql system catalogs to get type information.
+
+
+State:
+
+
+Alpha, but can already be useful. Not all base types implemented yet,
+also no enum types yet. Copy in and copy are not yet implemented. The
+other commands should work. The whole framework including conversion
+of composite and array types with the resulting possible recursion and
+a number of base types are implemented. Large object import, export,
+and unlink works.
+
+Please report bugs. If you want to implement a new type-converter
+yourself, you can do it in converters.cc and tell me (package
+maintainer) about it. See converters.h for the meaning of fields in
+the oct_pq_conv_t structure. Presently only the binary converters are
+needed, the string converters can be stubs returning an error value
+(1).
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/doc/README	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,4 @@
+Interfaces for SQL databases should go into this package. Currently
+only a postgresql interface is implemented (see README-postgresql). As
+soon as interfaces to further database systems emerge we should move
+the code into respective subdirectories.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/doc/README-postgresql	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,53 @@
+Octave postgresql interface
+
+
+Functions:
+
+
+pq_connect: connect to a postgresql database,
+
+pq_exec_params: execute an SQL command with optional parameters and
+                return result,
+
+pq_update_types: used if defined types change during connection time,
+
+pq_lo_import: import large object from client side,
+
+pq_lo_export: export large object to client side,
+
+pq_lo_unlink: delete large object,
+
+pq_close: disconnect from database.
+
+
+Features:
+
+
+- number of connections not limited,
+
+- mapping of postgresql types to Octave types in data exchange in both
+  directions,
+
+- arbitrarily deeply nested composite- and array-types,
+
+- binary data transfer,
+
+- reads postgresql system catalogs to get type information.
+
+
+State:
+
+
+Alpha, but can already be useful. Not all base types implemented yet,
+also no enum types yet. Copy in and copy are not yet implemented. The
+other commands should work. The whole framework including conversion
+of composite and array types with the resulting possible recursion and
+a number of base types are implemented. Large object import, export,
+and unlink works.
+
+Please report bugs. If you want to implement a new type-converter for
+a base type yourself, you can do it in converters.cc and tell me
+(package maintainer) about it. See converters.h for the meaning of
+fields in the oct_pq_conv_t structure. Presently only the binary
+converters are needed, the string converters can be stubs returning an
+error value (1).
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/doc/dev-postgresql/conversions.tex	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,326 @@
+\documentclass[a4paper,landscape]{article}
+
+\usepackage[utf8]{inputenc}
+\usepackage[landscape]{geometry}
+\usepackage{longtable}
+\usepackage[pdftex,                %%% hyper-references for pdflatex
+breaklinks=true]{hyperref}%        %%% break links if exceeding a single line
+
+\pdfadjustspacing=1                %%% force LaTeX-like character spacing
+
+\oddsidemargin=0mm
+\headsep=0mm
+\headheight=0mm
+\topmargin=0mm
+\textwidth=287mm
+\textheight=160mm
+\hoffset=-20mm
+
+\begin{document}
+
+\begin{longtable}{lp{40mm}p{40mm}p{50mm}p{40mm}p{50mm}}
+type &
+oid &
+array-oid &
+octave type &
+need to specify type &
+conversion \\\hline
+
+int4 &
+23 &
+1007 &
+int32 &
+no &
+NBO \\
+
+int2 &
+21 &
+1005 &
+int16 &
+no &
+NBO \\
+
+int8 &
+20 &
+1016 &
+int64 &
+no &
+NBO \\
+
+float4 &
+700 &
+1021 &
+single &
+no &
+NBO \\
+
+float8 &
+701 &
+1022 &
+double &
+no &
+NBO \\
+
+numeric &
+1700 &
+1231 &
+string &
+yes &
+int16: ndigits, int16: weight of first digit, int16: sign (pos: 0,
+neg: 0x4000, NaN: 0xC000), int16: display scale, ndigits x int8:
+digits \\
+
+money &
+790 &
+791 &
+int64 &
+yes &
+NBO \\
+
+text &
+25 &
+1009 &
+string &
+no &
+to server as is without trailing zero, server does conversion of
+character encoding, if necessary; from server string with already
+client-adapted character encoding (?) \\
+
+varchar &
+1043 &
+1015 &
+string &
+yes &
+same as text \\
+
+bpchar (character(n)) &
+1042 &
+1014 &
+string &
+yes &
+same as text \\
+
+name &
+&
+&
+string $<$ NAMEDATALEN &
+yes &
+same as text \\
+
+bytea &
+17 &
+1001 &
+uint8 vector &
+no &
+no conversion \\
+
+timestamp &
+1114 &
+1115 &
+string &
+yes &
+consider encoding (integer or float), NBO, \ldots{} (put off
+implementation) \\
+
+timestamptz &
+1184 &
+1185 &
+string &
+yes &
+(put off implementation) \\
+
+time &
+1083 &
+1183 &
+string &
+yes &
+(put off implementation) \\
+
+timetz &
+1266 &
+1270 &
+string &
+yes &
+(put off implementation) \\
+
+date &
+1082 &
+1182 &
+string &
+yes &
+(put off implementation) \\
+
+interval &
+1186 &
+1187 &
+string &
+yes &
+(put off implementation) \\
+
+bool &
+16 &
+1000 &
+bool &
+no &
+no conversion \\
+
+enum &
+variable &
+705 (``unknown'') (?) &
+string &
+yes &
+(to server and from server as is without trailing zero (?))\\
+
+point &
+600 &
+1017 &
+2-element float vector &
+no &
+double by double, NBO \\
+
+line (?) &
+628 &
+629 &
+4-element float vector &
+yes &
+double by double, NBO \\
+
+lseg &
+601 &
+1018 &
+4-element float vector &
+no &
+double by double, NBO \\
+
+box &
+603 &
+1020 &
+4-element float vector &
+yes &
+double by double, NBO \\
+
+path &
+602 &
+1019 &
+(2n-element float vector, and somehow code if it is closed (?)) &
+yes ((path? closed?) obsolete) &
+NBO, 1 byte (closed ? 1 : 0), int32 (npts), 2n double \\
+
+polygon &
+604 &
+1027 &
+2n-element float vector &
+yes &
+NBO, int32 (npts), 2n double \\
+
+circle &
+718 &
+719 &
+3-element float vector &
+no &
+double by double, NBO \\
+
+inet &
+869 &
+1041 &
+4,5,16, or 17-element uint8 vector &
+yes (is an addresstype? cidr? (code this in Octave representation of value) &
+uint8: \nolinkurl{AF_INET}, any other constant means \nolinkurl{AF_INET6}; uint8: number of
+set maskbits (in element 5 or 17 of octave vector, default 32 and
+128); uint8: \nolinkurl{is_cidr}?; uint8: addrsize (4 or 16); 4x or 16x uint8:
+address (left to right) \\
+
+cidr &
+650 &
+651 &
+see inet &
+see inet &
+see inet \\
+
+macaddr &
+829 &
+1040 &
+6-element uint8 vector &
+yes &
+6x uint8 (left to right) \\
+
+bit &
+1560 &
+1561 &
+string of 1 and 0 &
+yes &
+int32 (NBO): nbits; n times uint8 (left to right, first byte full) \\
+
+varbit &
+1562 &
+1563 &
+see bit &
+yes &
+see bit \\
+
+tsvector &
+3614 &
+3643 &
+No, do not provide communication of this type with
+Octave. one-dimensional cell-array of lexemes, which are
+one-dimensional cell-arrays of length 3, first entry word, second
+entry vector of positions (possibly empty), third entry vector of
+weights (same length as positions), set to zeros (weight D) if no
+weights are given &
+yes &
+int32: nlexemes, nlexemes x (zero-terminated lexeme (from server:
+already in correct encoding), uint16: number of position/weight-data
+(:= npos), npos x uint16: first 2 bits weight (0 == D?) and last 14
+bits position) \\
+
+tsquery &
+3615 &
+3645 &
+Do not provide communication of this type with Octave. &
+&
+\\
+
+uuid &
+2950 &
+2951 &
+16-element uint8 vector &
+yes &
+16 x uint8, left to right \\
+
+xml &
+142 &
+143 &
+Do not provide communication of this type with Octave. &
+&
+\\
+
+array &
+see other types &
+(another dimension) &
+(see \nolinkurl{pq_exec_params} help text) &
+yes &
+int32: ndim, int32: \nolinkurl{has_null}\nolinkurl{(_bitmap)} ? 1 :
+0, uint32: element-oid, 2 x ndim x int32: ((dims[], lbounds[]), ()),
+nelem x (int32: -1 for NULL element or (uint32: length without header,
+data without header in the datatypes binary format)) \\
+
+record &
+variable &
+ &
+one-dimensional cell-array with entries of respective types &
+yes &
+int32: ncols, ncols x (uint32: element-oid, int32: -1 for NULL element
+or (uint32: length without header, data without header in the
+datatypes binary format)) \\
+
+oid &
+(obsolete information 24, 26, 2202--2206, 3734, 3769) &
+(obsolete information 1008, 1009, 2207--2211, 3735, 3770) &
+uint32 &
+no &
+uint32 \\
+
+
+\end{longtable}
+
+\end{document}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/doc/dev-postgresql/timeformats.txt	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,35 @@
+timestamp:
+
+Timestamp (8 byte, float or int)
+
+
+timestamptz:
+
+TimestampTz (8 byte, float or int)
+
+
+interval:
+
+TimeOffset (8 byte, float or int) (all except day, month, year)
+
+int32                (days)
+
+int32                (months and years)
+
+
+time:
+
+TimeADT (8 byte, float or int)
+
+
+timetz:
+
+TimeADT (8 byte, float or int) (all except month, year)
+
+int32                 (timezone in seconds)
+
+
+date:
+
+int32
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/inst/__all_db_opts__.m	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,69 @@
+## Copyright (C) 2012 VZLU Prague
+##
+## This program is free software; you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## This program 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
+## General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with Octave; see the file COPYING.  If not, see
+## <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{names} =} __all_db_opts__ (@dots{})
+## Undocumented internal function.
+## @end deftypefn
+
+## Query all options from all known database functions and return a list
+## of possible values.
+
+## Copied from Octave (was '__all_opts__') (Olaf Till
+## <i7tiol@t-online.de>).
+
+function names = __all_db_opts__ (varargin)
+
+  persistent saved_names = {};
+
+  ## do not clear this function
+  mlock ();
+
+  ## guard against recursive calls.
+  persistent recursive = false;
+
+  if (recursive)
+    names = {};
+  elseif (nargin == 0)
+    names = saved_names;
+  else
+    ## query all options from all known functions. These will call setdbopts,
+    ## which will in turn call us, but we won't answer.
+    recursive = true;
+    names = saved_names;
+    for i = 1:nargin
+      try
+        opts = setdbopts (varargin{i});
+        fn = fieldnames (opts).';
+        names = [names, fn];
+      catch
+        # throw the error as a warning.
+        warning (lasterr ());
+      end_try_catch
+    endfor
+    names = unique (names);
+    [lnames, idx] = unique (tolower (names));
+    if (length (lnames) < length (names))
+      ## This is bad.
+      error ("duplicate options with inconsistent case");
+    else
+      names = names(idx);
+    endif
+    saved_names = names;
+    recursive = false;
+  endif
+
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/inst/getdbopts.m	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,51 @@
+## Copyright (C) 2012 Jaroslav Hajek
+##
+## This program is free software; you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## This program 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
+## General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with Octave; see the file COPYING.  If not, see
+## <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn  {Function File} {} getdbopts (@var{options}, @var{parname})
+## @deftypefnx {Function File} {} getdbopts (@var{options}, @var{parname}, @var{default})
+## Return a specific option from a structure created by
+## @code{setdbopts}.  If @var{parname} is not a field of the @var{options}
+## structure, return @var{default} if supplied, otherwise return an
+## empty matrix.
+## @end deftypefn
+
+## Copied from Octave (was 'optimget') (Olaf Till <i7tiol@t-online.de>).
+
+function retval = getdbopts (options, parname, default)
+
+  if (nargin < 2 || nargin > 4 || ! isstruct (options) || ! ischar (parname))
+    print_usage ();
+  endif
+
+  opts = __all_db_opts__ ();
+  idx = lookup (tolower (opts), tolower (parname), "m");
+
+  if (idx)
+    parname = opts{idx};
+  else
+    warning ("unrecognized option: %s", parname);
+  endif
+  if (isfield (options, parname))
+    retval = options.(parname);
+  elseif (nargin > 2)
+    retval = default;
+  else
+    retval = [];
+  endif
+
+endfunction
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/inst/pq_connect.m	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,156 @@
+## Copyright (C) 2012, 2013 Olaf Till <i7tiol@t-online.de>
+##
+## This program is free software; you can redistribute it and/or modify it under
+## the terms of the GNU General Public License as published by the Free Software
+## Foundation; either version 3 of the License, or (at your option) any later
+## version.
+##
+## This program 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 General Public License for more
+## details.
+##
+## You should have received a copy of the GNU General Public License along with
+## this program; if not, see <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn {Function File} {@var{connection} =} pq_connect (@var{settings})
+## Establishes a connection to a postgresql server according to
+## @var{settings} and returns an @code{octave_pq_connection} object
+## @var{connection} which can be passed to other functions of the
+## package. There can be multiple connections. An
+## @code{octave_pq_connection} object contains information on a
+## connection and will be internally altered by the packages functions
+## even though it is only passed as an argument, i.e. Octaves 'pass by
+## value' semantics are not adhered to in this case.
+##
+## @var{settings} can be set by @code{setdbopts} (copied from Octaves
+## @code{optimset}) and can contain (defaults depend on Postgresql):
+## @code{host} (hostname), @code{hostaddr} (numeric host address),
+## @code{port} (port to connect to), @code{dbname} (database to connect
+## to), @code{user} (user name to connect as), @code{password},
+## @code{connect_timeout}, @code{options} (command-line options to send
+## to the server at run-time, see Postgresql documentation),
+## @code{sslmode} (@code{disable}, @code{allow}, @code{prefer},
+## @code{require}, @code{verify-ca}, or @code{verify-full}; see
+## Postgresql documentation of SSL support), @code{sslcert} (file name
+## of client SSL certificate), @code{sslkey} (location of secret key for
+## client certificate, file name or external OpenSSL engine
+## (colon-separated engine name and an engine-specific key identifier)),
+## @code{sslrootcert} (file name of root SSL certificate), @code{sslcrl}
+## (file name of SSL certificate revocation list), @code{krbsrvname}
+## (kerberos service name), @code{service} (service name in
+## pq_service.conf to use for additional parameters).
+##
+## All these settings are passed to the server as they are, so it may be
+## better to consult the postgresql documentation for them, e.g. the
+## documentation of the PQconnectdb function in libpq.
+## @seealso {pq_exec_params, pq_update_types}
+## @end deftypefn
+
+## PKG_ADD: __all_db_opts__ ("pq_connect");
+
+function conn = pq_connect (settings)
+
+  if (nargin != 1)
+    print_usage ()
+  endif
+
+  if (ischar (settings) && strcmp (settings, "defaults"))
+    conn = setdbopts ("host", [], \
+                      "hostaddr", [], \
+                      "port", [], \
+                      "dbname", [], \
+                      "user", [], \
+                      "password", [], \
+                      "connect_timeout", [], \
+                      "options", [], \
+                      "sslmode", [], \
+                      "sslcert", [], \
+                      "sslkey", [], \
+                      "sslrootcert", [], \
+                      "sslcrl", [], \
+                      "krbsrvname", [], \
+                      "service", []);
+    return;
+  endif
+
+  if (! isempty (to = getdbopts (settings, "connect_timeout")) && \
+      isnumeric (to))
+    settings = setdbopts (settings, "connect_timeout", num2str (to));
+  endif
+
+  if (isfield (settings, "password") && isempty (settings.password))
+    ## I know this is far from elegant, but it seems robust and I'm to
+    ## lazy now to find out a more decent way.
+    printf ("password: ");
+    fflush (stdout);
+    password = "";
+    while (true)
+      c = kbhit ();
+      if (c == "\n")
+        printf ("\n");
+        break;
+      else
+        password = sprintf ("%s%s", password, c);
+      endif
+    endwhile
+    settings.password = password;
+  endif
+
+  optstring = "";
+
+  for [val, key] = settings
+    if (isempty (val))
+      val = "";
+    endif
+    val = strrep (val, '\', '\\');
+    val = strrep (val, "'", "''");
+    optstring = sprintf ("%s%s='%s' ", optstring, key, val);
+  endfor
+
+  conn = __pq_connect__ (optstring);
+
+endfunction
+
+%!demo
+%! conn = pq_connect (setdbopts ("dbname", "test"));
+%! pq_exec_params (conn, "create table testtable (t text, i int2, b bytea);")
+%! pq_exec_params (conn, "insert into testtable values ($1, $2, $3);", {"name1", 1, uint8([2, 4, 5])})
+%! pq_exec_params (conn, "insert into testtable values ($1, $2, $3);", {"name2", 2, uint8([7, 9, 3, 1])})
+%! pq_exec_params (conn, "select * from testtable;")
+%! pq_exec_params (conn, "drop table testtable;")
+%! pq_close (conn);
+
+%!demo
+%! ## recursive type, array-composite-array
+%! conn = pq_connect (setdbopts ("dbname", "test"));
+%! pq_exec_params (conn, "create type complex_bool_array_type as (b bool, ba bool[]);")
+%! pq_exec_params (conn, "create table complex_bool_array_array (a complex_bool_array_type[]);")
+%! pq_update_types (conn);
+%! pq_exec_params (conn, "insert into complex_bool_array_array values ($1);", {struct("ndims", 1, "data", {{{true, struct("ndims", 2, "data", {{true, false; true, true}})}; {false, struct("ndims", 1, "data", {{false; true}})}}})}, setdbopts ("param_types", {"complex_bool_array_type[]"}))
+%! pq_exec_params (conn, "select * from complex_bool_array_array;")
+%! ## recursive type, composite-composite-array
+%! pq_exec_params (conn, "create type complex_complex_bool_array_type as (b bool, c complex_bool_array_type);")
+%! pq_exec_params (conn, "create table complex_complex_bool_array (a complex_complex_bool_array_type);");
+%! pq_update_types (conn);
+%! pq_exec_params (conn, "insert into complex_complex_bool_array values ($1);", {{false, {true, struct("ndims", 2, "data", {{true, false; true, true}})}}}, setdbopts ("param_types", {"complex_complex_bool_array_type"}))
+%! pq_exec_params (conn, "select * from complex_complex_bool_array")
+%! pq_exec_params (conn, "drop table complex_complex_bool_array;")
+%! pq_exec_params (conn, "drop table complex_bool_array_array;")
+%! pq_exec_params (conn, "drop type complex_complex_bool_array_type;")
+%! pq_exec_params (conn, "drop type complex_bool_array_type;")
+%! pq_close (conn);
+
+%!test
+%! conn = pq_connect (setdbopts ("dbname", "test"));
+%! assert (islogical (t = pq_exec_params (conn, "select ($1);", {true}).data{1}) && t == true);
+%! assert (strcmp (typeinfo (t = pq_exec_params (conn, "select ($1);", {uint32(3)}).data{1}), "uint32 scalar") && t == 3);
+%! assert (strcmp (typeinfo (t = pq_exec_params (conn, "select ($1);", {.5}).data{1}), "scalar") && t == .5);
+%! assert (strcmp (typeinfo (t = pq_exec_params (conn, "select ($1);", {single(.5)}).data{1}), "float scalar") && t == .5);
+%! assert ((strcmp (ti = typeinfo (t = pq_exec_params (conn, "select ($1);", {"abc"}).data{1}), "string") || strcmp (ti, "sq_string")) && strcmp (t, "abc"));
+%! assert (strcmp (typeinfo (t = pq_exec_params (conn, "select ($1);", {uint8([2, 3])}).data{1}), "uint8 matrix") && isequal (t, [2; 3]));
+%! assert (strcmp (typeinfo (t = pq_exec_params (conn, "select ($1);", {int16(-2)}).data{1}), "int16 scalar") && t == int16 (-2));
+%! assert (strcmp (typeinfo (t = pq_exec_params (conn, "select ($1);", {int32(-2)}).data{1}), "int32 scalar") && t == int32 (-2));
+%! assert (strcmp (typeinfo (t = pq_exec_params (conn, "select ($1);", {int64(-2)}).data{1}), "int64 scalar") && t == int64 (-2));
+%! pq_close (conn);
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/inst/setdbopts.m	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,146 @@
+## Copyright (C) 2012 John W. Eaton
+##
+## Copyright (C) 2012 VZLU Prague
+##
+## This program is free software; you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published by
+## the Free Software Foundation; either version 3 of the License, or (at
+## your option) any later version.
+##
+## This program 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
+## General Public License for more details.
+##
+## You should have received a copy of the GNU General Public License
+## along with Octave; see the file COPYING.  If not, see
+## <http://www.gnu.org/licenses/>.
+
+## -*- texinfo -*-
+## @deftypefn  {Function File} {} setdbopts ()
+## @deftypefnx {Function File} {} setdbopts (@var{par}, @var{val}, @dots{})
+## @deftypefnx {Function File} {} setdbopts (@var{old}, @var{par}, @var{val}, @dots{})
+## @deftypefnx {Function File} {} setdbopts (@var{old}, @var{new})
+## Create options struct for optimization functions.
+##
+## Valid parameters are:
+##
+## @itemize @bullet
+## @item AutoScaling
+##
+## @item ComplexEqn
+##
+## @item FinDiffType
+##
+## @item FunValCheck
+## When enabled, display an error if the objective function returns an invalid
+## value (a complex value, NaN, or Inf).  Must be set to "on" or "off"
+## [default].  Note: the functions @code{fzero} and @code{fminbnd} correctly
+## handle Inf values and only complex values or NaN will cause an error in this
+## case. 
+##
+## @item GradObj
+## When set to "on", the function to be minimized must return a second argument
+## which is the gradient, or first derivative, of the function at the point
+## @var{x}.  If set to "off" [default], the gradient is computed via finite
+## differences.
+##
+## @item Jacobian
+## When set to "on", the function to be minimized must return a second argument
+## which is the Jacobian, or first derivative, of the function at the point
+## @var{x}.  If set to "off" [default], the Jacobian is computed via finite
+## differences.
+##
+## @item MaxFunEvals
+## Maximum number of function evaluations before optimization stops.
+## Must be a positive integer.
+##
+## @item MaxIter
+## Maximum number of algorithm iterations before optimization stops.
+## Must be a positive integer.
+##
+## @item OutputFcn
+## A user-defined function executed once per algorithm iteration.
+##
+## @item TolFun
+## Termination criterion for the function output.  If the difference in the
+## calculated objective function between one algorithm iteration and the next
+## is less than @code{TolFun} the optimization stops.  Must be a positive
+## scalar.
+##
+## @item TolX
+## Termination criterion for the function input.  If the difference in @var{x},
+## the current search point, between one algorithm iteration and the next is
+## less than @code{TolX} the optimization stops.  Must be a positive scalar.
+##
+## @item TypicalX
+##
+## @item Updating
+## @end itemize
+## @end deftypefn
+
+## Copied from Octave (was 'optimset') (Olaf Till <i7tiol@t-online.de>).
+
+function retval = setdbopts (varargin)
+
+  nargs = nargin ();
+
+  ## Add more as needed.
+  opts = __all_db_opts__ ();
+
+  if (nargs == 0)
+    if (nargout == 0)
+      ## Display possibilities.
+      puts ("\nAll possible optimization options:\n\n");
+      printf ("  %s\n", opts{:});
+      puts ("\n");
+    else
+      ## Return struct with all options initialized to []
+      retval = cell2struct (repmat ({[]}, size (opts)), opts, 2);
+    endif
+  elseif (nargs == 1 && ischar (varargin{1}))
+    ## Return defaults for named function.
+    fcn = varargin{1};
+    try
+      retval = feval (fcn, "defaults");
+    catch
+      error ("no defaults for function `%s'", fcn);
+    end_try_catch
+  elseif (nargs == 2 && isstruct (varargin{1}) && isstruct (varargin{2}))
+    ## Set slots in old from nonempties in new.  Should we be checking
+    ## to ensure that the field names are expected?
+    old = varargin{1};
+    new = varargin{2};
+    fnames = fieldnames (old);
+    ## skip validation if we're in the internal query
+    validation = ! isempty (opts);
+    lopts = tolower (opts);
+    for [val, key] = new
+      if (validation)
+        ## Case insensitive lookup in all options.
+        i = lookup (lopts, tolower (key));
+        ## Validate option.
+        if (i > 0 && strcmpi (opts{i}, key))
+          ## Use correct case.
+          key = opts{i};
+        else
+          warning ("unrecognized option: %s", key);
+        endif
+      endif
+      old.(key) = val;
+    endfor
+    retval = old;
+  elseif (rem (nargs, 2) && isstruct (varargin{1}))
+    ## Set values in old from name/value pairs.
+    pairs = reshape (varargin(2:end), 2, []);
+    retval = setdbopts (varargin{1}, cell2struct (pairs(2, :), pairs(1, :), 2));
+  elseif (rem (nargs, 2) == 0)
+    ## Create struct.  Default values are replaced by those specified by
+    ## name/value pairs.
+    pairs = reshape (varargin, 2, []);
+    retval = setdbopts (struct (), cell2struct (pairs(2, :), pairs(1, :), 2));
+  else
+    print_usage ();
+  endif
+
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/Makefile.in	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,13 @@
+OBJECTS := __pq_connect__.o pq_close.o pq_exec.o converters.o \
+           converters_arr_comp.o pq_connection.o command.o \
+           pq_update_types.o pq_lo.o
+
+pq_interface.oct: $(OBJECTS)
+	@MKOCTFILE@ -o pq_interface.oct -lpq $(OBJECTS)
+
+# be on the safe side with respect to include files
+%.o: %.cc converters.h pq_connection.h command.h
+	@MKOCTFILE@ -c $<
+
+.PHONY: clean
+clean: ; rm -f *.o *.oct
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/__pq_connect__.cc	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,60 @@
+/*
+
+Copyright (C) 2012 Olaf Till <i7tiol@t-online.de>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+This program 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#include <octave/oct.h>
+
+#include "pq_connection.h"
+
+
+// PKG_ADD: autoload ("__pq_connect__", "pq_interface.oct");
+
+DEFUN_DLD (__pq_connect__, args, ,
+           "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} {@var{id}} __pq_connect__ (@var{options})\n\
+Text.\n\
+\n\
+@end deftypefn")
+{
+  std::string fname ("__pq_connect__");
+
+  if (args.length () != 1)
+    {
+      print_usage ();
+
+      return octave_value_list ();
+    }
+
+  std::string opt_string = args(0).string_value ();
+
+  if (error_state)
+    {
+      error ("%s: argument not a string", fname.c_str ());
+
+      return octave_value_list ();
+    }
+
+  octave_value retval (new octave_pq_connection (opt_string));
+
+  // We spare checking
+  // bool(octave_pq_connection::octave_pq_get_conn()), since in case
+  // of false there was an error thrown, so destruction of the
+  // octave_pq_connection object will be caused by Octaves reference
+  // counting scheme.
+  return retval;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/autogen.sh	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,3 @@
+#! /bin/sh
+
+autoconf
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/command.cc	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,517 @@
+/*
+
+Copyright (C) 2012, 2013 Olaf Till <i7tiol@t-online.de>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+This program 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#include <octave/oct.h>
+#include <octave/ov-struct.h>
+#include <octave/Cell.h>
+#include <octave/lo-ieee.h>
+
+#include "command.h"
+
+#define ERROR_RETURN_NO_PG_TYPE                                         \
+ {                                                                      \
+   error ("could not determine postgresql type for Octave parameter");  \
+   return NULL;                                                         \
+ }
+
+command::command (octave_pq_connection &connection, std::string &cmd,
+                  Cell &rtypes,std::string &who) :
+  valid (1), conn (connection), caller (who), res (NULL), all_fetched (0),
+  rettypes (rtypes)
+{
+  if (! (cptr = conn.octave_pq_get_conn ()))
+    {
+      valid = 0;
+      error ("%s: connection not open", caller.c_str ());
+    }
+
+  if (! PQsendQuery (cptr, cmd.c_str ()))
+    {
+      valid = 0;
+      error ("%s: could not dispatch command: %s", caller.c_str (),
+             PQerrorMessage (cptr));
+    }
+  else
+    {
+      res = PQgetResult (cptr);
+      check_first_result ();
+    }
+}
+
+command::command (octave_pq_connection &connection, std::string &cmd,
+                  Cell &params, Cell &ptypes, Cell &rtypes, std::string &who)
+  : valid (1), conn (connection), caller (who), res (NULL), all_fetched (1),
+  rettypes (rtypes)
+{
+  if (! (cptr = conn.octave_pq_get_conn ()))
+    {
+      valid = 0;
+      error ("%s: connection not open", caller.c_str ());
+    }
+
+  int npars = params.length ();
+
+  char *vals [npars];
+  std::vector<oct_pq_dynvec_t> valsvec;
+  valsvec.resize (npars);
+  int pl [npars];
+  int pf [npars];
+  Oid oids [npars];
+
+  for (int i = 0; i < npars; i++)
+    {
+      pf[i] = 1; // means binary format
+
+      if (params(i).is_real_scalar () && params(i).isna ().bool_value ())
+        {
+          vals[i] = NULL;
+
+          oids[i] = 0;
+        }
+      else
+        {
+          oct_type_t oct_type;
+          oct_pq_conv_t *conv;
+          oct_pq_from_octave_fp_t conv_fcn;
+
+          if (ptypes(i).is_empty ())
+            {
+              oct_type = simple;
+
+              if (! (conv = pgtype_from_octtype (params(i))))
+                {
+                  valid = 0;
+                  break;
+                }
+
+              // array not possible here
+              oids[i] = conv->oid;
+            }
+          else
+            {
+              std::string s = ptypes(i).string_value ();
+              if (error_state)
+                {
+                  error ("%s: parameter type specification no string",
+                         caller.c_str ());
+                  valid = 0;
+                  break;
+                }
+
+              if (! (conv = pgtype_from_spec (s, oct_type)))
+                {
+                  valid = 0;
+                  break;
+                }
+
+              if (oct_type == array)
+                oids[i] = conv->aoid;
+              else
+                oids[i] = conv->oid;
+            }
+
+          switch (oct_type)
+            {
+            case simple:
+              conv_fcn = conv->from_octave_bin;
+              if (conv_fcn (params(i), valsvec[i]))
+                valid = 0;
+              break;
+
+            case array:
+              if (from_octave_bin_array (params(i), valsvec[i], conv))
+                valid = 0;
+              break;
+
+            case composite:
+              if (from_octave_bin_composite (params(i), valsvec[i], conv))
+                valid = 0;
+              break;
+
+            default:
+              // should not get here
+              error ("%s: internal error, undefined type identifier",
+                     caller.c_str ());
+
+              valid = 0;
+            }
+
+          if (! valid) break;
+
+          vals[i] = &(valsvec[i].front ());
+          pl[i] = valsvec[i].size ();
+        }
+    }
+
+  if (valid)
+    {
+      res = PQexecParams (cptr, cmd.c_str (), npars, oids, vals, pl, pf, 1);
+
+      check_first_result ();
+    }
+}
+
+oct_pq_conv_t *command::pgtype_from_spec (std::string &name,
+                                          oct_type_t &oct_type)
+{
+  oct_pq_conv_t *conv = NULL;
+
+  // printf ("pgtype_from_spec(%s): simple ", name.c_str ());
+
+  oct_type = simple; // default
+  int l;
+  while (name.size () >= 2 && ! name.compare (l = name.size () - 2, 2, "[]"))
+    {
+      name.erase (l, 2);
+      oct_type = array;
+
+      // printf ("array ");
+    }
+
+  oct_pq_name_conv_map_t::iterator iter;
+
+  if ((iter = conn.name_conv_map.find (name.c_str ())) ==
+      conn.name_conv_map.end ())
+    error ("%s: no converter found for type %s", caller.c_str (),
+           name.c_str ());
+  else
+    {
+      // printf ("(looked up in name map) ");
+
+      conv = iter->second;
+
+      if (oct_type == array && ! conv->aoid)
+        {
+          error ("%s: internal error, type %s, specified as array, has no array type in system catalog", name.c_str ());
+          return conv;
+        }
+
+      if (! (oct_type == array) && conv->is_composite)
+        {
+          oct_type = composite;
+
+          // printf ("composite ");
+        }
+    }
+
+  // printf ("\n");
+
+  return conv;
+}
+
+oct_pq_conv_t *command::pgtype_from_spec (Oid oid, oct_type_t &oct_type)
+{
+  // printf ("pgtype_from_spec(%u): ", oid);
+
+  oct_pq_conv_t *conv = NULL;
+
+  oct_pq_conv_map_t::iterator iter;
+  
+  if ((iter = conn.conv_map.find (oid)) == conn.conv_map.end ())
+    {
+      error ("%s: no converter found for element oid %u",
+             caller.c_str (), oid);
+      return conv;
+    }
+  conv = iter->second;
+  // printf ("(looked up %s in oid map) ", conv->name.c_str ());
+
+  if (conv->aoid == oid)
+    oct_type = array;
+  else if (conv->is_composite)
+    oct_type = composite;
+  else
+    oct_type = simple;
+
+  // printf ("oct_type: %i\n", oct_type);
+
+  return conv;
+}
+
+octave_value command::process_single_result (void)
+{
+  octave_value retval;
+
+  // first result is already fetched
+  if (! res && (res = PQgetResult (cptr)))
+    state = PQresultStatus (res);
+
+  if (! res)
+    all_fetched = 1;
+  else
+    {
+      switch (state)
+        {
+        case PGRES_BAD_RESPONSE:
+          valid = 0;
+          error ("%s: server response not understood", caller.c_str ());
+          break;
+        case PGRES_FATAL_ERROR:
+          valid = 0;
+          error ("%s: fatal error: %s", caller.c_str (),
+                 PQresultErrorMessage (res));
+          break;
+        case PGRES_COMMAND_OK:
+          retval = command_ok_handler ();
+          break;
+        case PGRES_TUPLES_OK:
+          retval = tuples_ok_handler ();
+          break;
+        case PGRES_COPY_OUT:
+          retval = copy_out_handler ();
+          break;
+        case PGRES_COPY_IN:
+          retval = copy_in_handler ();
+          break;
+        }
+
+      PQclear (res);
+      res = NULL;
+    }
+
+  return retval;
+}
+
+octave_value command::tuples_ok_handler (void)
+{
+  octave_map ret;
+
+  int nt = PQntuples (res);
+  int nf = PQnfields (res);
+
+  Cell data (nt, nf);
+  Cell columns (1, nf);
+
+  bool rtypes_given;
+  int l = rettypes.length ();
+  if (l > 0)
+    {
+      if (l != nf)
+        {
+          error ("%s: wrong number of given returned types", caller.c_str ());
+          valid = 0;
+          return octave_value_list ();
+        }
+      rtypes_given = true;
+    }
+  else
+    rtypes_given = false;
+
+  for (int j = 0; j < nf; j++) // j is column
+    {
+      columns(j) = octave_value (PQfname (res, j));
+
+      int f = PQfformat (res, j);
+
+      oct_pq_to_octave_fp_t simple_type_to_octave;
+      to_octave_array_fp_t array_to_octave;
+      to_octave_composite_fp_t composite_to_octave;
+
+      oct_pq_conv_t *conv;
+      oct_type_t oct_type;
+
+      // perform next block only if there are any rows, since
+      // otherwise no converter will be needed and we can spare a
+      // possible error of not finding a suitable one
+      if (nt > 0)
+        {
+          if (rtypes_given) // for internal reading of system tables
+            {
+              std::string type = rettypes(j).string_value ();
+              if (error_state)
+                error ("%s: could not convert given type to string",
+                       caller.c_str ());
+              else
+                conv = pgtype_from_spec (type, oct_type);
+
+              if (error_state)
+                {
+                  valid = 0;
+                  break;
+                }
+            }
+          else
+            if (! (conv = pgtype_from_spec (PQftype (res, j), oct_type)))
+              {
+                valid = 0;
+                break;
+              }
+
+          if (f)
+            {
+              array_to_octave = &command::to_octave_bin_array;
+              composite_to_octave = &command::to_octave_bin_composite;
+              // will be NULL for non-simple converters
+              simple_type_to_octave = conv->to_octave_bin;
+            }
+          else
+            {
+              array_to_octave = &command::to_octave_str_array;
+              composite_to_octave = &command::to_octave_str_composite;
+              // will be NULL for non-simple converters
+              simple_type_to_octave = conv->to_octave_str;
+            }
+        }
+
+      // FIXME: To avoid map-lookups of converters for elements of
+      // composite types in arbitrarily deep recursions (over
+      // composite types and possibly arrays) to be repeated in each
+      // row, build up a tree of pointers to looked up converter
+      // structures in the first row and pass branches of it, getting
+      // smaller through the recursions of type conversions, in the
+      // next rows.
+      for (int i = 0; i < nt; i++) // i is row
+        {
+          if (PQgetisnull (res, i, j))
+            data(i, j) = octave_value (octave_NA);
+          else
+            {
+              char *v = PQgetvalue (res, i, j);
+              int nb = PQgetlength (res, i, j);
+              octave_value ov;
+
+              switch (oct_type)
+                {
+                case simple:
+                  if (simple_type_to_octave (v, ov, nb))
+                    valid = 0;
+                  break;
+
+                case array:
+                  if ((this->*array_to_octave) (v, ov, nb, conv))
+                    valid = 0;
+                  break;
+
+                case composite:
+                  if ((this->*composite_to_octave) (v, ov, nb))
+                    valid = 0;
+                  break;
+
+                default:
+                  // should not get here
+                  error ("%s: internal error, undefined type identifier",
+                         caller.c_str ());
+
+                  valid = 0;
+                }
+
+              if (valid)
+                data(i, j) = ov;
+              else
+                break;
+            }
+        }
+
+      if (! valid)
+        break;
+    }
+
+  if (error_state)
+    return octave_value_list ();
+  else
+    {
+      ret.assign ("data", octave_value (data));
+      ret.assign ("columns", octave_value (columns));
+
+      return octave_value (ret);
+    }
+}
+
+octave_value command::copy_out_handler (void)
+{
+  octave_value retval;
+
+  valid = 0;
+
+  error ("copy-out not yet implemented");
+
+  return retval;
+}
+
+octave_value command::copy_in_handler (void)
+{
+  octave_value retval;
+
+  valid = 0;
+
+  error ("copy-in not yet implemented");
+
+  return retval;
+}
+
+oct_pq_conv_t *command::pgtype_from_octtype (octave_value &param)
+{
+  // printf ("pgtype_from_octtype: ");
+
+  if (param.is_bool_scalar ())
+    {
+      // printf ("bool\n");
+      return conn.name_conv_map["bool"];
+    }
+  else if (param.is_real_scalar ())
+    {
+      if (param.is_double_type ())
+        {
+          // printf ("float8\n");
+          return conn.name_conv_map["float8"];
+        }
+      else if (param.is_single_type ())
+        {
+          // printf ("float4\n");
+          return conn.name_conv_map["float4"];
+        }
+    }
+
+  if (param.is_scalar_type ())
+    {
+      if (param.is_int16_type ())
+        {
+          // printf ("int2\n");
+          return conn.name_conv_map["int2"];
+        }
+      else if (param.is_int32_type ())
+        {
+          // printf ("int4\n");
+          return conn.name_conv_map["int4"];
+        }
+      else if (param.is_int64_type ())
+        {
+          // printf ("int8\n");
+          return conn.name_conv_map["int8"];
+        }
+      else if (param.is_uint32_type ())
+        {
+          // printf ("oid\n");
+          return conn.name_conv_map["oid"];
+        }
+    }
+
+  if (param.is_uint8_type ())
+    {
+      // printf ("bytea\n");
+      return conn.name_conv_map["bytea"];
+    }
+  else if (param.is_string ())
+    {
+      // printf ("text\n");
+      return conn.name_conv_map["text"];
+    }
+
+  ERROR_RETURN_NO_PG_TYPE
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/command.h	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,147 @@
+/*
+
+Copyright (C) 2012, 2013 Olaf Till <i7tiol@t-online.de>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+This program 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#ifndef __OCT_PQ_COMMAND__
+
+#define __OCT_PQ_COMMAND__
+
+#include <octave/oct.h>
+#include <octave/ov-struct.h>
+#include <octave/Cell.h>
+
+#include "pq_connection.h"
+#include "converters.h"
+
+class
+command
+{
+public:
+
+  command (octave_pq_connection &connection, std::string &cmd, Cell &rtypes,
+           std::string &who);
+
+  command (octave_pq_connection &connection, std::string &cmd, Cell &params,
+           Cell &ptypes, Cell &rtypes, std::string &who);
+
+  ~command (void)
+  {
+    if (res) PQclear (res);
+
+    if (! all_fetched)
+      {
+        while ((res = PQgetResult (cptr)))
+          PQclear (res);
+      }
+  }
+
+  typedef struct
+  {
+    dim_vector pd, cur;
+    octave_idx_type nd;
+  }
+  count_state;
+
+  typedef int (command::*to_octave_array_fp_t)
+    (char *, octave_value &, int, oct_pq_conv_t *);
+
+  typedef int (command::*to_octave_composite_fp_t)
+    (char *, octave_value &, int);
+
+  int all_results_fetched (void)
+  {
+    return all_fetched;
+  }
+
+  octave_value process_single_result (void);
+
+  int good (void) {return valid;}
+
+private:
+
+  typedef enum {simple, array, composite} oct_type_t;
+
+  void check_first_result (void)
+    {
+      if (! res)
+        {
+          valid = 0;
+          error ("%s: could not execute command: %s", caller.c_str (),
+                 PQerrorMessage (cptr));
+
+        }
+      else if ((state = PQresultStatus (res)) == PGRES_EMPTY_QUERY)
+        {
+          valid = 0;
+          error ("%s: empty command", caller.c_str ());
+        }
+    }
+
+  octave_value command_ok_handler (void)
+  {
+    char *c = PQcmdTuples (res);
+
+    return octave_value (atoi (c));
+  }
+
+  octave_value tuples_ok_handler (void);
+
+  octave_value copy_out_handler (void);
+
+  octave_value copy_in_handler (void);
+
+  oct_pq_conv_t *pgtype_from_octtype (octave_value &);
+
+  oct_pq_conv_t *pgtype_from_spec (std::string &, oct_type_t &);
+
+  oct_pq_conv_t *pgtype_from_spec (Oid, oct_type_t &);
+
+  int from_octave_bin_array (octave_value &oct_arr, oct_pq_dynvec_t &val,
+                             oct_pq_conv_t *);
+
+  int from_octave_bin_composite (octave_value &oct_comp, oct_pq_dynvec_t &val,
+                                 oct_pq_conv_t *);
+
+  int from_octave_str_array (octave_value &oct_arr, oct_pq_dynvec_t &val,
+                             octave_value &type);
+
+  int from_octave_str_composite (octave_value &oct_comp, oct_pq_dynvec_t &val,
+                                 octave_value &type);
+
+  int to_octave_bin_array (char *, octave_value &, int, oct_pq_conv_t *);
+
+  int to_octave_bin_composite (char *, octave_value &, int);
+
+  int to_octave_str_array (char *, octave_value &, int, oct_pq_conv_t *);
+
+  int to_octave_str_composite (char *, octave_value &, int);
+
+  octave_idx_type count_row_major_order (dim_vector &, count_state &, bool);
+
+  PGresult *res;
+  int all_fetched;
+  int valid;
+  ExecStatusType state;
+  octave_pq_connection &conn;
+  PGconn *cptr;
+  Cell &rettypes;
+  std::string &caller;
+
+};
+
+#endif // __OCT_PQ_COMMAND__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/configure.ac	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,27 @@
+#                                               -*- Autoconf -*-
+# Process this file with autoconf to produce a configure script.
+
+AC_PREREQ([2.67])
+AC_INIT([postgresql], [0.1.0], [i7tiol@t-online.de])
+AC_CONFIG_SRCDIR([__pq_connect__.cc])
+
+# Checks for programs.
+AC_PROG_CXX
+AC_CHECK_PROG(OCTAVE, octave, octave)
+AC_CHECK_PROG(MKOCTFILE, mkoctfile, mkoctfile)
+
+# Checks for libraries.
+AC_CHECK_LIB([pq], [PQconnectdb])
+
+# Checks for header files.
+AC_CHECK_HEADER([postgresql/libpq-fe.h], ,[exit 1])
+AC_CHECK_HEADER([postgresql/pg_config_manual.h], ,[exit 1])
+AC_CHECK_HEADER([postgresql/libpq/libpq-fs.h], ,[exit 1])
+
+# Checks for typedefs, structures, and compiler characteristics.
+
+# Checks for library functions.
+AC_FUNC_ERROR_AT_LINE
+
+AC_CONFIG_FILES([Makefile])
+AC_OUTPUT
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/converters.cc	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,677 @@
+/*
+
+Copyright (C) 2012, 2013 Olaf Till <i7tiol@t-online.de>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+This program 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#include <octave/oct.h>
+#include <octave/ov-float.h>
+#include <octave/ov-uint8.h>
+
+#include <postgresql/libpq-fe.h>
+// FIXME: needed for NAMEDATALEN, but defining a lot of stuff which
+// might conflict with names here
+#include <postgresql/pg_config_manual.h>
+
+#include "converters.h"
+
+// remember to adjust OCT_PQ_NUM_CONVERTERS in converters.h
+
+// helper function for debugging
+void print_conv (oct_pq_conv_t *c)
+{
+  printf ("oid: %u, aoid: %u, relid: %u, c: %i, e: %i, nc: %i, n: %s, to_s: %i, to_b: %i, fr_s: %i, fr_b: %i\n",
+          c->oid, c->aoid, c->relid, c->is_composite, c->is_enum, c->is_not_constant, c->name.c_str (), c->to_octave_str ? 1 : 0, c->to_octave_bin ? 1 : 0, c->from_octave_str ? 1 : 0, c->from_octave_bin ? 1 : 0);
+}
+
+/* type bool */
+
+int to_octave_str_bool (char *c, octave_value &ov, int nb)
+{
+  bool tp = (*c == 't' ? true : false);
+
+  ov = octave_value (tp);
+
+  return 0;
+}
+
+int to_octave_bin_bool (char *c, octave_value &ov, int nb)
+{
+  ov = octave_value (bool (*c));
+
+  return 0;
+}
+
+int from_octave_str_bool (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  bool b = ov.bool_value ();
+
+  if (error_state)
+    {
+      error ("can not convert octave_value to bool value");
+      return 1;
+    }
+
+  val.push_back (b ? '1' : '0');
+  val.push_back ('\0');
+
+  return 0;
+}
+
+int from_octave_bin_bool (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  bool b = ov.bool_value ();
+
+  if (error_state)
+    {
+      error ("can not convert octave_value to bool value");
+      return 1;
+    }
+
+  val.push_back (char (b));
+
+  return 0;
+}
+
+oct_pq_conv_t conv_bool = {0, // 16
+                           0, // 1000
+                           0,
+                           false,
+                           false,
+                           false,
+                           "bool",
+                           &to_octave_str_bool,
+                           &to_octave_bin_bool,
+                           &from_octave_str_bool,
+                           &from_octave_bin_bool};
+
+/* end type bool */
+
+/* type oid */
+
+int to_octave_str_oid (char *c, octave_value &ov, int nb)
+{
+  return 1;
+}
+
+int to_octave_bin_oid (char *c, octave_value &ov, int nb)
+{
+  ov = octave_value (octave_uint32 (be32toh (*((uint32_t *) c))));
+
+  return 0;
+}
+
+int from_octave_str_oid (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  return 1;
+}
+
+int from_octave_bin_oid (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  uint32_t oid = ov.uint_value ();
+
+  if (error_state)
+    {
+      error ("can not convert octave_value to oid value");
+      return 1;
+    }
+
+  OCT_PQ_PUT(val, uint32_t, htobe32 (oid))
+
+  return 0;
+}
+
+oct_pq_conv_t conv_oid = {0, // 26
+                          0,
+                          0,
+                          false,
+                          false,
+                          false,
+                          "oid",
+                          &to_octave_str_oid,
+                          &to_octave_bin_oid,
+                          &from_octave_str_oid,
+                          &from_octave_bin_oid};
+
+/* end type oid */
+
+/* type float8 */
+
+int to_octave_str_float8 (char *c, octave_value &ov, int nb)
+{
+  // not implemented
+
+  return 1;
+}
+
+int to_octave_bin_float8 (char *c, octave_value &ov, int nb)
+{
+  union
+  {
+    double d;
+    int64_t i;
+  }
+  swap;
+
+  swap.i = be64toh (*((int64_t *) c));
+
+  ov = octave_value (swap.d);
+
+  return 0;
+}
+
+int from_octave_str_float8 (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  // not implemented
+
+  return 1;
+}
+
+int from_octave_bin_float8 (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  double d = ov.double_value ();
+
+  if (error_state)
+    {
+      error ("can not convert octave_value to float8 value");
+      return 1;
+    }
+
+  union
+  {
+    double d;
+    int64_t i;
+  }
+  swap;
+
+  swap.d = d;
+
+  OCT_PQ_PUT(val, int64_t, htobe64 (swap.i))
+
+  return 0;
+}
+
+oct_pq_conv_t conv_float8 = {0, // 701
+                             0, // 1022
+                             0,
+                             false,
+                             false,
+                             false,
+                             "float8",
+                             &to_octave_str_float8,
+                             &to_octave_bin_float8,
+                             &from_octave_str_float8,
+                             &from_octave_bin_float8};
+
+/* end type float8 */
+
+/* type float4 */
+
+int to_octave_str_float4 (char *c, octave_value &ov, int nb)
+{
+  // not implemented
+
+  return 1;
+}
+
+int to_octave_bin_float4 (char *c, octave_value &ov, int nb)
+{
+  union
+  {
+    float f;
+    int32_t i;
+  }
+  swap;
+
+  swap.i = be32toh (*((int32_t *) c));
+
+  ov = octave_value (swap.f);
+
+  return 0;
+}
+
+int from_octave_str_float4 (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  // not implemented
+
+  return 1;
+}
+
+int from_octave_bin_float4 (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  double f = ov.float_value ();
+
+  if (error_state)
+    {
+      error ("can not convert octave_value to float4 value");
+      return 1;
+    }
+
+  union
+  {
+    float f;
+    int32_t i;
+  }
+  swap;
+
+  swap.f = f;
+
+  OCT_PQ_PUT(val, int32_t, htobe32 (swap.i))
+
+  return 0;
+}
+
+oct_pq_conv_t conv_float4 = {0,
+                             0,
+                             0,
+                             false,
+                             false,
+                             false,
+                             "float4",
+                             &to_octave_str_float4,
+                             &to_octave_bin_float4,
+                             &from_octave_str_float4,
+                             &from_octave_bin_float4};
+
+/* end type float4 */
+
+/* type bytea */
+
+int to_octave_str_bytea (char *c, octave_value &ov, int nb)
+{
+  return 1;
+}
+
+int to_octave_bin_bytea (char *c, octave_value &ov, int nb)
+{
+  uint8NDArray m (dim_vector (nb, 1));
+
+  uint8_t *p = (uint8_t *) m.fortran_vec ();
+  for (octave_idx_type i = 0; i < nb; i++)
+    *(p++) = uint8_t (*(c++));
+
+  ov = octave_value (m);
+
+  return 0;
+}
+
+int from_octave_str_bytea (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  return 1;
+}
+
+int from_octave_bin_bytea (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  uint8NDArray b = ov.uint8_array_value ();
+
+  if (! error_state)
+    {
+      dim_vector dv = b.dims ();
+      if (dv.length () > 2 || (dv(0) > 1 && dv(1) > 1))
+        error ("bytea representation must be one-dimensional");
+    }
+
+  if (error_state)
+    {
+      error ("can not convert octave_value to bytea representation");
+      return 1;
+    }
+
+  octave_idx_type nl = b.numel ();
+
+  for (int i = 0; i < nl; i++)
+    val.push_back (b(i).value ());
+
+  return 0;
+}
+
+oct_pq_conv_t conv_bytea = {0,
+                            0,
+                            0,
+                            false,
+                            false,
+                            false,
+                            "bytea",
+                            &to_octave_str_bytea,
+                            &to_octave_bin_bytea,
+                            &from_octave_str_bytea,
+                            &from_octave_bin_bytea};
+
+/* end type bytea */
+
+/* type text */
+
+int to_octave_str_text (char *c, octave_value &ov, int nb)
+{
+  return 1;
+}
+
+int to_octave_bin_text (char *c, octave_value &ov, int nb)
+{
+  std::string s (c, nb);
+
+  ov = octave_value (s);
+
+  return 0;
+}
+
+int from_octave_str_text (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  return 1;
+}
+
+int from_octave_bin_text (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  std::string s = ov.string_value ();
+
+  if (error_state)
+    {
+      error ("can not convert octave_value to string");
+      return 1;
+    }
+
+  octave_idx_type l = s.size ();
+
+  for (int i = 0; i < l; i++)
+    val.push_back (s[i]);
+
+  return 0;
+}
+
+oct_pq_conv_t conv_text = {0,
+                           0,
+                           0,
+                           false,
+                           false,
+                           false,
+                           "text",
+                           &to_octave_str_text,
+                           &to_octave_bin_text,
+                           &from_octave_str_text,
+                           &from_octave_bin_text};
+
+/* end type text */
+
+/* type varchar */
+
+oct_pq_conv_t conv_varchar = {0,
+                              0,
+                              0,
+                              false,
+                              false,
+                              false,
+                              "varchar",
+                              &to_octave_str_text,
+                              &to_octave_bin_text,
+                              &from_octave_str_text,
+                              &from_octave_bin_text};
+
+/* end type varchar */
+
+/* type bpchar */
+
+oct_pq_conv_t conv_bpchar = {0,
+                             0,
+                             0,
+                             false,
+                             false,
+                             false,
+                             "bpchar",
+                             &to_octave_str_text,
+                             &to_octave_bin_text,
+                             &from_octave_str_text,
+                             &from_octave_bin_text};
+
+/* end type bpchar */
+
+/* type name */
+
+int to_octave_str_name (char *c, octave_value &ov, int nb)
+{
+  return 1;
+}
+
+int to_octave_bin_name (char *c, octave_value &ov, int nb)
+{
+  // FIXME: should we check the string in c?
+
+  std::string s (c, nb);
+
+  ov = octave_value (s);
+
+  return 0;
+}
+
+int from_octave_str_name (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  return 1;
+}
+
+int from_octave_bin_name (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  std::string s = ov.string_value ();
+
+  if (error_state)
+    {
+      error ("can not convert octave_value to string");
+      return 1;
+    }
+
+  octave_idx_type l = s.size ();
+
+  if (l >= NAMEDATALEN)
+    {
+      error ("identifier too long, must be less than %d characters",
+             NAMEDATALEN);
+      return 1;
+    }
+
+  for (int i = 0; i < l; i++)
+    val.push_back (s[i]);
+
+  return 0;
+}
+
+oct_pq_conv_t conv_name = {0,
+                           0,
+                           0,
+                           false,
+                           false,
+                           false,
+                           "name",
+                           &to_octave_str_name,
+                           &to_octave_bin_name,
+                           &from_octave_str_name,
+                           &from_octave_bin_name};
+
+/* end type name */
+
+/* type int2 */
+
+int to_octave_str_int2 (char *c, octave_value &ov, int nb)
+{
+  return 1;
+}
+
+int to_octave_bin_int2 (char *c, octave_value &ov, int nb)
+{
+  ov = octave_value (octave_int16 (int16_t (be16toh (*((int16_t *) c)))));
+
+  return 0;
+}
+
+int from_octave_str_int2 (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  return 1;
+}
+
+int from_octave_bin_int2 (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  int16_t i2 = ov.int_value ();
+
+  if (error_state)
+    {
+      error ("can not convert octave_value to int2 value");
+      return 1;
+    }
+
+  OCT_PQ_PUT(val, int16_t, htobe16 (i2))
+
+  return 0;
+}
+
+oct_pq_conv_t conv_int2 = {0, // 26
+                           0,
+                           0,
+                           false,
+                           false,
+                           false,
+                           "int2",
+                           &to_octave_str_int2,
+                           &to_octave_bin_int2,
+                           &from_octave_str_int2,
+                           &from_octave_bin_int2};
+
+
+/* end type int2 */
+
+/* type int4 */
+
+int to_octave_str_int4 (char *c, octave_value &ov, int nb)
+{
+  return 1;
+}
+
+int to_octave_bin_int4 (char *c, octave_value &ov, int nb)
+{
+  ov = octave_value (octave_int32 (int32_t (be32toh (*((int32_t *) c)))));
+
+  return 0;
+}
+
+int from_octave_str_int4 (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  return 1;
+}
+
+int from_octave_bin_int4 (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  int32_t i4 = ov.int_value ();
+
+  if (error_state)
+    {
+      error ("can not convert octave_value to int4 value");
+      return 1;
+    }
+
+  OCT_PQ_PUT(val, int32_t, htobe32 (i4))
+
+  return 0;
+}
+
+oct_pq_conv_t conv_int4 = {0,
+                           0,
+                           0,
+                           false,
+                           false,
+                           false,
+                           "int4",
+                           &to_octave_str_int4,
+                           &to_octave_bin_int4,
+                           &from_octave_str_int4,
+                           &from_octave_bin_int4};
+
+
+/* end type int4 */
+
+/* type int8 */
+
+int to_octave_str_int8 (char *c, octave_value &ov, int nb)
+{
+  return 1;
+}
+
+int to_octave_bin_int8 (char *c, octave_value &ov, int nb)
+{
+  ov = octave_value (octave_int64 (int64_t (be64toh (*((int64_t *) c)))));
+
+  return 0;
+}
+
+int from_octave_str_int8 (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  return 1;
+}
+
+int from_octave_bin_int8 (octave_value &ov, oct_pq_dynvec_t &val)
+{
+  int64_t i8 = ov.int64_scalar_value ();
+
+  if (error_state)
+    {
+      error ("can not convert octave_value to int8 value");
+      return 1;
+    }
+
+  OCT_PQ_PUT(val, int64_t, htobe64 (i8))
+
+  return 0;
+}
+
+oct_pq_conv_t conv_int8 = {0,
+                           0,
+                           0,
+                           false,
+                           false,
+                           false,
+                           "int8",
+                           &to_octave_str_int8,
+                           &to_octave_bin_int8,
+                           &from_octave_str_int8,
+                           &from_octave_bin_int8};
+
+
+/* end type int8 */
+
+/* type money */
+
+oct_pq_conv_t conv_money = {0,
+                            0,
+                            0,
+                            false,
+                            false,
+                            false,
+                            "money",
+                            &to_octave_str_int8,
+                            &to_octave_bin_int8,
+                            &from_octave_str_int8,
+                            &from_octave_bin_int8};
+
+/* end type money */
+
+oct_pq_conv_t *conv_ptrs[OCT_PQ_NUM_CONVERTERS] = {&conv_bool,
+                                                   &conv_oid,
+                                                   &conv_float8,
+                                                   &conv_float4,
+                                                   &conv_text,
+                                                   &conv_varchar,
+                                                   &conv_bpchar,
+                                                   &conv_name,
+                                                   &conv_bytea,
+                                                   &conv_int2,
+                                                   &conv_int4,
+                                                   &conv_int8,
+                                                   &conv_money};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/converters.h	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,115 @@
+/*
+
+Copyright (C) 2012, 2013 Olaf Till <i7tiol@t-online.de>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+This program 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#ifndef __OCT_PQ_CONVERTERS__
+
+#define __OCT_PQ_CONVERTERS__
+
+#include <octave/oct.h>
+
+#include <stdint.h>
+#include <endian.h>
+
+#include <vector>
+#include <string>
+
+#include <postgresql/libpq-fe.h>
+
+#define OCT_PQ_NUM_CONVERTERS 13
+
+typedef std::vector<char> oct_pq_dynvec_t;
+
+typedef int (*oct_pq_to_octave_fp_t) (char *, octave_value &, int);
+
+typedef int (*oct_pq_from_octave_fp_t) (octave_value &, oct_pq_dynvec_t &);
+
+// some objects will be constants, some will be allocated
+typedef struct
+{
+  Oid oid; // read from server
+  Oid aoid; // array oid // read from server
+  Oid relid; // pg_attribute.attrelid, zero for non-composite types
+  bool is_composite; // false for constant objects
+  bool is_enum; // false for constant objects
+  bool is_not_constant; // false for constant objects
+  // const char *name; not all constants, use std::string
+  std::string name;
+  oct_pq_to_octave_fp_t to_octave_str;
+  oct_pq_to_octave_fp_t to_octave_bin;
+  oct_pq_from_octave_fp_t from_octave_str;
+  oct_pq_from_octave_fp_t from_octave_bin;
+}
+  oct_pq_conv_t;
+
+// a wrapper class around oct_pq_conv_t* to provide a default
+// constructor which nullifies it, for efficient use of maps, where
+// checking for the presence of a key while inserting it can rely on a
+// newly generated key mapping to a value of NULL
+class oct_pq_conv_wrapper_t
+{
+public:
+
+  oct_pq_conv_wrapper_t (void) : conv (NULL) {}
+
+  oct_pq_conv_wrapper_t (oct_pq_conv_t *c) : conv (c) {}
+
+  operator oct_pq_conv_t *&(void) { return conv; }
+
+  oct_pq_conv_t *&operator->(void) { return conv; }
+
+private:
+
+  oct_pq_conv_t *conv;
+};
+
+// helper function for debugging
+void print_conv (oct_pq_conv_t *);
+
+extern oct_pq_conv_t *conv_ptrs[OCT_PQ_NUM_CONVERTERS];
+
+// append bytes of value 'val' of type 'type' to dynamic char vector 'dv'
+#define OCT_PQ_PUT(dv, type, val)                       \
+  dv.resize (dv.size () + sizeof (type));               \
+  *((type *) &(dv.end ()[-sizeof (type)])) = val;
+
+// increase size of dynamic char vector 'dv' by size of uint32 and
+// store the new size in a variable named 'var' of octave_idx_type;
+// after further increasing 'dv', OCT_PQ_FILL_UINT32_PLACEHOLDER
+// should be used with equal arguments
+#define OCT_PQ_SET_UINT32_PLACEHOLDER(dv, var)          \
+  octave_idx_type var = dv.size () + sizeof (uint32_t); \
+  dv.resize (var);
+// to be used after OCT_PQ_SET_UINT32_PLACEHOLDER with equal
+// arguments; calculate difference between current size of dynamic
+// char vector 'dv' and a previous size stored in a variable named
+// 'var', and write this difference, converted to uint32_t in network
+// byte order, to the placeholder within 'dv' just before the position
+// stored in 'var'
+#define OCT_PQ_FILL_UINT32_PLACEHOLDER(dv, var)                         \
+  *((uint32_t *) &(dv[var - sizeof (uint32_t)])) = htobe32 (dv.size () - var);
+
+#define OCT_PQ_DECL_GET_INT32(retvar, pointer, type)    \
+  type retvar = be32toh (*((type *) pointer));          \
+  pointer += 4;
+
+#define OCT_PQ_GET_INT32(retvar, pointer, type)         \
+  retvar = be32toh (*((type *) pointer));          \
+  pointer += 4;
+
+#endif // __OCT_PQ_CONVERTERS__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/converters_arr_comp.cc	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,456 @@
+/*
+
+Copyright (C) 2012, 2013 Olaf Till <i7tiol@t-online.de>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+This program 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#include <octave/oct.h>
+#include <octave/ov-struct.h>
+#include <octave/Cell.h>
+#include <octave/lo-ieee.h>
+
+#include <stdint.h>
+#include <endian.h>
+
+#include "command.h"
+
+octave_idx_type command::count_row_major_order (dim_vector &dv,
+                                                count_state &state, bool init)
+{
+  if (init)
+    {
+      state.nd = dv.length ();
+
+      state.cur.resize (state.nd);
+
+      state.pd.resize (state.nd);
+
+      // cannot be done with resize in multiple initializations
+      // (resizing to n<2 not possible) and there is no fill() method
+      for (octave_idx_type i = 0; i < state.nd; i++)
+        {
+          state.cur(i) = 0;
+          state.pd(i) = 1;
+        }
+
+      for (octave_idx_type i = 0; i < state.nd - 1; i++)
+        {
+           state.pd(i + 1) = state.pd(i) * dv(i);
+        }
+
+      return 0;
+    }
+  else
+    {
+      octave_idx_type nd = state.nd;
+
+      if (nd > 0)
+        {
+          octave_idx_type ret = 0;
+
+          state.cur(nd - 1)++;
+
+          for (octave_idx_type i = nd - 1; i > 0; i--)
+            {
+              if (state.cur(i) == dv(i))
+                {
+                  state.cur(i) = 0;
+                  state.cur(i - 1)++;
+                }
+
+              ret += state.cur(i) * state.pd(i);
+            }
+
+          if (state.cur(0) == dv(0))
+            ret = -1; // signals overflow
+          else
+            ret += state.cur(0) * state.pd(0);
+
+          return ret;
+        }
+      else
+        return -1;
+    }
+}
+
+int command::from_octave_bin_array (octave_value &oct_arr, oct_pq_dynvec_t &val,
+                                    oct_pq_conv_t *conv)
+{
+  octave_scalar_map m = oct_arr.scalar_map_value ();
+  if (error_state)
+    {
+      error ("%s: Postgresql array parameter no Octave structure",
+             caller.c_str ());
+      return 1;
+    }
+
+  if (! m.isfield ("ndims") || ! m.isfield ("data"))
+    {
+      error ("%s: field 'ndims' or 'data' missing in parameter for Postgresql array", caller.c_str ());
+      return 1;
+    }
+
+  octave_idx_type nd_pq = m.contents ("ndims").int_value ();
+  Cell arr = m.contents ("data").cell_value ();
+  if (error_state || nd_pq < 0)
+    {
+      error ("%s: 'ndims' and 'data' could not be converted to non-negative integer and cell-array in parameter for Postgresql array", caller.c_str ());
+      return 1;
+    }
+
+  RowVector lb;
+
+  // Are lbounds given?
+  if (m.isfield ("lbounds"))
+    {
+      lb = m.contents ("lbounds").row_vector_value ();
+      if (error_state)
+        {
+          error ("%s: could not convert given enumeration bases for array to row vector", caller.c_str ());
+          return 1;
+        }
+    }
+
+  octave_idx_type nl = arr.numel ();
+
+  // dimensions of Octaves representation of postgresql array
+  dim_vector d = arr.dims ();
+  d.chop_trailing_singletons ();
+  int nd_oct = d.length ();
+  if (nd_oct == 2 && d(1) == 1)
+    nd_oct = 1;
+
+  // check dimensions
+  if (nd_oct > nd_pq)
+    {
+      error ("given representation of postgresql array has more dimensions than specified");
+      return 1;
+    }
+
+  // check lbounds
+  if (nd_pq > 0 && lb.is_empty ())
+    lb.resize (nd_pq, 1); // fill with 1
+  else if (lb.length () != nd_pq)
+    {
+      error ("number of specified enumeration bases for array does not match specified number of dimensions");
+      return 1;
+    }
+
+  // ndim
+  OCT_PQ_PUT(val, int32_t, htobe32 ((int32_t) nd_pq))
+  // always make a NULL-bitmap, we don't scan for NULLs to see if it
+  // is really necessary
+  OCT_PQ_PUT(val, int32_t, htobe32 ((int32_t) 1))
+  // element OID
+  OCT_PQ_PUT(val, uint32_t, htobe32 ((uint32_t) conv->oid))
+  // dims, lbounds
+  for (int i = 0; i < nd_pq; i++)
+    {
+      OCT_PQ_PUT(val, int32_t, htobe32 ((int32_t) (i < nd_oct ? d(i) : 1)))
+      OCT_PQ_PUT(val, int32_t, htobe32 ((int32_t) lb(i)))
+    }
+  // elements
+  count_state state;
+  count_row_major_order (d, state, true); // initialize counter
+  for (int i = 0, ti = 0; ti < nl;
+       ti++, i = count_row_major_order (d, state, false))
+    {
+      if (arr(i).is_real_scalar () && arr(i).isna ().bool_value ())
+        // a length value (uint32_t) would not have the 6 highest bits
+        // set (while this has all bits set)
+        { OCT_PQ_PUT(val, int32_t, htobe32 ((int32_t) -1)) }
+      else
+        {
+          OCT_PQ_SET_UINT32_PLACEHOLDER(val, temp_pos)
+
+            if (conv->is_composite)
+              {
+                if (from_octave_bin_composite (arr(i), val, conv))
+                  return 1;
+              }
+            else
+              {
+                if (conv->from_octave_bin (arr(i), val))
+                  return 1;
+              }
+
+          OCT_PQ_FILL_UINT32_PLACEHOLDER(val, temp_pos)
+        }
+    }
+
+  return 0;
+}
+
+int command::from_octave_bin_composite (octave_value &oct_comp,
+                                        oct_pq_dynvec_t &val,
+                                        oct_pq_conv_t *conv)
+{
+  Cell rec (oct_comp.cell_value ());
+  if (error_state)
+    {
+      error ("%s: Octaves representation of a composite type could not be converted to cell-array", caller.c_str ());
+      return 1;
+    }
+
+  octave_idx_type nl = rec.numel ();
+
+  std::vector<Oid> oids;
+  if (conn.octave_pq_get_cols (conv->relid, oids))
+    return 1;
+
+  if (nl != oids.size ())
+    {
+      error ("%s: Octaves representation of a composite type has incorrect number of elements (%i, should have %i)", caller.c_str (), nl, oids.size ());
+      return 1;
+    }
+
+  // ncols
+  OCT_PQ_PUT(val, int32_t, htobe32 ((int32_t) nl))
+  // elements
+  for (int i = 0; i < nl; i++)
+    {
+      // element OID
+      OCT_PQ_PUT(val, uint32_t, htobe32 ((uint32_t) oids[i]))
+      if (rec(i).is_real_scalar () && rec(i).isna ().bool_value ())
+        // a length value (uint32_t) would not have the 6 highest bits
+        // set (while this has all bits set)
+        { OCT_PQ_PUT(val, int32_t, htobe32 ((int32_t) -1)) }
+      else
+        {
+          OCT_PQ_SET_UINT32_PLACEHOLDER(val, temp_pos)
+
+          oct_pq_conv_t *el_conv;
+          oct_type_t oct_type;
+
+          if (! (el_conv = pgtype_from_spec (oids[i], oct_type)))
+            return 1;
+
+          switch (oct_type)
+            {
+            case simple:
+              if (el_conv->from_octave_bin (rec(i), val))
+                return 1;
+              break;
+
+            case array:
+              if (from_octave_bin_array (rec(i), val, el_conv))
+                return 1;
+              break;
+
+            case composite:
+              if (from_octave_bin_composite (rec(i), val, el_conv))
+                return 1;
+              break;
+
+            default:
+              // should not get here
+              error ("%s: internal error, undefined type identifier",
+                     caller.c_str ());
+              return 1;
+            }
+
+          OCT_PQ_FILL_UINT32_PLACEHOLDER(val, temp_pos)
+        }
+    }
+
+  return 0;
+}
+
+int command::from_octave_str_array (octave_value &oct_arr, oct_pq_dynvec_t &val,
+                                    octave_value &type)
+{
+  // not implemented
+  error ("not implemented");
+  return 1;
+
+  return 0;
+}
+
+int command::from_octave_str_composite (octave_value &oct_comp,
+                                        oct_pq_dynvec_t &val,
+                                        octave_value &type)
+{
+  // not implemented
+  error ("not implemented");
+  return 1;
+
+  return 0;
+}
+
+int command::to_octave_bin_array (char *v, octave_value &ov, int nb,
+                                  oct_pq_conv_t *conv)
+{
+  char *p = v;
+
+  // ndim
+  OCT_PQ_DECL_GET_INT32(ndim, p, int32_t)
+  // has NULL bitmap, this information is not used
+  OCT_PQ_DECL_GET_INT32(hasnull, p, int32_t)
+  // element OID
+  OCT_PQ_DECL_GET_INT32(oid, p, uint32_t)
+
+  // check element OID
+  if (oid != conv->oid)
+    {
+      error ("%s: element oid %i sent by server does not match element oid %i expected for array with oid %i",
+             caller.c_str (), oid, conv->oid, conv->aoid);
+      return 1;
+    }
+
+  // dims, lbounds
+  dim_vector dv;
+  dv.resize (ndim, 0); // ndim < 2 is treated as ndim == 2
+  if (ndim == 1)
+    dv(1) = 1;
+
+  RowVector lbounds (ndim);
+
+  for (int i = 0; i < ndim; i++)
+    {
+      OCT_PQ_GET_INT32(dv(i), p, int32_t)
+      OCT_PQ_GET_INT32(lbounds(i), p, int32_t)
+    }
+  //
+
+  // elements
+  octave_idx_type nl = dv.numel ();
+  Cell c (dv);
+  count_state state;
+  count_row_major_order (dv, state, true); // initialize counter
+  for (int i = 0, ti = 0; ti < nl;
+       ti++, i = count_row_major_order (dv, state, false))
+    {
+      OCT_PQ_DECL_GET_INT32(null_id, p, int32_t)
+      if (null_id == -1)
+        // NULL
+        c(i) = octave_value (octave_NA);
+      else
+        {
+          uint32_t nb_el = uint32_t (null_id);
+
+          octave_value ov_el;
+
+          if (conv->is_composite)
+            {
+              if (to_octave_bin_composite (p, ov_el, nb_el))
+                return 1;
+            }
+          else
+            {
+              if (conv->to_octave_bin (p, ov_el, nb_el))
+                return 1;
+            }
+
+          p += nb_el;
+
+          c(i) = ov_el;
+        }
+    }
+
+  octave_scalar_map m;
+  m.assign ("data", octave_value (c));
+  m.assign ("ndims", octave_value (ndim));
+  m.assign ("lbounds", octave_value (lbounds));
+
+  ov = octave_value (m);
+
+  return 0;
+}
+
+int command::to_octave_bin_composite (char *v, octave_value &ov, int nb)
+{
+  char *p = v;
+
+  // ncols
+  OCT_PQ_DECL_GET_INT32(nl, p, int32_t)
+
+  // elements
+  Cell c (nl, 1);
+  for (int i = 0; i < nl; i++)
+    {
+      // element OID
+      OCT_PQ_DECL_GET_INT32(oid, p, uint32_t)
+
+      OCT_PQ_DECL_GET_INT32(null_id, p, int32_t)
+
+      if (null_id == -1)
+        // NULL
+        c(i) = octave_value (octave_NA);
+      else
+        {
+          uint32_t nb_el = uint32_t (null_id);
+
+          oct_pq_conv_t *el_conv;
+          oct_type_t oct_type;
+
+          if (! (el_conv = pgtype_from_spec (oid, oct_type)))
+            return 1;
+
+          octave_value el;
+          switch (oct_type)
+            {
+            case simple:
+              if (el_conv->to_octave_bin (p, el, nb_el))
+                return 1;
+              break;
+
+            case array:
+              if (to_octave_bin_array (p, el, nb_el, el_conv))
+                return 1;
+              break;
+
+            case composite:
+              if (to_octave_bin_composite (p, el, nb_el))
+                return 1;
+              break;
+
+            default:
+              // should not get here
+              error ("%s: internal error, undefined type identifier",
+                     caller.c_str ());
+              return 1;
+            }
+
+          p += nb_el;
+
+          c(i) = el;
+        }
+    }
+
+  ov = octave_value (c);
+
+  return 0;
+}
+
+
+int command::to_octave_str_array (char *v, octave_value &ov, int nb,
+                                  oct_pq_conv_t *conv)
+{
+  // not implemented
+  error ("not implemented");
+  return 1;
+
+  return 0;
+}
+
+int command::to_octave_str_composite (char *v, octave_value &ov, int nb)
+{
+  // not implemented
+  error ("not implemented");
+  return 1;
+
+  return 0;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/pq_close.cc	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,50 @@
+/*
+
+Copyright (C) 2012 Olaf Till <i7tiol@t-online.de>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+This program 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#include <octave/oct.h>
+
+#include "pq_connection.h"
+
+// PKG_ADD: autoload ("pq_close", "pq_interface.oct");
+
+DEFUN_DLD (pq_close, args, ,
+           "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} {@var{id}} pq_close (@var{connection})\n\
+Text.\n\
+\n\
+@end deftypefn")
+{
+  std::string fname ("pq_close");
+
+  if (args.length () != 1 ||
+      args(0).type_id () != octave_pq_connection::static_type_id ())
+    {
+      print_usage ();
+
+      return octave_value_list ();
+    }
+
+  octave_base_value& rep = const_cast<octave_base_value&> (args(0).get_rep ());
+
+  octave_pq_connection &oct_pq_conn = dynamic_cast<octave_pq_connection&> (rep);
+
+  oct_pq_conn.octave_pq_close ();
+
+  return octave_value_list ();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/pq_connection.cc	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,478 @@
+/*
+
+Copyright (C) 2012, 2013 Olaf Till <i7tiol@t-online.de>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+This program 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#include "pq_connection.h"
+#include "command.h"
+
+DEFINE_OV_TYPEID_FUNCTIONS_AND_DATA (octave_pq_connection, "PGconn", "PGconn")
+
+octave_pq_connection::octave_pq_connection (std::string arg)
+: postgres (0), conv_map (), name_conv_map (&map_str_cmp)
+{
+  static bool type_registered = false;
+
+  if (! type_registered) register_type ();
+
+  conn = PQconnectdb (arg.c_str ());
+
+  if (! conn || PQstatus (conn) == CONNECTION_BAD)
+    {
+      if (conn)
+        {
+          PQfinish (conn);
+
+          conn = NULL;
+        }
+
+      error ("PQ connection attempt failed");
+    }
+  else
+    {
+      // init name converter-map (kind of "bootstrapping")
+      for (int i = 0; i < OCT_PQ_NUM_CONVERTERS; i++)
+        name_conv_map[conv_ptrs[i]->name.c_str ()] = conv_ptrs[i];
+
+      if (octave_pq_get_postgres_oid () ||
+          octave_pq_fill_base_types () ||
+          octave_pq_get_composite_types () ||
+          octave_pq_get_enum_types ())
+        {
+          PQfinish (conn);
+
+          conn = NULL;
+
+          error ("could not read types");
+        }
+    }
+}
+
+octave_pq_connection::~octave_pq_connection (void)
+{
+  if (conn)
+    {
+      PQfinish (conn);
+
+      octave_pq_delete_non_constant_types ();
+    }
+}
+
+void octave_pq_connection::octave_pq_close (void)
+{
+  if (conn)
+    {
+      PQfinish (conn);
+
+      octave_pq_delete_non_constant_types ();
+
+      conn = NULL;
+    }
+  else
+    error ("PGconn object not open");
+}
+
+void octave_pq_connection::octave_pq_delete_non_constant_types (void)
+{
+  // In the first map, allocated types are usually referenced twice
+  // (by oid and aoid). Yet we need no refcount as long as we go
+  // through the name map as the last, since there (the same) types
+  // are only referenced once.
+
+  std::vector<oct_pq_conv_map_t::iterator> t_it_v;
+
+  for (oct_pq_conv_map_t::iterator it = conv_map.begin ();
+       it != conv_map.end ();
+       it++)
+    if (it->second->is_not_constant)
+      t_it_v.push_back (it);
+
+  for (std::vector<oct_pq_conv_map_t::iterator>::iterator it = t_it_v.begin ();
+       it != t_it_v.end (); it++)
+    conv_map.erase (*it);
+
+  std::vector<oct_pq_name_conv_map_t::iterator> t_name_it_v;
+
+  for (oct_pq_name_conv_map_t::iterator it = name_conv_map.begin ();
+       it != name_conv_map.end ();
+       it++)
+    {
+      oct_pq_conv_t *conv = it->second;
+
+      if (conv->is_not_constant)
+        {
+          t_name_it_v.push_back (it);
+
+          delete conv;
+        }
+    }
+
+  for (std::vector<oct_pq_name_conv_map_t::iterator>::iterator it =
+         t_name_it_v.begin ();
+       it != t_name_it_v.end (); it++)
+    name_conv_map.erase (*it);
+}
+
+int octave_pq_connection::octave_pq_get_postgres_oid (void)
+{
+  Cell p, pt, rt (1, 1);
+
+  rt(0) = octave_value ("oid");
+
+  std::string cmd ("select oid from pg_roles where rolname = 'postgres';"),
+    caller ("octave_pq_get_postgres_oid");
+
+  command c (*this, cmd, p, pt, rt, caller);
+  if (! c.good ())
+    {
+      error ("could not read pg_roles");
+      return 1;
+    }
+
+  octave_value res = c.process_single_result ();
+  if (error_state)
+    return 1;
+
+  postgres = res.scalar_map_value ().contents ("data").cell_value ()(0).
+    int_value ();
+  if (error_state)
+    return 1;
+
+  return 0;
+}
+
+int octave_pq_connection::octave_pq_fill_base_types (void)
+{
+  // assert postgres oid had been determined
+  if (! postgres.int_value ()) return 1;
+
+  Cell p (1, 1), pt (1, 1), rt (3, 1);
+  p(0) = postgres;
+  pt(0) = octave_value ("oid");
+  rt(0) = octave_value ("oid");
+  rt(1) = octave_value ("name");
+  rt(2) = octave_value ("oid");
+
+  std::string cmd ("select oid, typname, typarray from pg_type where (typowner = $1 AND typtype = 'b' AND typarray != 0) OR typname = 'record';"),
+    caller ("octave_pq_fill_base_types");
+
+  command c (*this, cmd, p, pt, rt, caller);
+  if (! c.good ())
+    {
+      error ("octave_pq_fill_base_types: could not read pg_type");
+      return 1;
+    }
+
+  octave_value res = c.process_single_result ();
+  if (error_state)
+    return 1;
+
+  Cell tpls = res.scalar_map_value ().contents ("data").cell_value ();
+  if (error_state)
+    {
+      error
+        ("octave_pq_fill_base_types: could not convert result data to cell");
+      return 1;
+    }
+
+  // make a temporary map of server base types (cell row numbers) for searching
+  typedef std::map<std::string, int, bool (*) (const std::string &,
+                                               const std::string &)>
+    bt_map_t;
+  bt_map_t bt_map (&map_string_cmp);
+  for (int i = 0; i < tpls.rows (); i++)
+    bt_map[tpls(i, 1).string_value ()] = i;
+  if (error_state)
+    {
+      error ("octave_pq_fill_base_types: could not read returned result");
+      return 1;
+    }
+
+  for (int i = 0; i < OCT_PQ_NUM_CONVERTERS; i++)
+    {
+      bt_map_t::iterator bt_it;
+      if ((bt_it = bt_map.find (conv_ptrs[i]->name)) == bt_map.end ())
+        {
+          error ("octave_pq_fill_base_types: type %s not found in pg_types",
+                 conv_ptrs[i]->name.c_str ());
+          return 1;
+        }
+      // fill in oid and aoid into static records of converters
+      conv_ptrs[i]->oid = tpls(bt_it->second, 0).int_value ();
+      conv_ptrs[i]->aoid = tpls(bt_it->second, 2).int_value ();
+
+      // fill in map of converters over oid with oid and, if not zero,
+      // also with aoid
+      conv_map[conv_ptrs[i]->oid] = conv_ptrs[i];
+      if (conv_ptrs[i]->aoid != 0)
+        conv_map[conv_ptrs[i]->aoid] = conv_ptrs[i];
+    }
+  if (error_state)
+    {
+      error ("octave_pq_fill_base_types: could not read returned result");
+      return 1;
+    }
+
+  return 0;
+}
+
+int octave_pq_connection::octave_pq_get_composite_types (void)
+{
+  Cell p, pt, rt (4, 1);
+  rt(0) = octave_value ("oid");
+  rt(1) = octave_value ("name");
+  rt(2) = octave_value ("oid");
+  rt(3) = octave_value ("oid");
+
+  std::string cmd ("select oid, typname, typarray, typrelid from pg_type where typtype = 'c';"),
+    caller ("octave_pq_get_composite_types");
+
+  command c (*this, cmd, p, pt, rt, caller);
+  if (! c.good ())
+    {
+      error ("octave_pq_get_composite_types: could not read pg_type");
+      return 1;
+    }
+
+  octave_value res = c.process_single_result ();
+  if (error_state)
+    return 1;
+
+  Cell tpls = res.scalar_map_value ().contents ("data").cell_value ();
+  if (error_state)
+    {
+      error ("octave_pq_get_composite_types: could not convert result data to cell");
+      return 1;
+    }
+
+  for (int i = 0; i < tpls.rows (); i++)
+    {
+      Oid oid = tpls(i, 0).int_value ();
+      Oid aoid = tpls(i, 2).int_value ();
+      Oid relid = tpls(i, 3).int_value ();
+      std::string name = tpls(i, 1).string_value ();
+      if (error_state)
+        {
+          error ("octave_pq_get_composite_types: could not read returned result");
+          return 1;
+        }
+
+      // must be allocated and filled before creating the name map
+      // entry, to get a remaining location for the c-string used as
+      // key
+      oct_pq_conv_t *t_conv = new oct_pq_conv_t;
+      t_conv->oid = oid;
+      t_conv->aoid = aoid;
+      t_conv->relid = relid;
+      t_conv->is_composite = true;
+      t_conv->is_enum = false;
+      t_conv->is_not_constant = true;
+      t_conv->name = name;
+      t_conv->to_octave_str = NULL;
+      t_conv->to_octave_bin = NULL;
+      t_conv->from_octave_str = NULL;
+      t_conv->from_octave_bin = NULL;
+
+      oct_pq_conv_t *&by_oid = conv_map[oid],
+        *&by_name = name_conv_map[t_conv->name.c_str ()];
+      if (by_oid || by_name)
+        {
+          error ("octave_pq_get_composite_types: internal error, key already in typemap (by_oid: %u/%li, by name: %s/%li)",
+                 oid, by_oid, t_conv->name.c_str (), by_name);
+          if (! by_oid) conv_map.erase (oid);
+          if (! by_name) name_conv_map.erase (t_conv->name.c_str ());
+          delete t_conv;
+          return 1;
+        }
+
+      by_oid = by_name = t_conv;
+
+      if (aoid)
+        {
+          oct_pq_conv_t *&by_aoid = conv_map[aoid];
+          if (by_aoid)
+            {
+              error ("octave_pq_get_composite_types: internal error, aoid key %u already in typemap", aoid);
+              conv_map.erase (oid);
+              name_conv_map.erase (t_conv->name.c_str ());
+              delete t_conv;
+              return 1;
+            }
+
+          by_aoid = by_oid;
+        }
+
+    }
+
+  return 0;
+}
+
+int octave_pq_connection::octave_pq_get_enum_types (void)
+{
+  Cell p, pt, rt (3, 1);
+  rt(0) = octave_value ("oid");
+  rt(1) = octave_value ("name");
+  rt(2) = octave_value ("oid");
+
+  std::string cmd ("select oid, typname, typarray from pg_type where typtype = 'e';"),
+    caller ("octave_pq_get_enum_types");
+
+  command c (*this, cmd, p, pt, rt, caller);
+  if (! c.good ())
+    {
+      error ("octave_pq_get_enum_types: could not read pg_type");
+      return 1;
+    }
+ 
+  octave_value res = c.process_single_result ();
+  if (error_state)
+    return 1;
+
+  Cell tpls = res.scalar_map_value ().contents ("data").cell_value ();
+  if (error_state)
+    {
+      error ("octave_pq_get_enum_types: could not convert result data to cell");
+      return 1;
+    }
+
+  for (int i = 0; i < tpls.rows (); i++)
+    {
+      Oid oid = tpls(i, 0).int_value ();
+      Oid aoid = tpls(i, 2).int_value ();
+      std::string name = tpls(i, 1).string_value ();
+      if (error_state)
+        {
+          error ("octave_pq_get_enum_types: could not read returned result");
+          return 1;
+        }
+
+      // must be allocated and filled before creating the name map
+      // entry, to get a remaining location for the c-string used as
+      // key
+      oct_pq_conv_t *t_conv = new oct_pq_conv_t;
+      t_conv->oid = oid;
+      t_conv->aoid = aoid;
+      t_conv->relid = 0;
+      t_conv->is_composite = false;
+      t_conv->is_enum = true;
+      t_conv->is_not_constant = true;
+      t_conv->name = name;
+      t_conv->to_octave_str = NULL;
+      t_conv->to_octave_bin = NULL;
+      t_conv->from_octave_str = NULL;
+      t_conv->from_octave_bin = NULL;
+
+      // we trust there is always an array type in the table
+      oct_pq_conv_t *&by_oid = conv_map[oid], *&by_aoid = conv_map[aoid],
+        *&by_name = name_conv_map[t_conv->name.c_str ()];
+      if (by_oid || by_aoid || by_name)
+        {
+          error ("octave_pq_get_enum_types: internal error, key already in typemap");
+          if (! by_oid) conv_map.erase (oid);
+          if (! by_aoid) conv_map.erase (aoid);
+          if (! by_name) name_conv_map.erase (t_conv->name.c_str ());
+          delete t_conv;
+          return 1;
+        }
+
+      by_oid = by_aoid = by_name = t_conv;
+
+    }
+
+  return 0;
+}
+
+int octave_pq_connection::octave_pq_refresh_types (void)
+{
+  octave_pq_delete_non_constant_types ();
+
+  if (octave_pq_get_composite_types () || octave_pq_get_enum_types ())
+    {
+      if (conn)
+        PQfinish (conn);
+      conn = NULL;
+      error ("octave_pq_refresh_types: could not read types");
+      return 1;
+    }
+  else
+    return 0;
+}
+
+int octave_pq_connection::octave_pq_get_cols (Oid relid, std::vector<Oid> &oids)
+{
+  // printf ("octave_pq_get_cols(relid %u): ", relid);
+
+  Cell p (1, 1), pt (1, 1), rt (2, 1);
+  p(0) = octave_value (octave_uint32 (relid));
+  pt(0) = octave_value ("oid");
+  rt(0) = octave_value ("oid");
+  rt(1) = octave_value ("int2");
+
+  std::string cmd ("select atttypid, attnum from pg_attribute where attrelid = $1;"),
+    caller ("octave_pq_get_cols");
+
+  command c (*this, cmd, p, pt, rt, caller);
+  if (! c.good ())
+    {
+      error ("%s: could not read pg_type", caller.c_str ());
+      return 1;
+    }
+
+  octave_value res = c.process_single_result ();
+  if (error_state)
+    return 1;
+
+  Cell tpls = res.scalar_map_value ().contents ("data").cell_value ();
+  if (error_state)
+    {
+      error
+        ("%s: could not convert result data to cell", caller.c_str ());
+      return 1;
+    }
+
+  octave_idx_type r = tpls.rows ();
+
+  // printf ("%i colums, ", r);
+
+  oids.resize (r);
+
+  // "column" number (attnum) is one-based, so subtract 1
+  for (octave_idx_type i = 0; i < r; i++)
+    {
+      octave_idx_type pos = tpls(i, 1).idx_type_value () - 1;
+
+      // printf ("%u at pos %i, ", tpls(i, 0).uint_value (), pos);
+
+      if (pos >= r)
+        {
+          error ("%s: internal error (?system catalog erroneous?): column position %i greater than ncols %i for relid %u",
+                 caller.c_str (), pos, r, relid);
+          return 1;
+        }
+
+      oids[pos] = tpls(i, 0).uint_value ();
+    }
+  if (error_state)
+    {
+      error ("%s: could not convert result data", caller.c_str ());
+      return 1;
+    }
+
+  // printf ("\n");
+
+  return 0;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/pq_connection.h	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,123 @@
+/*
+
+Copyright (C) 2012, 2013 Olaf Till <i7tiol@t-online.de>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+This program 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#ifndef __OCT_PQ_CONNECTION__
+
+#define __OCT_PQ_CONNECTION__
+
+#include <octave/oct.h>
+
+#include <postgresql/libpq-fe.h>
+
+#include "converters.h"
+
+static bool map_str_cmp (const char *c1, const char *c2)
+{
+  if (strcmp (c1, c2) < 0)
+    return true;
+  else
+    return false;
+}
+
+static bool map_string_cmp (const std::string &s1, const std::string &s2)
+{
+  if (s1.compare (s2) < 0)
+    return true;
+  else
+    return false;
+}
+
+typedef std::map<Oid, oct_pq_conv_wrapper_t> oct_pq_conv_map_t;
+
+typedef std::map<const char *, oct_pq_conv_wrapper_t,
+  bool (*) (const char *, const char *)> oct_pq_name_conv_map_t;
+
+class
+octave_pq_connection : public octave_base_value
+{
+public:
+
+  octave_pq_connection (std::string);
+
+  ~octave_pq_connection (void);
+
+  void octave_pq_close (void);
+
+  int octave_pq_refresh_types (void);
+
+  int octave_pq_get_cols (Oid relid, std::vector<Oid> &);
+
+  PGconn *octave_pq_get_conn (void) { return conn; }
+
+  oct_pq_conv_map_t conv_map;
+
+  oct_pq_name_conv_map_t name_conv_map;
+
+
+  // Octave internal stuff
+
+  bool is_constant (void) const { return true; }
+
+  bool is_defined (void) const { return true; }
+
+  bool is_true (void) const { return conn != 0; }
+
+  void print_raw (std::ostream& os, bool pr_as_read_syntax = false) const
+  {
+    indent (os);
+    os << "<PGconn object>";
+    newline (os);
+  }
+
+  void print (std::ostream& os, bool pr_as_read_syntax = false) const
+  {
+    print_raw (os);
+  }
+
+  bool print_as_scalar (void) const { return true; }
+
+private:
+
+  // needed by Octave for register_type()
+  octave_pq_connection (void) : conn (NULL) { }
+
+  PGconn *conn;
+
+  // Oid of postgres_user, needed to distinguish base types from
+  // others.
+  octave_value postgres;
+
+  void octave_pq_delete_non_constant_types (void);
+
+  // returns zero on success
+  int octave_pq_get_postgres_oid (void);
+
+  // returns zero on success
+  int octave_pq_fill_base_types (void);
+
+  // returns zero on success
+  int octave_pq_get_composite_types (void);
+
+  // returns zero on success
+  int octave_pq_get_enum_types (void);
+
+  DECLARE_OV_TYPEID_FUNCTIONS_AND_DATA
+};
+
+#endif // __OCT_PQ_CONNECTION__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/pq_exec.cc	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,319 @@
+/*
+
+Copyright (C) 2012, 2013 Olaf Till <i7tiol@t-online.de>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+This program 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#include <octave/oct.h>
+#include <octave/parse.h>
+#include <octave/ov-struct.h>
+#include <octave/Cell.h>
+
+#include "command.h"
+
+// PKG_disabled_ADD: autoload ("pq_exec", "pq_interface.oct");
+// PKG_ADD: autoload ("pq_exec_params", "pq_interface.oct");
+// PKG_ADD: __all_db_opts__ ("pq_exec_params");
+
+
+#if 0
+
+// I left this here because of its (formerly working) functionality of
+// reading more than one result. But the code (and the helptext, too)
+// has not been adapted to general changes and is not working, and it
+// would need converters for text mode to be useful. Anyway I don't
+// see why one should need to execute many commands with one line,
+// except if one wants to use some unchanged external SQL code. I'll
+// probably wait till someone expresses such a need.
+
+DEFUN_DLD (pq_exec, args, ,
+           "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} {@var{id}} pq_exec (@var{connection}, @var{command})\n\
+@deftypefnx {Loadable Function} {@var{id}} pq_exec (@var{connection}, @var{command}, @var{copydata}, @dots{})\n\
+Sends the string @var{command}, which should contain one or more SQL commands, over the connection @var{connection} and returns multiple output values, one for each command. For queries (commands potentially returning data), the output will be a structure with fields @code{data} (containing a cell array with the data) and @code{columns} (containing the column headers). For other commands, the output will be the number of affected rows in the database. For each command in @var{command} containing a @code{COPY FROM STDIN}, an additional argument @var{copydata} must be supplied which is either a cell-array with suitable data or a handle for a function which will return parts of this cell-array successively, one for each call, and @code{0} when ready.\n\
+\n\
+@end deftypefn")
+{
+  std::string fname ("pq_exec");
+
+  octave_value_list retval;
+
+  if (args.length () < 2 || args.length () > 3 ||
+      args(0).type_id () != octave_pq_connection::static_type_id ())
+    {
+      print_usage ();
+
+      return retval;
+    }
+
+  std::string cmd (args(1).string_value ());
+
+  if (error_state)
+    {
+      error ("%s: second argument can not be converted to a string", fname.c_str ());
+
+      return retval;
+    }
+
+  octave_base_value& rep = const_cast<octave_base_value&> (args(0).get_rep ());
+
+  octave_pq_connection &oct_pq_conn = dynamic_cast<octave_pq_connection&> (rep);
+
+  Cell rettypes; // not implemented here
+
+  command c (oct_pq_conn, cmd, rettypes, fname);
+
+  if (c.good ())
+    {
+      while (true)
+        {
+          octave_value val;
+
+          val = c.process_single_result ();
+
+          if (! c.good () || c.all_results_fetched ())
+            break;
+          else
+            {
+              int l = retval.length ();
+
+              retval.resize (l + 1);
+
+              retval (l) = val;
+            }
+        }
+    }
+
+  return retval;
+}
+
+#endif // code disabled
+
+DEFUN_DLD (pq_exec_params, args, ,
+           "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} pq_exec_params (@var{connection}, @var{command})\n\
+@deftypefnx {Loadable Function} pq_exec_params (@var{connection}, @var{command}, @var{params})\n\
+@deftypefnx {Loadable Function} pq_exec_params (@var{connection}, @var{command}, @var{settings})\n\
+@deftypefnx {Loadable Function} pq_exec_params (@var{connection}, @var{command}, @var{params}, @var{settings})\n\
+Sends the string @var{command}, which must contain a single SQL command, over the connection @var{connection}. Parameters in @var{command} can be replaced by $1, $2, etc and their values given in the one-dimensional cell-array @var{params}. Parameters of composite type sent this way must have their type defined in the database. For typeconversions, the package maintains a notion of defined types, which should be refreshed with @code{pq_update_types} if types are defined or dropped after establishing the connection. @var{settings} is a structure of settings, it can be created by @code{setdbopts}.\n\
+\n\
+Settings currently understood by @code{pq_exec_params}:\n\
+\n\
+@code{param_types}: One-dimensional cell-array with type specifications for parameters in @var{params}. If present, must have the same length as @var{params}. Entries may be empty if no specification is necessary (see below). Type specifications are strings corresponding to the entries returned by @code{SELECT typname FROM pg_type WHERE typarray != 0 OR typtype = 'c';}, optionally having @code{[]} appended (without space) to indicate an array.\n\
+\n\
+For queries (commands potentially returning data), the output will be a structure with fields @code{data} (containing a cell array with the data, columns correspond to returned database columns, rows correspond to returned tuples) and @code{columns} (containing the column headers). Copy commands do not work as yet. For other commands, the output will be the number of affected rows in the database.\n\
+\n\
+Mapping of currently implemented Postgresql types to Octave types\n\
+\n\
+The last column indicates whether specification of type (see above) is necessary for conversion from Octave type to Postgresql type, i.e. if Postgresql type is not deduced from the type of the Octave variable.\n\
+\n\
+@multitable {Postgresql} {Octave type blah blah blah blah blah} {Spec.}\n\
+@headitem Postgresql @tab Octave @tab Spec.\n\
+@item bool\n\
+@tab logical scalar\n\
+@tab no\n\
+@item oid\n\
+@tab uint32 scalar\n\
+@tab no\n\
+@item float8\n\
+@tab double scalar\n\
+@tab no\n\
+@item float4\n\
+@tab single scalar\n\
+@tab no\n\
+@item text\n\
+@tab string\n\
+@tab no\n\
+@item varchar\n\
+@tab string\n\
+@tab yes\n\
+@item bpchar\n\
+@tab string\n\
+@tab yes\n\
+@item name\n\
+@tab string of length < @code{NAMEDATALEN} (often 64)\n\
+@tab yes\n\
+@item bytea\n\
+@tab one-dimensional array of uint8\n\
+@tab no\n\
+@item int2\n\
+@tab int16 scalar\n\
+@tab no\n\
+@item int4\n\
+@tab int32 scalar\n\
+@tab no\n\
+@item int8\n\
+@tab int64 scalar\n\
+@tab no\n\
+@item money\n\
+@tab int64 scalar, which is 100 times the currency value to enable storing the 'small currency' (e.g. Cent) fraction in the last two digits\n\
+@tab yes\n\
+@item any array\n\
+@tab Structure with fields @code{data} (holding a cell-array with entries of a type corresponding to the Postgresql element type), @code{ndims} (holding the number of dimensions of the corresponding Postgresql array, since this can not be deduced from the dimensions of the Octave cell-array in all cases), and optionally (but always present in returned values) @code{lbounds} (a row vector of enumeration bases for all dimensions, default is @code{ones (1, ndims)}, see Postgresql documentation). Array elements may not correspond to arrays in Postgresql (use additional dimensions for this), but may correspond to composite types, which is allowed to lead to arbitrarily deep nesting.\n\
+@tab yes\n\
+@item any composite type\n\
+@tab One-dimensional cell-array with entries of types corresponding to the respective Postgresql types. Entries may also correspond to an array-type or composite type; this is allowed to lead to arbitrarily deep nesting.\n\
+@tab yes\n\
+@end multitable\n\
+Octaves @code{NA} corresponds to a Postgresql NULL value (not @code{NaN}, which is interpreted as a value of a float type!).\n\
+@seealso{pq_update_types}\n\
+@end deftypefn")
+{
+  std::string fname ("pq_exec_params");
+
+  octave_value retval;
+
+  int nargs = args.length ();
+
+  if (nargs == 1 && args(0).is_string () &&
+      args(0).string_value () == "defaults")
+    {
+      octave_value_list f_args (2);
+      Matrix a;
+
+      f_args(0) = octave_value ("param_types");
+      f_args(1) = octave_value (a);
+
+      return feval ("setdbopts", f_args, 1);
+    }
+
+  if (nargs < 2 || nargs > 4 ||
+      args(0).type_id () != octave_pq_connection::static_type_id ())
+    {
+      print_usage ();
+
+      return retval;
+    }
+
+  std::string cmd (args(1).string_value ());
+
+  if (error_state)
+    {
+      error ("%s: second argument can not be converted to a string", fname.c_str ());
+
+      return retval;
+    }
+
+  octave_base_value& rep = const_cast<octave_base_value&> (args(0).get_rep ());
+
+  octave_pq_connection &oct_pq_conn = dynamic_cast<octave_pq_connection&> (rep);
+
+
+  /*
+  printf ("oid map:\n");
+  for (oct_pq_conv_map_t::iterator it = oct_pq_conn.conv_map.begin ();
+       it != oct_pq_conn.conv_map.end (); it++)
+    {
+      printf ("key: %u; ", it->first);
+      print_conv (it->second);
+    }
+  printf ("\n");
+
+  printf ("name map:\n");
+  for (oct_pq_name_conv_map_t::iterator it = oct_pq_conn.name_conv_map.begin ();
+       it != oct_pq_conn.name_conv_map.end (); it++)
+    {
+      printf ("key: %s; ", it->first);
+      print_conv (it->second);
+    }
+  printf ("\n");
+  */
+
+
+  Cell params;
+
+  octave_scalar_map settings;
+
+  if (nargs == 3)
+    {
+      if (args(2).is_cell ())
+        params = args(2).cell_value ();
+      else
+        settings = args(2).scalar_map_value ();
+
+      if (error_state)
+        {
+          error ("%s: third argument neither cell-array nor scalar structure",
+                 fname.c_str ());
+
+          return retval;
+        }
+    }
+  else if (nargs == 4)
+    {
+      params = args(2).cell_value ();
+      if (error_state)
+        {
+          error ("%s: could not convert third argument to cell-array",
+                 fname.c_str ());
+
+          return retval;
+        }
+      settings = args(3).scalar_map_value ();
+      if (error_state)
+        {
+          error ("%s: could not convert fourth argument to scalar structure");
+
+          return retval;
+        }
+    }
+
+  int nparams = params.length ();
+
+  dim_vector pdims = params.dims ();
+
+  if (pdims.length () > 2 || (pdims(0) > 1 && pdims(1) > 1))
+    {
+      error ("%s: cell-array of parameters must not be more than one-dimensional",
+             fname.c_str ());
+
+      return retval;
+    }
+
+  octave_value_list f_args (3);
+
+  octave_value_list f_ret;
+
+  f_args(0) = octave_value (settings);
+  f_args(1) = octave_value ("param_types");
+  f_args(2) = octave_value (Cell (1, nparams));
+
+  f_ret = feval ("getdbopts", f_args, 1);
+  Cell ptypes = f_ret(0).cell_value ();
+  if (error_state)
+    {
+      error ("could not convert param_types to cell");
+
+      return retval;
+    }
+
+  if (ptypes.length () != nparams)
+    {
+      error ("%s: if given, cell-array of parameter types must have same length as cell-array of parameters",
+             fname.c_str ());
+
+      return retval;
+    }
+
+  Cell rtypes;
+
+  command c (oct_pq_conn, cmd, params, ptypes, rtypes, fname);
+
+  if (c.good ())
+    retval = c.process_single_result ();
+
+  return retval;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/pq_lo.cc	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,394 @@
+/*
+
+Copyright (C) 2013 Olaf Till <i7tiol@t-online.de>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+This program 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#include <octave/oct.h>
+#include <octave/ov-struct.h>
+#include <octave/Cell.h>
+
+#include "command.h"
+#include <postgresql/libpq/libpq-fs.h>
+
+// PKG_ADD: autoload ("pq_lo_import", "pq_interface.oct");
+// PKG_ADD: autoload ("pq_lo_export", "pq_interface.oct");
+// PKG_ADD: autoload ("pq_lo_unlink", "pq_interface.oct");
+
+
+DEFUN_DLD (pq_lo_import, args, ,
+           "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} {@var{oid}} pq_lo_import (@var{connection}, @var{path})\n\
+Imports the file in @var{path} on the client side as a large object into the database associated with @var{connection} and returns the Oid of the new large object.\n\
+@end deftypefn")
+{
+  std::string fname ("pq_lo_import");
+
+  octave_value retval;
+
+  if (args.length () != 2 ||
+      args(0).type_id () != octave_pq_connection::static_type_id ())
+    {
+      print_usage ();
+
+      return retval;
+    }
+
+  std::string path (args(1).string_value ());
+
+  if (error_state)
+    {
+      error ("%s: second argument can not be converted to a string",
+             fname.c_str ());
+
+      return retval;
+    }
+
+  octave_base_value& rep = const_cast<octave_base_value&> (args(0).get_rep ());
+
+  octave_pq_connection &oct_pq_conn = dynamic_cast<octave_pq_connection&> (rep);
+
+  PGconn *conn = oct_pq_conn.octave_pq_get_conn ();
+
+  if (! conn)
+    {
+      error ("%s: connection not open", fname.c_str ());
+      return retval;
+    }
+
+  bool make_tblock = false;
+  switch (PQtransactionStatus (conn))
+    {
+    case PQTRANS_IDLE:
+      make_tblock = true;
+      break;
+    case PQTRANS_INTRANS:
+      break;
+    case PQTRANS_INERROR:
+      error ("%s: can't manipulate large objects within a failed transaction block",
+             fname.c_str ());
+      break;
+    case PQTRANS_UNKNOWN:
+      error ("%s: connection is bad", fname.c_str ());
+      break;
+    default: // includes PQTRANS_ACTIVE
+      error ("%s: unexpected connection state", fname.c_str ());
+    }
+
+  if (error_state)
+    return retval;
+
+  if (make_tblock)
+    {
+      std::string cmd ("begin;");
+      Cell params;
+      Cell ptypes (1, 0);
+      Cell rtypes;
+      command c (oct_pq_conn, cmd, params, ptypes, rtypes, fname);
+
+      if (c.good ())
+        c.process_single_result ();
+
+      if (! c.good ())
+        {
+          error ("%s: could not begin transaction", fname.c_str ());
+          return retval;
+        }
+    }
+
+  Oid oid;
+
+  bool import_error = false;
+  std::string msg;
+
+  if (! (oid = lo_import (conn, path.c_str ())))
+    {
+      import_error = true;
+      msg = PQerrorMessage (conn);
+    }
+
+  // if we started the transaction, commit it even in case of import failure
+  bool commit_error = false;
+  if (make_tblock)
+    {
+      std::string cmd ("commit;");
+      Cell params;
+      Cell ptypes (1, 0);
+      Cell rtypes;
+      command c (oct_pq_conn, cmd, params, ptypes, rtypes, fname);
+
+      if (c.good ())
+        c.process_single_result ();
+
+      if (! c.good ())
+        commit_error = true;
+    }
+
+  if (import_error)
+    error ("%s: large object import failed: %s", fname.c_str (), msg.c_str ());
+
+  if (commit_error)
+    error ("%s: could not commit transaction", fname.c_str ());
+
+  if (error_state)
+    return retval;
+
+  retval = octave_value (octave_uint32 (oid));
+
+  return retval;
+}
+
+
+DEFUN_DLD (pq_lo_export, args, ,
+           "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} pq_lo_export (@var{connection}, @var{oid}, @var{path})\n\
+Exports the large object of Oid @var{oid} in the database associated with @var{connection} to the file @var{path} on the client side.\n\
+@end deftypefn")
+{
+  std::string fname ("pq_lo_export");
+
+  octave_value retval;
+
+  if (args.length () != 3 ||
+      args(0).type_id () != octave_pq_connection::static_type_id ())
+    {
+      print_usage ();
+
+      return retval;
+    }
+
+  std::string path (args(2).string_value ());
+
+  if (error_state)
+    {
+      error ("%s: third argument can not be converted to a string",
+             fname.c_str ());
+
+      return retval;
+    }
+
+  Oid oid = args(1).uint_value ();
+
+  if (error_state)
+    {
+      error ("%s: second argument can not be converted to an oid",
+             fname.c_str ());
+
+      return retval;
+    }
+
+  octave_base_value& rep = const_cast<octave_base_value&> (args(0).get_rep ());
+
+  octave_pq_connection &oct_pq_conn = dynamic_cast<octave_pq_connection&> (rep);
+
+  PGconn *conn = oct_pq_conn.octave_pq_get_conn ();
+
+  if (! conn)
+    {
+      error ("%s: connection not open", fname.c_str ());
+      return retval;
+    }
+
+  bool make_tblock = false;
+  switch (PQtransactionStatus (conn))
+    {
+    case PQTRANS_IDLE:
+      make_tblock = true;
+      break;
+    case PQTRANS_INTRANS:
+      break;
+    case PQTRANS_INERROR:
+      error ("%s: can't manipulate large objects within a failed transaction block",
+             fname.c_str ());
+      break;
+    case PQTRANS_UNKNOWN:
+      error ("%s: connection is bad", fname.c_str ());
+      break;
+    default: // includes PQTRANS_ACTIVE
+      error ("%s: unexpected connection state", fname.c_str ());
+    }
+
+  if (error_state)
+    return retval;
+
+  if (make_tblock)
+    {
+      std::string cmd ("begin;");
+      Cell params;
+      Cell ptypes (1, 0);
+      Cell rtypes;
+      command c (oct_pq_conn, cmd, params, ptypes, rtypes, fname);
+
+      if (c.good ())
+        c.process_single_result ();
+
+      if (! c.good ())
+        {
+          error ("%s: could not begin transaction", fname.c_str ());
+          return retval;
+        }
+    }
+
+  bool export_error = false;
+  std::string msg;
+
+  if (lo_export (conn, oid, path.c_str ()) == -1)
+    {
+      export_error = true;
+      msg = PQerrorMessage (conn);
+    }
+
+  // if we started the transaction, commit it even in case of export failure
+  bool commit_error = false;
+  if (make_tblock)
+    {
+      std::string cmd ("commit;");
+      Cell params;
+      Cell ptypes (1, 0);
+      Cell rtypes;
+      command c (oct_pq_conn, cmd, params, ptypes, rtypes, fname);
+
+      if (c.good ())
+        c.process_single_result ();
+
+      if (! c.good ())
+        commit_error = true;
+    }
+
+  if (export_error)
+    error ("%s: large object export failed: %s", fname.c_str (), msg.c_str ());
+
+  if (commit_error)
+    error ("%s: could not commit transaction", fname.c_str ());
+
+  return retval;
+}
+
+
+DEFUN_DLD (pq_lo_unlink, args, ,
+           "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} pq_lo_unlink (@var{connection}, @var{oid})\n\
+Removes the large object of Oid @var{oid} from the database associated with @var{connection}.\n\
+@end deftypefn")
+{
+  std::string fname ("pq_lo_unlink");
+
+  octave_value retval;
+
+  if (args.length () != 2 ||
+      args(0).type_id () != octave_pq_connection::static_type_id ())
+    {
+      print_usage ();
+
+      return retval;
+    }
+
+  Oid oid = args(1).uint_value ();
+
+  if (error_state)
+    {
+      error ("%s: second argument can not be converted to an oid",
+             fname.c_str ());
+
+      return retval;
+    }
+
+  octave_base_value& rep = const_cast<octave_base_value&> (args(0).get_rep ());
+
+  octave_pq_connection &oct_pq_conn = dynamic_cast<octave_pq_connection&> (rep);
+
+  PGconn *conn = oct_pq_conn.octave_pq_get_conn ();
+
+  if (! conn)
+    {
+      error ("%s: connection not open", fname.c_str ());
+      return retval;
+    }
+
+  bool make_tblock = false;
+  switch (PQtransactionStatus (conn))
+    {
+    case PQTRANS_IDLE:
+      make_tblock = true;
+      break;
+    case PQTRANS_INTRANS:
+      break;
+    case PQTRANS_INERROR:
+      error ("%s: can't manipulate large objects within a failed transaction block",
+             fname.c_str ());
+      break;
+    case PQTRANS_UNKNOWN:
+      error ("%s: connection is bad", fname.c_str ());
+      break;
+    default: // includes PQTRANS_ACTIVE
+      error ("%s: unexpected connection state", fname.c_str ());
+    }
+
+  if (error_state)
+    return retval;
+
+  if (make_tblock)
+    {
+      std::string cmd ("begin;");
+      Cell params;
+      Cell ptypes (1, 0);
+      Cell rtypes;
+      command c (oct_pq_conn, cmd, params, ptypes, rtypes, fname);
+
+      if (c.good ())
+        c.process_single_result ();
+
+      if (! c.good ())
+        {
+          error ("%s: could not begin transaction", fname.c_str ());
+          return retval;
+        }
+    }
+
+  bool unlink_error = false;
+  std::string msg;
+
+  if (lo_unlink (conn, oid) == -1)
+    {
+      unlink_error = true;
+      msg = PQerrorMessage (conn);
+    }
+
+  // if we started the transaction, commit it even in case of unlink failure
+  bool commit_error = false;
+  if (make_tblock)
+    {
+      std::string cmd ("commit;");
+      Cell params;
+      Cell ptypes (1, 0);
+      Cell rtypes;
+      command c (oct_pq_conn, cmd, params, ptypes, rtypes, fname);
+
+      if (c.good ())
+        c.process_single_result ();
+
+      if (! c.good ())
+        commit_error = true;
+    }
+
+  if (unlink_error)
+    error ("%s: large object unlink failed: %s", fname.c_str (), msg.c_str ());
+
+  if (commit_error)
+    error ("%s: could not commit transaction", fname.c_str ());
+
+  return retval;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main/database/src/pq_update_types.cc	Wed Jan 16 06:17:06 2013 +0000
@@ -0,0 +1,52 @@
+/*
+
+Copyright (C) 2013 Olaf Till <i7tiol@t-online.de>
+
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 3 of the License, or
+(at your option) any later version.
+
+This program 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 General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; If not, see <http://www.gnu.org/licenses/>.
+
+*/
+
+#include <octave/oct.h>
+
+#include "command.h"
+
+// PKG_ADD: autoload ("pq_update_types", "pq_interface.oct");
+
+DEFUN_DLD (pq_update_types, args, ,
+           "-*- texinfo -*-\n\
+@deftypefn {Loadable Function} pq_update_types (@var{connection})\n\
+Updates information on existing postgresql types for @var{connection}. Use this before @code{pq_exec_params} if types were created or dropped while the connection was already established. A newly created connection will automatically retrieve this information at connection time.\n\
+\n\
+@end deftypefn")
+{
+  std::string fname ("pq_update_types");
+
+  octave_value_list retval;
+
+  if (args.length () != 1 ||
+      args(0).type_id () != octave_pq_connection::static_type_id ())
+    {
+      print_usage ();
+
+      return retval;
+    }
+
+  octave_base_value& rep = const_cast<octave_base_value&> (args(0).get_rep ());
+
+  octave_pq_connection &oct_pq_conn = dynamic_cast<octave_pq_connection&> (rep);
+
+  oct_pq_conn.octave_pq_refresh_types ();
+
+  return retval;
+}