Skip to content

Commit 6bdc552

Browse files
author
g_j_m
committed
Partial fix for ticket #277
git-svn-id: http://svn.osgeo.org/qgis/trunk/qgis@6266 c8812cc2-4d05-0410-92ff-de0c093fc19c
1 parent e07bffb commit 6bdc552

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/providers/postgres/qgspostgresprovider.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1401,6 +1401,49 @@ void QgsPostgresProvider::findColumns(tableCols& cols)
14011401
temp.table_type = PQgetvalue(result, i, 6);
14021402
temp.column_type = PQgetvalue(result, i, 7);
14031403

1404+
// BUT, the above SQL doesn't always give the correct value for the view
1405+
// column name (that's because that information isn't available directly
1406+
// from the database), mainly when the view column name has been renamed
1407+
// using 'AS'. To fix this we need to look in the view definition and
1408+
// adjust the view column name if necessary.
1409+
1410+
QString view = "SELECT definition FROM pg_views WHERE schemaname = '" + temp.view_schema + "' AND "
1411+
" viewname = '" + temp.view_name + "'";
1412+
1413+
PGresult* r = PQexec(connection, (const char*)(view.utf8()));
1414+
if (PQntuples(r) > 0)
1415+
{
1416+
QString viewDef = PQgetvalue(r, 0, 0);
1417+
// Now pick the view definiton apart, looking for
1418+
// temp.column_name to the left of an 'AS'.
1419+
1420+
// This regular expression needs more work and testing. Since the view
1421+
// definition comes from postgresql and has been 'standardised', we
1422+
// don't need to deal with everything that the user could put in a view
1423+
// definition. Possible variations could include:
1424+
// - lowercase AS
1425+
// - quotes around table and column names
1426+
// - inclusion of the scheam
1427+
// - meaningful characters in the schema/table/column names (such as . ' " )
1428+
// - anything else???
1429+
QRegExp s(".* " + temp.table_name + "\\." + temp.column_name + " AS (\\w+),* .*");
1430+
1431+
#ifdef QGSIDEBUG
1432+
std::cerr <<__FILE__<<__LINE__ << ' ' << view.toLocal8Bit().data() << '\n'
1433+
<< viewDef.toLocal8Bit().data() << '\n'
1434+
<< s.pattern().toLocal8Bit().data() << '\n';
1435+
#endif
1436+
1437+
if (s.indexIn(viewDef) != -1)
1438+
{
1439+
temp.view_column_name = s.cap(1);
1440+
//std::cerr<<__FILE__<<__LINE__<<' '<<temp.view_column_name.toLocal8Bit().data()<<'\n';
1441+
}
1442+
}
1443+
else
1444+
QgsDebugMsg("Failed to get view definition for " + temp.view_schema + "." + temp.view_name);
1445+
1446+
14041447
QgsDebugMsg(temp.view_schema + "."
14051448
+ temp.view_name + "."
14061449
+ temp.view_column_name + " <- "

0 commit comments

Comments
 (0)