Giter Site home page Giter Site logo

jtv / libpqxx Goto Github PK

View Code? Open in Web Editor NEW
941.0 46.0 226.0 10.12 MB

The official C++ client API for PostgreSQL.

Home Page: http://pqxx.org/

License: BSD 3-Clause "New" or "Revised" License

Makefile 11.28% Shell 22.56% M4 0.83% C++ 62.23% Python 2.28% CMake 0.78% Ruby 0.05%
postgresql postgres cplusplus cplusplus-17 databases

libpqxx's Introduction

libpqxx

Welcome to libpqxx, the C++ API to the PostgreSQL database management system.

Home page: http://pqxx.org/development/libpqxx

Find libpqxx on Github: https://github.com/jtv/libpqxx

Documentation on Read The Docs: https://libpqxx.readthedocs.io

Compiling this package requires PostgreSQL to be installed -- or at least the C headers and library for client development. The library builds on top of PostgreSQL's standard C API, libpq, though your code won't notice.

If you're getting the code straight from the Git repo, the head of the master branch represents the current development version. Releases are tags on commits in master. For example, to get version 7.1.1:

    git checkout 7.1.1

Upgrade notes

The 7.x versions require at least C++17. Make sure your compiler is up to date. For libpqxx 8.x you will need at least C++20.

Also, 7.0 makes some breaking changes in rarely used APIs:

  • There is just a single connection class. It connects immediately.
  • Custom connection classes are no longer supported.
  • It's no longer possible to reactivate a connection once it's been closed.
  • The API for defining string conversions has changed.

If you're defining your own type conversions, 7.1 requires one additional field in your nullness traits.

Building libpqxx

There are two different ways of building libpqxx from the command line:

  1. Using CMake, on any system which supports it.
  2. On Unix-like systems, using a configure script.

"Unix-like" systems include GNU/Linux, Apple macOS and the BSD family, AIX, HP-UX, Irix, Solaris, etc. Even on Microsoft Windows, a Unix-like environment such as WSL, Cygwin, or MinGW should work.

You'll find detailed build and install instructions in BUILDING-configure.md and BUILDING-cmake.md, respectively.

And if you're working with Microsoft Visual Studio, have a look at Gordon Elliott's Easy-PQXX Build for Windows Visual Studio project.

Documentation

Building the library, if you have the right tools installed, generates HTML documentation in the doc/ directory. It is based on the headers in include/pqxx/ and text in include/pqxx/doc/. This documentation is also available online at readthedocs.

Programming with libpqxx

Your first program will involve the libpqxx classes connection (see the pqxx/connection.hxx header), and work (a convenience alias for transaction<> which conforms to the interface defined in pqxx/transaction_base.hxx).

These *.hxx headers are not the ones you include in your program. Instead, include the versions without filename suffix (e.g. pqxx/connection). Those will include the actual .hxx files for you. This was done so that includes are in standard C++ style (as in <iostream> etc.), but an editor will still recognize them as files containing C++ code.

Continuing the list of classes, you may also need the result class (pqxx/result.hxx). In a nutshell, you create a pqxx::connection based on a Postgres connection string (see below), create a pqxx::work (a transaction object) in the context of that connection, and run one or more queries and/or SQL commands on that.

Depending on how you execute a query, it can return a stream of std::tuple (each representing one row); or a pqxx::result object which holds both the result data and additional metadata: how many rows your query returned and/or modified, what the column names are, and so on. A pqxx::result is a container of pqxx::row, and a pqxx::row is a container of pqxx::field.

Here's an example with all the basics to get you going:

    #include <iostream>
    #include <pqxx/pqxx>

    int main()
    {
        try
        {
            // Connect to the database.  You can have multiple connections open
            // at the same time, even to the same database.
            pqxx::connection c;
            std::cout << "Connected to " << c.dbname() << '\n';

            // Start a transaction.  A connection can only have one transaction
            // open at the same time, but after you finish a transaction, you
            // can start a new one on the same connection.
            pqxx::work tx{c};

            // Query data of two columns, converting them to std::string and
            // int respectively.  Iterate the rows.
            for (auto [name, salary] : tx.query<std::string, int>(
                "SELECT name, salary FROM employee ORDER BY name"))
            {
                std::cout << name << " earns " << salary << ".\n";
            }

            // For large amounts of data, "streaming" the results is more
            // efficient.  It does not work for all types of queries though.
            //
            // You can read fields as std::string_view here, which is not
            // something you can do in most places.  A string_view becomes
            // meaningless when the underlying string ceases to exist.  In this
            // one situation, you can convert a field to string_view and it
            // will be valid for just that one iteration of the loop.  The next
            // iteration may overwrite or deallocate its buffer space.
            for (auto [name, salary] : tx.stream<std::string_view, int>(
                "SELECT name, salary FROM employee"))
            {
                std::cout << name << " earns " << salary << ".\n";
            }

            // Execute a statement, and check that it returns 0 rows of data.
            // This will throw pqxx::unexpected_rows if the query returns rows.
            std::cout << "Doubling all employees' salaries...\n";
            tx.exec0("UPDATE employee SET salary = salary*2");

            // Shorthand: conveniently query a single value from the database.
            int my_salary = tx.query_value<int>(
                "SELECT salary FROM employee WHERE name = 'Me'");
            std::cout << "I now earn " << my_salary << ".\n";

            // Or, query one whole row.  This function will throw an exception
            // unless the result contains exactly 1 row.
            auto [top_name, top_salary] = tx.query1<std::string, int>(
                R"(
                    SELECT name, salary
                    FROM employee
                    WHERE salary = max(salary)
                    LIMIT 1
                )");
            std::cout << "Top earner is " << top_name << " with a salary of "
                      << top_salary << ".\n";

            // If you need to access the result metadata, not just the actual
            // field values, use the "exec" functions.  Most of them return
            // pqxx::result objects.
            pqxx::result res = tx.exec("SELECT * FROM employee");
            std::cout << "Columns:\n";
            for (pqxx::row_size_type col = 0; col < res.columns(); ++col)
                std::cout << res.column_name(col) << '\n';

            // Commit the transaction.  If you don't do this, the database will
            // undo any changes you made in the transaction.
            std::cout << "Making changes definite: ";
            tx.commit();
            std::cout << "OK.\n";
        }
        catch (std::exception const &e)
        {
            std::cerr << "ERROR: " << e.what() << '\n';
            return 1;
        }
        return 0;
    }

Connection strings

Postgres connection strings state which database server you wish to connect to, under which username, using which password, and so on. Their format is defined in the documentation for libpq, the C client interface for PostgreSQL. Alternatively, these values may be defined by setting certain environment variables as documented in e.g. the manual for psql, the command line interface to PostgreSQL. Again the definitions are the same for libpqxx-based programs.

The connection strings and variables are not fully and definitively documented here; this document will tell you just enough to get going. Check the PostgreSQL documentation for authoritative information.

The connection string consists of attribute=value pairs separated by spaces, e.g. "user=john password=1x2y3z4". The valid attributes include:

  • host — Name of server to connect to, or the full file path (beginning with a slash) to a Unix-domain socket on the local machine. Defaults to "/tmp". Equivalent to (but overrides) environment variable PGHOST.
  • hostaddr — IP address of a server to connect to; mutually exclusive with "host".
  • port — Port number at the server host to connect to, or socket file name extension for Unix-domain connections. Equivalent to (but overrides) environment variable PGPORT.
  • dbname — Name of the database to connect to. A single server may host multiple databases. Defaults to the same name as the current user's name. Equivalent to (but overrides) environment variable PGDATABASE.
  • user — User name to connect under. This defaults to the name of the current user, although PostgreSQL users are not necessarily the same thing as system users.
  • requiressl — If set to 1, demands an encrypted SSL connection (and fails if no SSL connection can be created).

Settings in the connection strings override the environment variables, which in turn override the default, on a variable-by-variable basis. You only need to define those variables that require non-default values.

Linking with libpqxx

To link your final program, make sure you link to both the C-level libpq library and the actual C++ library, libpqxx. With most Unix-style compilers, you'd do this using these options: -lpqxx -lpq

while linking. Both libraries must be in your link path, so the linker knows where to find them. Any dynamic libraries you use must also be in a place where the loader can find them when loading your program at runtime.

Some users have reported problems using the above syntax, however, particularly when multiple versions of libpqxx are partially or incorrectly installed on the system. If you get massive link errors, try removing the "-lpqxx" argument from the command line and replacing it with the name of the libpqxx library binary instead. That's typically libpqxx.a, but you'll have to add the path to its location as well, e.g. /usr/local/pqxx/lib/libpqxx.a. This will ensure that the linker will use that exact version of the library rather than one found elsewhere on the system, and eliminate worries about the exact right version of the library being installed with your program..

libpqxx's People

Contributors

an-tao avatar ash-j-f avatar baldvin-kovacs avatar daniel347x avatar dvereb avatar eelis avatar elelel avatar georgthegreat avatar gzliudan avatar isnullxbh avatar jadematrix avatar jmoellers avatar jtv avatar kayess avatar keithstellyes avatar mkrupcale avatar rameshrr avatar rdassen avatar rocksolidwebdesign avatar sergey-kurenkov avatar sil3ntstorm avatar skasperski avatar tambry avatar teamplatform1 avatar timsc avatar tomlankhorst avatar tt4g avatar vestnik avatar webmaster128 avatar yayj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

libpqxx's Issues

Where are the tags

There are apparently no tags associated with this github repository. How do I find the source code for a tagged release? As near as I can tell, commit commit 23376d4 corresponds to 5.0.0.

[Wiki] Wrong example about working with exceptions

http://pqxx.org/development/libpqxx/wiki/WikiStart#Handlingerrors

#include <iostream>
#include <pqxx/except>
#include "my-db-code.hxx"

int main(int argc, char *argv[])
{
  try
  {
    do_db_work(trans);
  }
  catch (const std::exception &e)
  {
    std::cerr << e.what() << std::endl;
    return 1;
  }
  catch (const pqxx::sql_error &e)
  {
    std::cerr
        << "Database error: " << e.what() << std::endl
        << "Query was: " << e.query() << std::endl;
    return 2;
  }
}

The second catch of pqxx::sql_error will never execute https://ideone.com/Nsf3SM
It must be moved before std::exception catch https://ideone.com/JCUWu8

[Docs] Wrong usage of quote() ?

http://pqxx.org/development/libpqxx/wiki/EmployeeExample

void add_employee(pqxx::transaction_base &txn, std::string name, int department)
{
  // Use quote() to escape and quote a value safely for use in a
  // query.  Avoid bugs and security holes when strings contain
  // backslashes, quotes, or other "weird" characters.
  // That's not very useful for department (an integer), but it
  // also represents the value as a string.  We don't want to add
  // an int to the query, we want to add a string that represents
  // the int value.
  txn.exec(
    "INSERT INTO Employee(name, department) "
    "VALUES (" +
    txn.quote(name) + ", " +
    txn.quote(department) +
    ")");
}

quote() calls quote_raw() -> esc_raw() -> PQescapeByteaConn() which does:

Escapes binary data for use within an SQL command with the type bytea.

esc() calls PQescapeStringConn()

I think the above code should be fixed to:

txn.exec(
    "INSERT INTO Employee(name, department) "
    "VALUES (" +
    "'" + txn.esc(name) + "', " +
    "'" + txn.esc(std::to_string(department)) + "'" +
    ")");

From the docs I got confused about when to use quote() and when esc() that's why I started investigating the library code. I am still confused because I can't make these two functions return different results to understand the difference (I tried all kinds of characters including unicode).

#include <iostream>
#include <pqxx/pqxx>

int main() {
    pqxx::connection c{"postgresql://..."};
    pqxx::work tx{c};

    std::string text{"Hi ' %"};
    std::cout
        << ' ' << tx.esc(text) << std::endl
        << tx.quote(text) << std::endl;

    return 0;
}

Output

 Hi '' %
'Hi '' %'

Link error on Fedora

Here's the section from config.log when trying to build 5.0.1:

configure:17181: checking for PQexec in -lpq
configure:17206: gcc -o conftest -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic  -Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -L/usr/lib64 conftest.c -lpq -L/usr/lib64 -lpq  >&5
configure:17206: $? = 0
configure:17215: result: yes
configure:17253: checking for correct C++ linkage of basic libpq functions
configure:17296: g++ -o conftest -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic -Wno-long-long -fvisibility=hidden -fvisibility-inlines-hidden  -Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -L/usr/lib64 conftest.cpp  >&5
/tmp/cc1PyrL4.o: In function `main':
/builddir/build/BUILD/libpqxx-5.0.1/conftest.cpp:43: undefined reference to `PQexec'
collect2: error: ld returned 1 exit status

Link to bugzilla

please tell me how to use it in Xcode

i can't install it in my mac computer

liyudeMBP:Desktop liyu$ g++ link.cpp -lpqxx -lpq
liyudeMBP:Desktop liyu$ g++ link.cpp -lpqxx -lpq
liyudeMBP:Desktop liyu$ g++ link.cpp -lpq
Undefined symbols for architecture x86_64:
"pqxx::connection_base::disconnect()", referenced from:
_main in link-f6a0e9.o
"pqxx::connection_base::init()", referenced from:
pqxx::basic_connectionpqxx::connect_direct::basic_connection(char const*) in link-f6a0e9.o
"pqxx::connection_base::close()", referenced from:
pqxx::basic_connectionpqxx::connect_direct::~basic_connection() in link-f6a0e9.o
"pqxx::connection_base::dbname()", referenced from:
_main in link-f6a0e9.o
"pqxx::connection_base::connection_base(pqxx::connectionpolicy&)", referenced from:
pqxx::basic_connectionpqxx::connect_direct::basic_connection(char const*) in link-f6a0e9.o
"pqxx::connectionpolicy::connectionpolicy(std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator > const&)", referenced from:
pqxx::connect_direct::connect_direct(std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator > const&) in link-f6a0e9.o
"pqxx::connectionpolicy::~connectionpolicy()", referenced from:
pqxx::connect_direct::~connect_direct() in link-f6a0e9.o
"pqxx::connection_base::is_open() const", referenced from:
_main in link-f6a0e9.o
"vtable for pqxx::connect_direct", referenced from:
pqxx::connect_direct::connect_direct(std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator > const&) in link-f6a0e9.o
NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
liyudeMBP:Desktop liyu$ g++ link.cpp -lpq -lpqxx

it always have some erro please help me !
thanks

Documentation doesn't seem to describe usage of pqxx::connection constructor

The tutorial says it's passed a string for options but doesn't really help anymore than that. I was confused on documentation for it (I was not familiar with the C binding)

A quick StackOverflow search lead me here: https://stackoverflow.com/questions/11202996/strange-behavior-for-libpq-with-pqconnectdb which says it's just using PQconnectStart, my look-over the source code seems to confirm this.

Perhaps documentation should at the very least reference this libpqc doc? https://www.postgresql.org/docs/9.0/static/libpq-connect.html I certainly would've saved time. I'd be willing to give a PR to fix this.

Link errors after upgrading to version 6

Homebrew just upgraded libpqxx to version 6, which immediately seems to have broken my code. It now fails to link:

Undefined symbols for architecture x86_64:
  "pqxx::row::row(pqxx::result, unsigned long)", referenced from:
      pqxx::const_result_iterator::const_result_iterator(pqxx::result const*, unsigned long) in loader.cc.o
  "pqxx::internal::clear_result(pg_result const*)", referenced from:
      pqxx::result::make_data_pointer(pg_result const*) in loader.cc.o
  "pqxx::internal::basic_transaction::do_commit()", referenced from:
      vtable for pqxx::transaction<(pqxx::isolation_level)0, (pqxx::readwrite_policy)0> in loader.cc.o
      construction vtable for pqxx::internal::basic_transaction-in-pqxx::transaction<(pqxx::isolation_level)0, (pqxx::readwrite_policy)0> in loader.cc.o
  "pqxx::internal::basic_transaction::basic_transaction(pqxx::connection_base&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, pqxx::readwrite_policy)", referenced from:
      pqxx::transaction<(pqxx::isolation_level)0, (pqxx::readwrite_policy)0>::transaction(pqxx::connection_base&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&) in loader.cc.o
  "typeinfo for pqxx::internal::basic_transaction", referenced from:
      construction vtable for pqxx::internal::basic_transaction-in-pqxx::transaction<(pqxx::isolation_level)0, (pqxx::readwrite_policy)0> in loader.cc.o
      typeinfo for pqxx::transaction<(pqxx::isolation_level)0, (pqxx::readwrite_policy)0> in loader.cc.o
  "VTT for pqxx::internal::basic_transaction", referenced from:
      pqxx::internal::basic_transaction::~basic_transaction() in loader.cc.o

I noticed that pqxx::row::row is listed as deprecated, but as far as I can see my code does not try to use it. My usage pattern looks like this:

pqxx::result result;
result=transaction.exec(…..);
for (const auto &row: result) {
    ProcessRow(row, some_object);
}

Where ProcessRow takes an const pqxx::row &row parameter, so no copying should ever happen.

I have no idea what is up with the transaction link errors.

pqxx.org is down

pqxx.org is down, at least for the last few days. Is that administered by anyone here?

Version bump request

I'm updating code that uses libpqxx but linking fails due to errors stating "undefined reference to `pqxx::internal::clear_result(pg_result const*)'".

The fix appears to have been addressed in response to issue #22. However, the change in git has not propagated out to the linux distributions. As linking inconsistency is a work stoppage problem for me (libpqxx is installed via package management software), would it be possible to tag either current HEAD or, at the least, commit 71ebccd with an incremented version number. The newer version numbering should get package maintainers attention.

libpq ver 9.6.5 build date 2017Sep06
libpqxx ver 5.1.0 build date 2017Aug03

configure error 'The Oid typedef in libpq has changed'

building on Ubuntu 16.04 64-bit using libpqxx github master as of

fb1cca3

I receive the following ./configure error

checking that type of libpq's Oid is as expected... configure: error: 
The Oid typedef in libpq has changed.  Please notify the libpqxx authors of the
change!

however ./configure && make && make install and linking my app works fine on my Ubuntu 16.04 system when I use svn trunk revision 1945

svn co svn://pqxx.org/libpqxx/trunk/

I have installed all the needed postgres dev libs as far as I know, I have installed:

sudo apt-get install postgresql-9.5 postgresql-server-dev-9.5 libpq5 libpq-dev

I checked libpq-fe.h from my /usr/include and saw that Oid is defined as unsigned int, which is the same as libpqxx defines it to be, so I don't know what's wrong.

I see in git log a commit as follows

commit 0bd0167304e3d970aa4ee50c5c95275baf96f3cc
Author: Jeroen Vermeulen <[email protected]>
...skipping...
    Fixed spurious "Oid type has changed!" error in configure, thanks Kathy

but I don't see the message about fixing the spurious ID when I search actual github commits

on github, the commit message for 0bd0167 is "Use constexpr and noexcept."

I also notice that the git log message says ...skipping...

the autoconf code for this check in the ./configure script from svn vs github look nearly identical except some minor indentation and whitespace differences

I don't have libpqxx already installed anywhere on my system

was this spurious Oid error something that was fixed at some point? is it a regression? did the commit get skipped for some reason when moving from svn?

the most curious thing to me is why svn trunk does not have this error when the check code is the same

thanks!

Missing header after installation

After general installation procedure with ./configure && make && make install, the compilation fails with the following error:

In file included from /usr/local/include/pqxx/field:19:0,
                 from /usr/local/include/pqxx/result.hxx:31,
                 from /usr/local/include/pqxx/result:19,
                 from /usr/local/include/pqxx/binarystring.hxx:26,
                 from /usr/local/include/pqxx/binarystring:18,
                 from /usr/local/include/pqxx/pqxx:17,
                 from /ametsuchi/server/wsv/wsv_postgres.cc:19:
/usr/local/include/pqxx/field.hxx:34:22: fatal error: pqxx/types: No such file or directory

Path issue (building libpqxx)

Building libpqxx on Windows 10 with x64 Native Tool Command Prompt for VS 2017, Community Edition.
Using PostgreSQL 9.5 installed with one-click installer

As instruction in file win32\common to set
PGSQLSRC="C:\Program Files\PostgreSQL\9.5"
Will produce error during copy file:

Copying libpq.dll to lib.

IMPORTANT: you MUST copy this libpq.dll into the directory
where your program's .EXE resides. The system libpq.dll is
not necessarily compatible with the libpq include files that
you built libpqxx with. Do NOT copy this file into your
Windows system32 directory, that may break other programs.
Instead, keep it with your program and distribute it along
with the program.

    copy ""C:\Program Files\PostgreSQL\9.5"\lib\libpq.dll" "lib"

The system cannot find the file specified.
NMAKE : fatal error U1077: 'copy' : return code '0x1'
Stop.

I can fix the error by editing the win32\common:

PGSQLSRC=C:\PROGRA1\POSTGR1\9.5

Note the path without quotes and it use short name.
This is a minor issue, but it waste time for new user like me trying to compile the library.
Hope you could mention this in the win32\common-sample.

deleting a connection trough a pointer to pqxx::connection_base leaks connection

See #57

Most of methods take a pqxx:connection_base for reference so it seems valid to have pointers to pqxx::connection_base around, but deleting a connection trough a pqxx::connection_base pointer leaks the connection. I'd say fine that pqxx::connection_base doesn't have a virtual table but then in his destructor we need to call the close(). My suggestion is to move the close from ~basic_connection to ~connection_base

build fails on VS2015

as of 3f38637 on Windows 8.1 Pro 64-bit with Visual Studio 2015

I wonder if this is related https://stackoverflow.com/questions/23374003/symbol-cannot-be-used-in-a-using-declaration

build works correctly on svn trunk rev 1945

here is my terminal output:

C:\src>git clone https://github.com/jtv/libpqxx
C:\src>cd libpqxx
C:\src\libpqxx>nmake /f win32\vc-libpqxx.mak ALL

Microsoft (R) Program Maintenance Utility Version 14.00.24210.0
Copyright (C) Microsoft Corporation.  All rights reserved.

        cl.exe /nologo /W3 /EHsc /FD /GR /c  /I "include" /I C:\PROGRA~1\POSTGR~1\9.5\include /I C:\PROGRA~1\POSTGR~1\9.5\include  /D "WIN32" /D "_MBCS" /D "_WINDOWS" /D "PQXX_INTERNAL" /MDd /Gm /ZI /Od /D "_LIB" /D "_DEBUG" /RTC1 /Fo"ObjStaticDebug\\" /Fd"ObjStaticDebug\\" src/binarystring.cxx binarystring.cxx
c:\src\libpqxx\include\pqxx\result.hxx(222): warning C4800: 'const pqxx::internal::pq::PGresult *': forcing value to bool 'true' or 'false' (performance warning)
c:\src\libpqxx\include\pqxx\row.hxx(292): error C2886: 'field': symbol cannot be used in a member using-declaration
c:\src\libpqxx\include\pqxx\row.hxx(209): note: see declaration of 'field'
c:\src\libpqxx\include\pqxx\row.hxx(293): error C2886: 'field': symbol cannot be used in a member using-declaration
c:\src\libpqxx\include\pqxx\row.hxx(209): note: see declaration of 'field'
c:\src\libpqxx\include\pqxx\result_iterator.hxx(134): error C2886: 'row': symbol cannot be used in a member using-declaration
c:\src\libpqxx\include\pqxx\result_iterator.hxx(42): note: see declaration of 'row'
c:\src\libpqxx\include\pqxx\result_iterator.hxx(135): error C2886: 'row': symbol cannot be used in a member using-declaration
c:\src\libpqxx\include\pqxx\result_iterator.hxx(42): note: see declaration of 'row'
c:\src\libpqxx\src\binarystring.cxx(57): error C2653: 'internal': is not a class or namespace name
c:\src\libpqxx\src\binarystring.cxx(57): error C2062: type 'unsigned char' unexpected
c:\src\libpqxx\src\binarystring.cxx(58): error C2065: 'A': undeclared identifier
c:\src\libpqxx\src\binarystring.cxx(58): error C2228: left of '.get' must have class/struct/union
c:\src\libpqxx\src\binarystring.cxx(58): note: type is 'unknown-type'
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64\cl.exe"' : return code '0x2'
Stop.

MSDN:
Compiler Error C2228
Compiler Error C2886

Need of better guide how to build

Hi, it is constant fail to build and run tests due to need of better guide.
I fail to make it work with cmake. commands like
include_directories(/usr/local/include/) target_link_libraries(${PROJECT_NAME} PUBLIC /usr/local/lib/libpqxx.a)
does not link the lib because of failed make install.
Please provide guides

MinGW + MSYS Build Issue

Sorry if this isn't the right place for this, but my build is failing during the make on Windows in the MinGW and MSYS environment.

$ make
Making all in include
make[1]: Entering directory `/home/Sam/libpqxx-6.0.0/include'
Making all in pqxx
make[2]: Entering directory `/home/Sam/libpqxx-6.0.0/include/pqxx'
make  all-am
make[3]: Entering directory `/home/Sam/libpqxx-6.0.0/include/pqxx'
make[3]: Leaving directory `/home/Sam/libpqxx-6.0.0/include/pqxx'
make[2]: Leaving directory `/home/Sam/libpqxx-6.0.0/include/pqxx'
make[2]: Entering directory `/home/Sam/libpqxx-6.0.0/include'
make[2]: Nothing to be done for `all-am'.
make[2]: Leaving directory `/home/Sam/libpqxx-6.0.0/include'
make[1]: Leaving directory `/home/Sam/libpqxx-6.0.0/include'
Making all in src
make[1]: Entering directory `/home/Sam/libpqxx-6.0.0/src'
/bin/sh ../libtool  --tag=CXX   --mode=compile g++ -DHAVE_CONFIG_H   -I../include -I../include -Ic:/PROGRA~2/PostgreSQL/9.6/include   -g -O2 -fvisibility=hidden -fvisibility-inlines-hidden -MT connection_base.lo -MD -MP -MF .deps/connection_base.Tpo -c -o connection_base.lo connection_base.cxx
libtool: compile:  g++ -DHAVE_CONFIG_H -I../include -I../include "-Ic:/PROGRA~2/PostgreSQL/9.6/include" -g -O2 -fvisibility=hidden -fvisibility-inlines-hidden -MT connection_base.lo -MD -MP -MF .deps/connection_base.Tpo -c connection_base.cxx -o connection_base.o
connection_base.cxx:26:21: fatal error: mstcpip.h: No such file or directory
 #include <mstcpip.h>
                     ^

Obviously the mstcpip header is missing, but I don't see this header in a clean MinGW installation. I see it in my MinGW-w64 installation and in Windows itself (Windows Kits). Is there a work around for this?

Please tag releases

Hi Jeroen

I'm a Debian maintainer for this lib and long time (2-3y) ago we exchanged some emails related to 5.0.
I see it' been released yey ;-)
Thx a lot for your continuous work on libpqxx.

Also I'd like to ask you to tag 5.0.1 as a release please. It'd make much easier to link it with all the tool chain we're using for building, testing etc.. Actually I think that all libpqxx users will benefit from it been tagged and maybe even signed ;-P

Unfortunately 5 won't make into Stretch but I'll try to upload it to experimental as soon as I can.

Anyway once more thx a lot for your great work.

Linker error - Need Help setting up pqxx with CMakeLists

I wanted to move onto the next phase of my project and installed PostgresSQL and libpqxx both with Homebrew.
OS: OS X 10.12.5
IDE: CLion

Beforehand, my CMakeLists.txt linked and compiled all libraries and include directories as it should without problems. Now I included pqxx correctly in my CMakeList but the linking seems to miss something. Creating a pqxx::Connection C() generates this linker error::

[100%] Linking CXX executable cpp-service
Undefined symbols for architecture x86_64:
  "_ASN1_STRING_data", referenced from:
      _verify_peer_name_matches_certificate_name in libpq.a(fe-secure-openssl.o)
  "_ASN1_STRING_length", referenced from:
      _verify_peer_name_matches_certificate_name in libpq.a(fe-secure-openssl.o)
  "_BIO_clear_flags", referenced from:
      _my_sock_read in libpq.a(fe-secure-openssl.o)
      _my_sock_write in libpq.a(fe-secure-openssl.o)
  "_BIO_int_ctrl", referenced from:
      _pgtls_open_client in libpq.a(fe-secure-openssl.o)
  "_BIO_new", referenced from:
      _pgtls_open_client in libpq.a(fe-secure-openssl.o)
  "_BIO_s_socket", referenced from:
      _pgtls_open_client in libpq.a(fe-secure-openssl.o)
  "_BIO_set_flags", referenced from:
      _my_sock_read in libpq.a(fe-secure-openssl.o)
      _my_sock_write in libpq.a(fe-secure-openssl.o)
  "_CRYPTO_get_id_callback", referenced from:
      _pgtls_close in libpq.a(fe-secure-openssl.o)
      _pgtls_init in libpq.a(fe-secure-openssl.o)

[...]

ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [cpp-service] Error 1
make[2]: *** [CMakeFiles/cpp-service.dir/all] Error 2
make[1]: *** [CMakeFiles/cpp-service.dir/rule] Error 2
make: *** [cpp-service] Error 2

my CMakeLists.txt files looks as followed:

cmake_minimum_required(VERSION 3.7)
project(cpp-service)

#Set Version
set (cpp-service_VERSION_MAJOR 1)
set (cpp-service_VERSION_MAJOR 0)

set(CMAKE_CXX_STANDARD 11)
find_package(Boost COMPONENTS date_time REQUIRED)
if(Boost_FOUND)
	
	include_directories(${Boost_INCLUDE_DIRS})
else()
	message(FATAL ERROR :"Boost was not found ")
endif()
#Setup Asio
find_file(asio_INCLUDE asio.hpp HINTS "/usr/local/restbed/dependency/asio/asio/include/" )


if ( asio_INCLUDE )
	set( ASIO_FOUND TRUE )
	set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DASIO_STANDALONE=YES" )

	message( STATUS "${Green}Found ASIO include at: ${asio_INCLUDE}${Reset}" )
else ( )
	message( FATAL_ERROR "${Red}Failed to locate ASIO dependency.${Reset}" )
endif ( )

#libpqxx
set(libpqxx_SOURCE "/usr/local/opt/libpqxx" )

if ( libpqxx_SOURCE )
	set( libpqxx_FOUND TRUE )
	set( libpqxx_INCLUDE "${libpqxx_SOURCE}/include" )
	set( libpqxx_LIBRARY "${libpqxx_SOURCE}/lib" )

	message( STATUS "${Green}Found libpqxx include at: ${libpqxx_LIBRARY}${Reset}" )
else ( )
	message( FATAL_ERROR "${Red}Failed to locate libpqxx dependency.${Reset}" )
endif ( )


#postgres
set(postgres_SOURCE "/usr/local/opt/postgres" )

if ( postgres_SOURCE )
	set( postgres_FOUND TRUE )
	set( postgres_INCLUDE "${postgres_SOURCE}/include" )
	set( postgres_LIBRARY "${postgres_SOURCE}/lib" )

	message( STATUS "${Green}Found Postgres include at: ${postgres_LIBRARY}${Reset}" )
else ( )
	message( FATAL_ERROR "${Red}Failed to locate Postgres dependency.${Reset}" )
endif ( )
# RestBED
set(restbed_SOURCE "/usr/local/restbed" )

if ( restbed_SOURCE )
	set( restbed_FOUND TRUE )

	set( restbed_BUILD "${PROJECT_SOURCE_DIR}/restbed_build" )

	set( restbed_DISTRIBUTION "${restbed_SOURCE}/distribution" )
	set( restbed_INCLUDE "${restbed_DISTRIBUTION}/include" )
	set( restbed_LIBRARY "${restbed_DISTRIBUTION}/library" )

	message( STATUS "${Green}Found Restbed include at: ${restbed_INCLUDE}${Reset}" )
else ( )
	message( FATAL_ERROR "${Red}Failed to locate Restbed dependency.${Reset}" )
endif ( )

find_library( ssl_LIBRARY ssl ssleay32 HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )
find_library( crypto_LIBRARY crypto libeay32 HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/out32dll" "${PROJECT_SOURCE_DIR}/dependency/openssl" "/usr/local/opt/openssl/lib" "/usr/lib" "/usr/local/lib" "/opt/local/lib" )
find_path( ssl_INCLUDE openssl/ssl.h HINTS "${PROJECT_SOURCE_DIR}/dependency/openssl/inc32" "${PROJECT_SOURCE_DIR}/dependency/openssl/include" "/usr/local/opt/openssl/include" "/usr/include" "/usr/local/include" "/opt/local/include" )

if ( ssl_INCLUDE AND ssl_LIBRARY AND crypto_LIBRARY )
	set( OPENSSL_FOUND TRUE )
	add_definitions( -DBUILD_SSL=TRUE )

	if ( APPLE AND BUILD_SSL )
		set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations" )
	endif( )

	message( STATUS "${Green}Found OpenSSL library at: ${ssl_LIBRARY}${Reset}" )
	message( STATUS "${Green}Found OpenSSL include at: ${ssl_INCLUDE}${Reset}" )
	message( STATUS "${Green}Found Crypto library at: ${crypto_LIBRARY}${Reset}" )
else ( )
	message( FATAL_ERROR "${Red}Failed to locate OpenSSL dependency. see restbed/dependency/openssl; ./config shared; make all${Reset}" )
endif ( )

# find all files from restbed library
# NEED TO CHECK WHETHER .dylib or .a exists
file(GLOB_RECURSE restbed_LIBRARY_FILES
		"${restbed_LIBRARY}/*.a")
#Find all files from Boost Library
file(GLOB_RECURSE Boost_LIBRARY_FILES
		"${Boost_LIBRARIES}/*.a"
		"${Boost_LIBRARIES}/*.dylib")
#libpqxx
file(GLOB_RECURSE libpqxx_LIBRARY_FILES
		"${libpqxx_LIBRARY}/*.a"
		"${libpqxx_LIBRARY}/*.dylib"
		"${libpqxx_LIBRARY}/pk_config/*.pc")
#postgres
file(GLOB_RECURSE postgres_LIBRARY_FILES
		"${postgres_LIBRARY}/*.a"
		"${postgres_LIBRARY}/*.dylib")

#OpenSSL LIB
file(GLOB_RECURSE OPENSLL_LIBRARY_FILES
		"${ssl_LIBRARY}/*.a"
		"${ssl_LIBRARY}/*.dylib"
		"${crypto_LIBRARY}/*.dylib"
		"${crypto_LIBRARY}/*.a")
#Get all our files
file(GLOB SOURCE
		"*.h"
		"*.cpp"
		)
include_directories(${restbed_INCLUDE})
include_directories(${libpqxx_INCLUDE})
include_directories(${ssl_INCLUDE})


add_executable(cpp-service ${SOURCE})
target_link_libraries(cpp-service ${restbed_LIBRARY_FILES})
target_link_libraries(cpp-service ${Boost_LIBRARY})
target_link_libraries(cpp-service ${Boost_DATE_TIME_LIBRARY})
target_link_libraries(cpp-service ${libpqxx_LIBRARY_FILES})
target_link_libraries(cpp-service ${postgres_LIBRARY_FILES})
target_link_libraries(cpp-service ${OPENSSL_LIBRARY_FILES})

Do you think you could provide a CMakeList file for linking pqxx correctly?

How does result fetching internally work?

Consider that I need multiple passes over my resultset. What happens in libpqxx? Is the result buffered buffered clientside once or is it fetched from the server when iterated over?

pqxx::connection C(connection_string);
pqxx::nontransaction N(C);
pqxx::result R( N.exec( sql ));

for (pqxx::result::const_iterator c = R.begin(); c != R.end(); ++c) {

}

for (pqxx::result::const_iterator c = R.begin(); c != R.end(); ++c) {
}

loop include problem

if we include <pqxx/row>, we will get compile error.

row ->row.hxx -> field -> field.hxx ->result -> result.hxx -> result_iterator.hxx -> row

Running a program with libpqxx, getting error: The application was unable to start correctly (0xc000007b). Click OK to close the application.

I was able to successfully build the Static library for libpqxx using the command:
nmake /f win32/vc-libpqxx.mak STATIC
on the Developer Command Prompt for VS2013.

I then copied and paste one of the sample programs, such as below:

#include "stdafx.h"
#include
#include <pqxx/pqxx>

using namespace std;
using namespace pqxx;

int main(int argc, char *argv[])
{
try {
connection C("dbname = test user = postgres password = rcm
hostaddr = 127.0.0.1 port = 5434");
/if (C.is_open()) {
cout << "Opened database successfully: " << C.dbname() << endl;
}
else {
cout << "Can't open database" << endl;
return 1;
}
C.disconnect();
/
}
catch (const std::exception &e) {
cerr << e.what() << std::endl;
return 1;
}
return 0;
}

Successfully compiled but when I run the executable, I get a pop-up error that states:
The application was unable to start correctly (0xc000007b). Click OK to close the application.

Searching online, it seems to be due to a 32-bit application calling a 64-bit DLL issue. I've used Dependency Walker (but people online states it's too old and isn't accurate, i.e. 2006) and I've used ProcessMonitor but nothing stands out.

Any advice?

std::optional wrapper breaks MSYS2 builds

Commit d6f3057 breaks MSYS2 builds on Windows (mingw64, i686, gcc version 6.2.0) :

In file included from ../include/pqxx/field:19:0,
                 from ../include/pqxx/result.hxx:31,
                 from ../include/pqxx/result:19,
                 from ../include/pqxx/binarystring.hxx:26,
                 from ../include/pqxx/binarystring:18,
                 from connection_base.cxx:46:
../include/pqxx/field.hxx: In member function 'int pqxx::field::get_opt() const':
../include/pqxx/field.hxx:215:36: error: expected primary-expression before ')' token
     if (is_null()) return OPTIONAL();
                                    ^

c++11 flag is not added in configure

g++ -DHAVE_CONFIG_H -I../include -I../include -I/usr/include/postgresql -g -O2 -Wno-long-long -fvisibility=hidden -fvisibility-inlines-hidden -MT binarystring.lo -MD -MP -MF .deps/binarystring.Tpo -c binarystring.cxx -fPIC -DPIC -o .libs/binarystring.o - one of the lines that was executed. autotools must explicitly add -std=c++0x

Automatic reconnect function

Can you add automatic reconnect function? thanks.
For instance, When the server restarts, test cannot auto re connect to the server.

double free or corruption after sql execution

Hello,

I tried the example but I get the "double free or corruption" error.

Found 7employees:
... double free or corruption (!prev): 0x0000563b64fa5f30 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x7230b)[0x7f28df2b030b]
/lib/x86_64-linux-gnu/libc.so.6(+0x7896e)[0x7f28df2b696e]
/lib/x86_64-linux-gnu/libc.so.6(+0x791ce)[0x7f28df2b71ce]
/usr/lib/x86_64-linux-gnu/libpqxx-4.0.so(+0x327d0)[0x7f28e01057d0]
/usr/lib/x86_64-linux-gnu/libpqxx-4.0.so(_ZN4pqxx8internal19freemem_result_dataEPKNS0_11result_dataE+0xe)[0x7f28e01057fe]
....

linking to shared lib fails on github master but succeeds on svn trunk

here is the example test case C++ source code I'm using for foo.cpp

#include "pqxx/pqxx"

#include <iostream>

int main()
{
	auto conn_string = "dbname=foo user=foo password=foo";
	auto sql = "SELECT 1";

	pqxx::result rs;
	try {
		pqxx::connection conn(conn_string);
		pqxx::work w(conn);
		rs = w.exec(sql);
		w.commit();
	} catch (const std::exception &e) {
		std::cout << "Exception:\n" << e.what() << std::endl;
	}

	return 0;
}

I'm using the following process, which successfully compiles (and runs) foo.cpp against the shared lib version as of svn trunk 1945 but fails when using the latest github master

git clone https://github.com/jtv/libpqxx
cd libpqxx
CXXFLAGS="-std=c++11 -DPQXX_SHARED -g" ./configure --disable-documentation --enable-shared=yes --enable-static=no --prefix=$HOME/local
make
make install
cd ~/pqxx_foo_test
g++ foo.cpp -v -o foo -std=c++11 -I$HOME/local/include -L$HOME/local/lib -DPQXX_SHARED -lpqxx -lpq && ./foo

the build of libpqxx completes successfully but in the last step, where I compile foo.cpp using g++ compilation succeeds but linking fails with the following error

In function `pqxx::result::make_data_pointer(pg_result const*)': /home/me/local/include/pqxx/result.hxx:203: undefined reference to `pqxx::internal::clear_result(pg_result const*)'

NOTE: it appears that -DPQXX_SHARED is not required on linux because compiling svn trunk and compiling my example foo.cpp against the shared svn trunk works with or without this flag. reading the docs, it is not clear to me whether this directive is required on windows only, or at all, I am including it when building both svn trunk and github master, nothing appears to change if I leave it out

my gcc version information

g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

compiling github master statically and linking foo.cpp to libpqxx statically succeeds

Windows Copy path correction

In win32/vc-libpqxx.mak, the file copy paths need to be amended to move the quotation mark after the LIBPQPATH variable as follows:

Line 259: copy $(LIBPQPATH)"$(LIBPQDLL)" "$(OUTDIR)"
Line 269: copy $(LIBPQDPATH)"$(LIBPQDDLL)" "$(OUTDIR)"
Line 272: copy $(LIBPQPATH)"$(LIBPQLIB)" "$(OUTDIR)"
Line 275: copy $(LIBPQDPATH)"$(LIBPQDLIB)" "$(OUTDIR)"

Kind Regards

Simon Fagg
Wedgetail Systems

Not used `string_traits::subject_type`

using subject_type = T; \

I think it should be removed because it confuses those who specialize their types for string_traits. It raises a question: Should I add that alias in my specialization or not?

In the bellow specializations it is not defined

template<> struct PQXX_LIBEXPORT string_traits<const char *>
{
static constexpr const char *name() noexcept { return "const char *"; }
static constexpr bool has_null() noexcept { return true; }
static bool is_null(const char *t) { return !t; }
static const char *null() { return nullptr; }
static void from_string(const char Str[], const char *&Obj) { Obj = Str; }
static std::string to_string(const char *Obj) { return Obj; }
};

Configure doesn't use correct compiler flags

Even after regenerating configure using autogen.sh, libpqxx only builds correctly when setting CXXFLAGS to include -std=c++17 manually. Configure should append proper switches instead.

Broken example on http://pqxx.org

Not sure if this is right place to report, but didn't find anything else.

On http://pqxx.org/development/libpqxx/ the "Complete example" at the bottom doesn't compile. The for (auto row: r) row iteration is missing a closing brace.

Also, the catch statements at the bottom should be reversed as the pqxx::sql_error catch is unreachable because the std::exception will always catch it first.

Warning on Mac in ld while building with clang

ld: warning: direct access in function 'std::__1::__shared_ptr_pointer<pg_result const*, void (*)(pg_result const*), std::__1::allocator<pg_result const> >::__get_deleter(std::type_info const&) const' from file '/Users/sergey.kurenkov/src/tests/env/lib/libpqxx.a(connection_base.o)' to global weak symbol 'typeinfo name for void (*)(pg_result const*)' from file 'CMakeFiles/tests.dir///tests/test.cpp.o' means the weak symbol cannot be overridden at runtime. This was likely caused by different translation units being compiled with different visibility settings.

clang:

$ clang --version
Apple LLVM version 9.0.0 (clang-900.0.39.2)
Target: x86_64-apple-darwin16.7.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

Documentation Question?

The following sentence is on the website: http://pqxx.org/development/libpqxx/

Just one caveat: not all platforms support throwing an exception in a shared library and catching it outside that shared library. It's probably a good habit to use dynamic libraries instead.

What exactly is meant by "use dynamic libraries instead" (of shared library). I have no idea what that means. What is the meaning of dynamic and shared libraries in the case of libpqxx? In most literature they are synonymous.

Undefined reference when building PQXX (pqxx::internal::clear_result(pg_result const*)

Hi everyone,
I'm having problems testing the library, I'm getting the following error:

test_escape.o: In function `pqxx::internal::PQAlloc<pg_result const, &pqxx::internal::clear_result>::loseref()':
/libpqxx-master/test/unit/../../include/pqxx/util.hxx:609: undefined reference to `pqxx::internal::clear_result(pg_result const*)'

What I did to build the library was:
./configure --prefix=/usr/local --enable-shared
make -j8
sudo make install

Build Fails on Mac OS X

Consult the full error log here: log.txt

So the build fails on Mac OS X with AppleClang8.1 with the error output shown in the log. This is because it apparently doesn't recognize that it is C++11 syntax. This is easily amended by passing the -std=c++11 flag to the compiler. For anyone having this problem just be sure to pass make the flag like so:

make CXXFLAGS="-std=c++11"

Maybe add a flag to the Makefile in order to eliminate any doubts that the compiler will compile for C++11?

cannot convert 'std::basic_istream<char>::__istream_type to bool (C++11)

Compiling on Alpine Linux

strconv.cxx:233:10: error: cannot convert 'std::basic_istream<char>::__istream_type {aka std::basic_istream<char>}' to 'bool' in assignment
       ok = (S >> result);

It seems to be linked to boolean being explicit with C++11
(see http://stackoverflow.com/questions/22330765/how-to-fix-istringstream-compiler-error)

I'm not a C++ expert, but it seems easy to fix.
Just wanted to report and make sure I'm correct about the assumption.

out of source ./configure script fails with: IOError: [Errno 2] No such file or directory: u'../libpqxx/include/pqxx/config.h'

when doing an out of source build as of 3f38637 i.e. latest master, the following error occurs

Traceback (most recent call last):
  File "../libpqxx/tools/splitconfig", line 182, in <module>
    main()
  File "../libpqxx/tools/splitconfig", line 171, in main
    original_header = read_header(args.sourcetree, 'include/pqxx/config.h')
  File "../libpqxx/tools/splitconfig", line 73, in read_header
    return read_lines(os.path.join(source_tree, filename))
  File "../libpqxx/tools/splitconfig", line 41, in read_lines
    with codecs.open(path, encoding='ascii') as stream:
  File "/usr/lib/python2.7/codecs.py", line 896, in open
    file = __builtin__.open(filename, mode, buffering)
IOError: [Errno 2] No such file or directory: u'../libpqxx/include/pqxx/config.h'

when building inside the main source tree, this error does not occur

here are steps to reproduce and the full output

$ git clone https://github.com/jtv/libpqxx
Cloning into 'libpqxx'...
remote: Counting objects: 22598, done.
remote: Compressing objects: 100% (24/24), done.
remote: Total 22598 (delta 10), reused 6 (delta 3), pack-reused 22571
Receiving objects: 100% (22598/22598), 4.56 MiB | 2.93 MiB/s, done.
Resolving deltas: 100% (18238/18238), done.
Checking connectivity... done.

$ mkdir libpqxx_build
$ cd libpqxx_build
$ ../libpqxx/configure
checking for g++... g++
checking whether the C++ compiler works... yes
checking for C++ compiler default output file name... a.out
checking for suffix of executables... 
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking whether g++ supports C++11 features by default... no
checking whether g++ supports C++11 features with -std=gnu++11... yes
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... gawk
checking whether make sets $(MAKE)... yes
checking for style of include used by make... GNU
checking whether make supports nested variables... yes
checking dependency style of g++... gcc3
checking whether we are using the GNU C++ compiler... (cached) yes
checking whether g++ accepts -g... (cached) yes
checking for gcc... gcc
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking whether gcc understands -c and -o together... yes
checking dependency style of gcc... gcc3
checking build system type... x86_64-unknown-linux-gnu
checking host system type... x86_64-unknown-linux-gnu
checking how to print strings... printf
checking for a sed that does not truncate output... /bin/sed
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for fgrep... /bin/grep -F
checking for ld used by gcc... /usr/bin/ld
checking if the linker (/usr/bin/ld) is GNU ld... yes
checking for BSD- or MS-compatible name lister (nm)... /usr/bin/nm -B
checking the name lister (/usr/bin/nm -B) interface... BSD nm
checking whether ln -s works... yes
checking the maximum length of command line arguments... 1572864
checking how to convert x86_64-unknown-linux-gnu file names to x86_64-unknown-linux-gnu format... func_convert_file_noop
checking how to convert x86_64-unknown-linux-gnu file names to toolchain format... func_convert_file_noop
checking for /usr/bin/ld option to reload object files... -r
checking for objdump... objdump
checking how to recognize dependent libraries... pass_all
checking for dlltool... no
checking how to associate runtime and link libraries... printf %s\n
checking for ar... ar
checking for archiver @FILE support... @
checking for strip... strip
checking for ranlib... ranlib
checking command to parse /usr/bin/nm -B output from gcc object... ok
checking for sysroot... no
checking for a working dd... /bin/dd
checking how to truncate binary pipes... /bin/dd bs=4096 count=1
checking for mt... mt
checking if mt is a manifest tool... no
checking how to run the C preprocessor... gcc -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking for dlfcn.h... yes
checking for objdir... .libs
checking if gcc supports -fno-rtti -fno-exceptions... no
checking for gcc option to produce PIC... -fPIC -DPIC
checking if gcc PIC flag -fPIC -DPIC works... yes
checking if gcc static flag -static works... yes
checking if gcc supports -c -o file.o... yes
checking if gcc supports -c -o file.o... (cached) yes
checking whether the gcc linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes
checking dynamic linker characteristics... GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
checking whether stripping libraries is possible... yes
checking if libtool supports shared libraries... yes
checking whether to build shared libraries... no
checking whether to build static libraries... yes
checking how to run the C++ preprocessor... g++ -E
checking for ld used by g++... /usr/bin/ld -m elf_x86_64
checking if the linker (/usr/bin/ld -m elf_x86_64) is GNU ld... yes
checking whether the g++ linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes
checking for g++ option to produce PIC... -fPIC -DPIC
checking if g++ PIC flag -fPIC -DPIC works... yes
checking if g++ static flag -static works... yes
checking if g++ supports -c -o file.o... yes
checking if g++ supports -c -o file.o... (cached) yes
checking whether the g++ linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes
checking dynamic linker characteristics... (cached) GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
checking whether make sets $(MAKE)... (cached) yes
checking for mkdir... /bin/mkdir
checking for pkg-config... /usr/bin/pkg-config
checking for doxygen... no
checking for dot... YES
checking for xmlto... no
checking whether to enable maintainer-specific portions of Makefiles... no
checking maintainer mode... 
checking g++ visibility attribute... yes
checking g++ const attribute... yes
checking C++14 deprecation attribute... yes
checking g++ pure attribute... yes
checking for C++17 std::optional support... no
checking for experimental C++17 std::optional support... no
checking for pg_config... /usr/bin/pg_config
configure: using PostgreSQL headers at /usr/include/postgresql
configure: using PostgreSQL libraries at /usr/lib/x86_64-linux-gnu
checking for ANSI C header files... (cached) yes
checking for library containing select... none required
checking /usr/include/postgresql/libpq-fe.h usability... yes
checking /usr/include/postgresql/libpq-fe.h presence... yes
checking for /usr/include/postgresql/libpq-fe.h... yes
checking for ability to compile source files using libpq... yes
checking for main in -lpq... yes
checking for PQexec in -lpq... yes
checking for correct C++ linkage of basic libpq functions... yes
checking for C++11 support... checking that type of libpq's Oid is as expected... yes
checking for strerror_r... yes
checking for GNU-style strerror_r... yes
checking for strlcpy... no
checking for working <sys/select.h>... yes
checking for poll()... yes
checking if select() accepts NULL fdsets... yes
checking whether make sets $(MAKE)... (cached) yes
checking that generated files are newer than configure... done
configure: creating ./config.status
config.status: creating Makefile
config.status: creating config/Makefile
config.status: creating doc/Makefile
config.status: creating doc/Doxyfile
config.status: creating src/Makefile
config.status: creating test/Makefile
config.status: creating test/unit/Makefile
config.status: creating tools/Makefile
config.status: creating win32/Makefile
config.status: creating include/Makefile
config.status: creating include/pqxx/Makefile
config.status: creating libpqxx.pc
config.status: creating pqxx-config
config.status: creating include/pqxx/config.h
config.status: executing depfiles commands
config.status: executing libtool commands
config.status: executing configitems commands
Traceback (most recent call last):
  File "../libpqxx/tools/splitconfig", line 182, in <module>
    main()
  File "../libpqxx/tools/splitconfig", line 171, in main
    original_header = read_header(args.sourcetree, 'include/pqxx/config.h')
  File "../libpqxx/tools/splitconfig", line 73, in read_header
    return read_lines(os.path.join(source_tree, filename))
  File "../libpqxx/tools/splitconfig", line 41, in read_lines
    with codecs.open(path, encoding='ascii') as stream:
  File "/usr/lib/python2.7/codecs.py", line 896, in open
    file = __builtin__.open(filename, mode, buffering)
IOError: [Errno 2] No such file or directory: u'../libpqxx/include/pqxx/config.h'

Having issues building libpqxx with MinGW + MSYS on windows: libpq-fe.h no such file

I've downloaded the release distribution libpqxx-4.0.1.tar.gz. I've already installed PostgreSQL 9.6 from the installer and so this includes the libpq-fe.h.

To Reproduce the Bug:

  1. When running the configure.sh script as-is from the release distribution, the values of pg_config --libdir and pg_config --includedir weren't being stored into the variables, so I added a fix so that it would run pg_config properly and get the values stored to the variable.

pg_config --libdir returns C:\Program Files\PostgreSQL\9.6\lib
pg_config --includedir returns C:\Program Files\PostgreSQL\9.6\include

With those outputs, I've also added a fix so that the Program Files were replaced with Program/ Files to escape the space, as follows:

pg_config --libdir returns C:\Program/ Files\PostgreSQL\9.6\lib
pg_config --includedir returns C:\Program/ Files\PostgreSQL\9.6\include

  1. I've exported LDFLAGS and CPPFLAGS:
    LDFLAGS="-IC:\Windows\System32 -IC:\PROGRA~1\PostgreSQL\9.6\include"
    CPPFLAGS="-LC:\Boost"

  2. Ran configure.sh in mingw+msys, the script aborts telling me that libpq-fe.h no such file exists. The config.log shows that it is adding #include<C:\Program/ Files\PostgreSQL\9.6\include\libpq-fe.h>. And just generally looking at the configure.sh code, all the #include<{with_postgres_include}\libpq-fe.h> requires the postgres include directory to be added.

I've tried not adding the second -I flag in LDFLAGS but I still get this error.
Any ideas would be greatly appreciated!

Why not use unique_ptr<> ?

This is just a question, you can close this issue right away.

The below code is like this for a reason or just a habit?

char *const buf = new char[2*maxlen+1];
try
{
int err = 0;
PQescapeStringConn(m_conn, buf, str, maxlen, &err);
if (err) throw argument_error(err_msg());
escaped = std::string(buf);
}
catch (const std::exception &)
{
delete [] buf;
throw;
}
delete [] buf;

http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#e6-use-raii-to-prevent-leaks

Access column result of array integer[]

Hello.I have a problem to get the result of a column of integer[] (array of integers) as std::vectorstd::int32_t. Can I do this using libpqxx library methods?

libpqxx internal error: pqxx::transaction: invalid status code

when trying to exec a prepared statement I get

I am using libpqxx 4.0.1

terminate called after throwing an instance of 'pqxx::internal_error'
  what():  libpqxx internal error: pqxx::transaction: invalid status code
[1]    29097 abort (core dumped)

relevant lines:

conn_.prepare("insertval", "INSERT INTO values (value, datetime, variable_id) VALUES($1, $2, $3)");

if(!w_) {
    w_ = new pqxx::work(conn_);
}
w_->prepared("insertval")(value)(timestamp)(var_id).exec();

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.