I connect to Postgres using GDAL 2.0 API using the function GDALOpenEx() as below. But when I use poDS->GetLayerCount(), it just returns 0. My Postgres(v9.5) has a database name postgres, and the schema public contains 3 tables with data. What is wrong?

#include <ogrsf_frmts.h>
bool read_data_from_postgis()
    using std::string;
    GDALDataset* poDS;
    string source = "PG:host= port=5432 user=postgres password=abcd dbname=postgres";

    poDS = (GDALDataset*)GDALOpenEx(source.c_str(), NULL, NULL, (const char* const*)"LIST_ALL_TABLES=YES", NULL);
    if (poDS == nullptr)
        std::cerr << "connection FAILED.\n";
        return false;
    std::cout << "Connected to Postgres.\n";
    std::cout << poDS->GetLayerCount() << std::endl;  // return 0!!

    return true;
  • Try adding the GDAL_OF_VERBOSE_ERROR flag to GDALOpenEx and run poDS->ReportError and poDS->GetDriverName. See if those are as expected or provide any more information. – RomaH Aug 18 '16 at 20:01
  • Oh and check the FAQ at the bottom of the page about permissions. Could be a silent error: gdal.org/drv_pg.html – RomaH Aug 18 '16 at 20:18
  • @RomaH, thanks for your tips. And according to your advice, I added GDAL_OF_VERBOSE_ERROR | GDAL_OF_VECTOR as the openFlags parameter. Then I can get the layer with geometry. Nice! However, not all layers are listed. I tried to put "LIST_ALL_TABLES=YES" as openOptions parameter. But it does not work. Any tips on this? – stevenhz Aug 20 '16 at 19:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.