@@ -1401,6 +1401,49 @@ void QgsPostgresProvider::findColumns(tableCols& cols)
1401
1401
temp.table_type = PQgetvalue (result, i, 6 );
1402
1402
temp.column_type = PQgetvalue (result, i, 7 );
1403
1403
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
+
1404
1447
QgsDebugMsg (temp.view_schema + " ."
1405
1448
+ temp.view_name + " ."
1406
1449
+ temp.view_column_name + " <- "
0 commit comments