Skip to content

Commit

Permalink
PG: avoid error when the original search_path is empty
Browse files Browse the repository at this point in the history
  • Loading branch information
rouault committed Oct 9, 2024
1 parent 4e28921 commit ab40f2d
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 5 deletions.
31 changes: 31 additions & 0 deletions autotest/ogr/ogr_pg.py
Original file line number Diff line number Diff line change
Expand Up @@ -6200,3 +6200,34 @@ def test_ogr_pg_ogr2ogr_with_multiple_dotted_table_name(pg_ds):

finally:
pg_ds.ExecuteSQL(f'DROP SCHEMA "{tmp_schema}" CASCADE')


###############################################################################
# Test scenario of https://lists.osgeo.org/pipermail/gdal-dev/2024-October/059608.html


@only_without_postgis
@gdaltest.enable_exceptions()
def test_ogr_pg_empty_search_path(pg_ds):

with pg_ds.ExecuteSQL("SHOW search_path") as sql_lyr:
f = sql_lyr.GetNextFeature()
old_search_path = f.GetField(0)
old_search_path = old_search_path.replace(
"test_ogr_pg_empty_search_path_no_postgis, ", ""
)

with pg_ds.ExecuteSQL("SELECT CURRENT_USER") as lyr:
f = lyr.GetNextFeature()
current_user = f.GetField(0)
pg_ds.ExecuteSQL(f"ALTER ROLE {current_user} SET search_path = ''")
try:
ds = reconnect(pg_ds, update=1)

with ds.ExecuteSQL("SHOW search_path") as sql_lyr:
f = sql_lyr.GetNextFeature()
new_search_path = f.GetField(0)
assert new_search_path == "test_ogr_pg_empty_search_path_no_postgis, public"

finally:
ds.ExecuteSQL(f"ALTER ROLE {current_user} SET search_path = {old_search_path}")
16 changes: 11 additions & 5 deletions ogr/ogrsf_frmts/pg/ogrpgdatasource.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -653,13 +653,18 @@ int OGRPGDataSource::Open(const char *pszNewName, int bUpdate, int bTestOpen,
{
osNewSearchPath +=
OGRPGEscapeString(hPGConn, osActiveSchema.c_str());
osNewSearchPath += ',';
}
osNewSearchPath += osSearchPath;
if (!osSearchPath.empty() && osSearchPath != "\"\"")
{
if (!osNewSearchPath.empty())
osNewSearchPath += ',';
osNewSearchPath += osSearchPath;
}
if (!osPostgisSchema.empty() &&
osSearchPath.find(osPostgisSchema) == std::string::npos)
{
osNewSearchPath += ',';
if (!osNewSearchPath.empty())
osNewSearchPath += ',';
osNewSearchPath +=
OGRPGEscapeString(hPGConn, osPostgisSchema.c_str());
}
Expand All @@ -674,8 +679,9 @@ int OGRPGDataSource::Open(const char *pszNewName, int bUpdate, int bTestOpen,
OGRPGClearResult(hResult);
CPLDebug("PG", "Command \"%s\" failed. Trying without 'public'.",
osCommand.c_str());
osCommand =
CPLSPrintf("SET search_path='%s'", osActiveSchema.c_str());
osCommand = CPLSPrintf(
"SET search_path=%s",
OGRPGEscapeString(hPGConn, osActiveSchema.c_str()).c_str());
PGresult *hResult2 = OGRPG_PQexec(hPGConn, osCommand.c_str());

if (!hResult2 || PQresultStatus(hResult2) != PGRES_COMMAND_OK)
Expand Down

0 comments on commit ab40f2d

Please sign in to comment.