[QGIS Commit] r8160 - in branches/ogr-plugin-branch/src: app app/dbutilities core ui

svn_qgis at osgeo.org svn_qgis at osgeo.org
Fri Feb 15 16:20:18 EST 2008


Author: gcontreras
Date: 2008-02-15 16:20:17 -0500 (Fri, 15 Feb 2008)
New Revision: 8160

Modified:
   branches/ogr-plugin-branch/src/app/CMakeLists.txt
   branches/ogr-plugin-branch/src/app/dbutilities/qgsogrdatabaseconnection.cpp
   branches/ogr-plugin-branch/src/app/dbutilities/qgspostgresdatabaseconnection.cpp
   branches/ogr-plugin-branch/src/app/qgsdbsourceselect.cpp
   branches/ogr-plugin-branch/src/app/qgsdbsourceselect.h
   branches/ogr-plugin-branch/src/app/qgsnewconnection.cpp
   branches/ogr-plugin-branch/src/app/qgsnewconnection.h
   branches/ogr-plugin-branch/src/core/qgsdatasourceuri.cpp
   branches/ogr-plugin-branch/src/ui/qgsdbsourceselectbase.ui
Log:
Changes to adapt newconnection dialog to work with
the new dbutility classes 

Modified: branches/ogr-plugin-branch/src/app/CMakeLists.txt
===================================================================
--- branches/ogr-plugin-branch/src/app/CMakeLists.txt	2008-02-14 19:16:45 UTC (rev 8159)
+++ branches/ogr-plugin-branch/src/app/CMakeLists.txt	2008-02-15 21:20:17 UTC (rev 8160)
@@ -16,6 +16,8 @@
 qgsclipboard.cpp
 qgscontinuouscolordialog.cpp
 qgscustomprojectiondialog.cpp
+qgsdbfilterproxymodel.cpp
+qgsdbtablemodel.cpp
 qgsdelattrdialog.cpp
 qgsfillstylewidget.cpp
 qgsgeomtypedialog.cpp

Modified: branches/ogr-plugin-branch/src/app/dbutilities/qgsogrdatabaseconnection.cpp
===================================================================
--- branches/ogr-plugin-branch/src/app/dbutilities/qgsogrdatabaseconnection.cpp	2008-02-14 19:16:45 UTC (rev 8159)
+++ branches/ogr-plugin-branch/src/app/dbutilities/qgsogrdatabaseconnection.cpp	2008-02-15 21:20:17 UTC (rev 8160)
@@ -70,7 +70,8 @@
   else
    {
      uri=this->uri();            
-   } 
+   }
+  qDebug("inche uri:"+uri);  
   //clean all previous errors
   CPLErrorReset(); 
   // Register all OGR-drivers

Modified: branches/ogr-plugin-branch/src/app/dbutilities/qgspostgresdatabaseconnection.cpp
===================================================================
--- branches/ogr-plugin-branch/src/app/dbutilities/qgspostgresdatabaseconnection.cpp	2008-02-14 19:16:45 UTC (rev 8159)
+++ branches/ogr-plugin-branch/src/app/dbutilities/qgspostgresdatabaseconnection.cpp	2008-02-15 21:20:17 UTC (rev 8160)
@@ -54,7 +54,7 @@
     " port=" + mConnectionParameters->port +
     " user=" + mConnectionParameters->user + 
     " password='" + pass + "'";
-  PGconn *pd = PQconnectdb(connInfo.toLocal8Bit().data());
+  pd = PQconnectdb(connInfo.toLocal8Bit().data());
   //  std::cout << pd->ErrorMessage();
   if (PQstatus(pd) == CONNECTION_OK)
     {
@@ -70,7 +70,6 @@
       result=false;
     }
   
-   
   return result;     
 }
 

Modified: branches/ogr-plugin-branch/src/app/qgsdbsourceselect.cpp
===================================================================
--- branches/ogr-plugin-branch/src/app/qgsdbsourceselect.cpp	2008-02-14 19:16:45 UTC (rev 8159)
+++ branches/ogr-plugin-branch/src/app/qgsdbsourceselect.cpp	2008-02-15 21:20:17 UTC (rev 8160)
@@ -20,10 +20,13 @@
 #include "qgsdbsourceselect.h"
 
 #include "qgisapp.h"
+#include "qgslogger.h"
 #include "qgsapplication.h"
 #include "qgscontexthelp.h"
 #include "qgsnewconnection.h"
+#include "qgsnewogrgenericconnection.h"
 #include "qgspgquerybuilder.h"
+#include "qgsdatasourceuri.h"
 
 #include <QInputDialog>
 #include <QMessageBox>
@@ -39,92 +42,77 @@
 QgsDbSourceSelect::QgsDbSourceSelect(QgisApp *app, Qt::WFlags fl)
   : QDialog(app, fl), mColumnTypeThread(NULL), qgisApp(app), pd(0)
 {
+  //create member objects
+  mConnectionRegistry=new QgsConnectionRegistry;
+  
   setupUi(this);
+  btnAdd->setEnabled(false);
   
+  //get last connection type used
+  QString connType=mConnectionRegistry->selectedType();
+  populateConnectionList(connType);
+  setConnectionListPosition();
+ 
   //connect 
-  
   connect(cmbType,SIGNAL(currentIndexChanged(QString)),this,SLOT(populateConnectionList(QString)));
-  btnAdd->setEnabled(false);
-  //create connection manager
-  mConnMan=new QgsConnectionManager;
   
   //get last connection type used
-  QString conType=mConnMan->getSelectedType();
+  QString conType=mConnectionRegistry->selectedType();
   populateConnectionList(conType);
   setConnectionListPosition();
-  //loadConnections("PostgreSQL");
-  // connect the double-click signal to the addSingleLayer slot in the parent
+  
+  mSearchModeComboBox->addItem(tr("Wildcard"));
+  mSearchModeComboBox->addItem(tr("RegExp"));
 
-  //disable the 'where clause' box for 0.4 release
-  //  groupBox3->hide();
-  //insert the encoding types available in qt
-  mEncodingComboBox->insertItem("BIG5"); 
-  mEncodingComboBox->insertItem("BIG5-HKSCS"); 
-  mEncodingComboBox->insertItem("EUCJP"); 
-  mEncodingComboBox->insertItem("EUCKR"); 
-  mEncodingComboBox->insertItem("GB2312"); 
-  mEncodingComboBox->insertItem("GBK"); 
-  mEncodingComboBox->insertItem("GB18030"); 
-  mEncodingComboBox->insertItem("JIS7"); 
-  mEncodingComboBox->insertItem("SHIFT-JIS"); 
-  mEncodingComboBox->insertItem("TSCII"); 
-  mEncodingComboBox->insertItem("UTF-8"); 
-  mEncodingComboBox->insertItem("UTF-16"); 
-  mEncodingComboBox->insertItem("KOI8-R"); 
-  mEncodingComboBox->insertItem("KOI8-U"); 
-  mEncodingComboBox->insertItem("ISO8859-1"); 
-  mEncodingComboBox->insertItem("ISO8859-2");
-  mEncodingComboBox->insertItem("ISO8859-3"); 
-  mEncodingComboBox->insertItem("ISO8859-4"); 
-  mEncodingComboBox->insertItem("ISO8859-5"); 
-  mEncodingComboBox->insertItem("ISO8859-6");
-  mEncodingComboBox->insertItem("ISO8859-7"); 
-  mEncodingComboBox->insertItem("ISO8859-8"); 
-  mEncodingComboBox->insertItem("ISO8859-8-I"); 
-  mEncodingComboBox->insertItem("ISO8859-9"); 
-  mEncodingComboBox->insertItem("ISO8859-10"); 
-  mEncodingComboBox->insertItem("ISO8859-13"); 
-  mEncodingComboBox->insertItem("ISO8859-14"); 
-  mEncodingComboBox->insertItem("ISO8859-15"); 
-  mEncodingComboBox->insertItem("IBM 850"); 
-  mEncodingComboBox->insertItem("IBM 866"); 
-  mEncodingComboBox->insertItem("CP874"); 
-  mEncodingComboBox->insertItem("CP1250"); 
-  mEncodingComboBox->insertItem("CP1251"); 
-  mEncodingComboBox->insertItem("CP1252"); 
-  mEncodingComboBox->insertItem("CP1253"); 
-  mEncodingComboBox->insertItem("CP1254"); 
-  mEncodingComboBox->insertItem("CP1255"); 
-  mEncodingComboBox->insertItem("CP1256"); 
-  mEncodingComboBox->insertItem("CP1257"); 
-  mEncodingComboBox->insertItem("CP1258"); 
-  mEncodingComboBox->insertItem("Apple Roman"); 
-  mEncodingComboBox->insertItem("TIS-620"); 
+  mSearchColumnComboBox->addItem(tr("All"));
+  mSearchColumnComboBox->addItem(tr("Schema"));
+  mSearchColumnComboBox->addItem(tr("Table"));
+  mSearchColumnComboBox->addItem(tr("Type"));
+  mSearchColumnComboBox->addItem(tr("Geometry column"));
+  mSearchColumnComboBox->addItem(tr("Sql"));
 
-  //read the last encoding from the settings
-  //or use local as default
-  QSettings settings; 
-  QString lastUsedEncoding = settings.readEntry("/UI/encoding");
-  if(lastUsedEncoding.isNull()||lastUsedEncoding.isEmpty()||lastUsedEncoding=="\0")
-    {
-      mEncodingComboBox->setCurrentText(QString(QTextCodec::codecForLocale()->name()));
-    }
-  else
-    {
-      mEncodingComboBox->setCurrentText(lastUsedEncoding);
-    }
+  mProxyModel.setParent(this);
+  mProxyModel.setFilterKeyColumn(-1);
+  mProxyModel.setFilterCaseSensitivity(Qt::CaseInsensitive);
+  mProxyModel.setDynamicSortFilter(true);
+  mProxyModel.setSourceModel(&mTableModel);
+  mTablesTreeView->setModel(&mProxyModel);
+  mTablesTreeView->setSortingEnabled(true);
 
-  // Do some things that couldn't be done in designer
-  lstTables->horizontalHeader()->setStretchLastSection(true);
-  // Set the column count to 3 for the type, name, and sql
-  lstTables->setColumnCount(3);
-  mColumnLabels += tr("Type"); 
-  mColumnLabels += tr("Name"); 
-  mColumnLabels += tr("Sql");
-  lstTables->setHorizontalHeaderLabels(mColumnLabels);
-  lstTables->verticalHeader()->hide();
-  
-  
+  mSearchGroupBox->hide();
+  connect(mTablesTreeView, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(setSql(const QModelIndex&)));
+
+   //for Qt < 4.3.2, passing -1 to include all model columns
+  //in search does not seem to work
+  mSearchColumnComboBox->setCurrentIndex(2); 
+  /*setupUi(this);
+  btnAdd->setEnabled(false);
+  populateConnectionList();
+
+  mSearchModeComboBox->addItem(tr("Wildcard"));
+  mSearchModeComboBox->addItem(tr("RegExp"));
+
+  mSearchColumnComboBox->addItem(tr("All"));
+  mSearchColumnComboBox->addItem(tr("Schema"));
+  mSearchColumnComboBox->addItem(tr("Table"));
+  mSearchColumnComboBox->addItem(tr("Type"));
+  mSearchColumnComboBox->addItem(tr("Geometry column"));
+  mSearchColumnComboBox->addItem(tr("Sql"));
+
+  mProxyModel.setParent(this);
+  mProxyModel.setFilterKeyColumn(-1);
+  mProxyModel.setFilterCaseSensitivity(Qt::CaseInsensitive);
+  mProxyModel.setDynamicSortFilter(true);
+  mProxyModel.setSourceModel(&mTableModel);
+  mTablesTreeView->setModel(&mProxyModel);
+  mTablesTreeView->setSortingEnabled(true);
+
+  mSearchGroupBox->hide();
+  connect(mTablesTreeView, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(setSql(const QModelIndex&)));
+
+   //for Qt < 4.3.2, passing -1 to include all model columns
+  //in search does not seem to work
+  mSearchColumnComboBox->setCurrentIndex(2);*/
 }
 /** Autoconnected SLOTS **/
 // Slot for adding a new connection
@@ -143,12 +131,6 @@
   addTables();
 }
 
-// Slot for opening the query builder when a layer is double clicked
-void QgsDbSourceSelect::on_lstTables_itemDoubleClicked(QTableWidgetItem *item)
-{
-  setSql(item);
-}
-
 // Slot for editing a connection
 void QgsDbSourceSelect::on_btnEdit_clicked()
 {
@@ -162,144 +144,300 @@
 }
 /** End Autoconnected SLOTS **/
 
-//remember what type is selected
-void QgsDbSourceSelect::on_cmbType_activated(int)
-{
-  dbChanged();
-}
 // Remember which database is selected
 void QgsDbSourceSelect::on_cmbConnections_activated(int)
 {
   dbChanged();
 }
 
-void QgsDbSourceSelect::setLayerType(QString schema, 
-                                     QString table, QString column,
-                                     QString type)
+void QgsDbSourceSelect::on_mSearchOptionsButton_clicked()
 {
-/*                                     
-#ifdef QGISDEBUG
-  std::cerr << "Received layer type of " << type.toLocal8Bit().data()
-            << " for " 
-            << (schema+'.'+table+'.'+column).toLocal8Bit().data() 
-            << '\n';
-#endif
+  if(mSearchGroupBox->isVisible())
+    {
+      mSearchGroupBox->hide();
+    }
+  else
+    {
+      mSearchGroupBox->show();
+    }
+}
 
-  // Find the right row in the table by searching for the text that
-  // was put into the Name column.
-  QString full_desc = fullDescription(schema, table, column);
+void QgsDbSourceSelect::on_mSearchTableEdit_textChanged(const QString & text)
+{
+  if(mSearchModeComboBox->currentText() == tr("Wildcard"))
+    {
+      mProxyModel._setFilterWildcard(text);
+    }
+  else if(mSearchModeComboBox->currentText() == tr("RegExp"))
+    {
+      mProxyModel._setFilterRegExp(text);
+    }
+}
 
-  QList<QTableWidgetItem*> ii = lstTables->findItems(full_desc,
-                                                     Qt::MatchExactly);
-
-  if (ii.count() > 0)
-  {
-    int row = lstTables->row(ii.at(0)); // just use the first one
-    QTableWidgetItem* iconItem = lstTables->item(row, 0);
-
-    // Get the icon and tooltip text 
-    const QIcon* p;
-    QString toolTipText;
-    if (mLayerIcons.contains(type))
+void QgsDbSourceSelect::on_mSearchColumnComboBox_currentIndexChanged(const QString & text)
+{
+  if(text == tr("All"))
     {
-      p = &(mLayerIcons.value(type).second);
-      toolTipText = mLayerIcons.value(type).first;
+      mProxyModel.setFilterKeyColumn(-1);
     }
-    else
+  else if(text == tr("Schema"))
     {
-      qDebug(("Unknown geometry type of '" + type + "'.").toLocal8Bit().data());
-      p = &(mLayerIcons.value("UNKNOWN").second);
-      toolTipText = mLayerIcons.value("UNKNOWN").first;
+      mProxyModel.setFilterKeyColumn(0);
     }
+  else if(text == tr("Table"))
+    {
+      mProxyModel.setFilterKeyColumn(1);
+    }
+  else if(text == tr("Type"))
+    {
+      mProxyModel.setFilterKeyColumn(2);
+    }
+  else if(text == tr("Geometry column"))
+    {
+      mProxyModel.setFilterKeyColumn(3);
+    }
+  else if(text == tr("Sql"))
+    {
+      mProxyModel.setFilterKeyColumn(4);
+    }
+}
 
-    iconItem->setIcon(*p);
-    iconItem->setToolTip(toolTipText);
-  }*/
+void QgsDbSourceSelect::on_mSearchModeComboBox_currentIndexChanged(const QString & text)
+{
+  on_mSearchTableEdit_textChanged(mSearchTableEdit->text());
 }
 
+void QgsDbSourceSelect::setLayerType(QString schema, 
+                                     QString table, QString column,
+                                     QString type)
+{
+  mTableModel.setGeometryTypesForTable(schema, table, column, type);
+  mTablesTreeView->sortByColumn(1, Qt::AscendingOrder);
+   mTablesTreeView->sortByColumn(0, Qt::AscendingOrder);
+}
 
+QString QgsDbSourceSelect::makeGeomQuery(QString schema, 
+                                                QString table, QString column)
+{
+  return QString("select distinct "
+		  "case"
+		  " when geometrytype(%1) IN ('POINT','MULTIPOINT') THEN 'POINT'"
+		  " when geometrytype(%1) IN ('LINESTRING','MULTILINESTRING') THEN 'LINESTRING'"
+		  " when geometrytype(%1) IN ('POLYGON','MULTIPOLYGON') THEN 'POLYGON'"
+		  " end "
+		  "from \"%2\".\"%3\"").arg(column).arg(schema).arg(table);
+}
 
 QgsDbSourceSelect::~QgsDbSourceSelect()
 {
-    delete mConnMan;                                   
     PQfinish(pd);
 }
 void QgsDbSourceSelect::populateConnectionList(QString type)
 {
-  qDebug("QgsDbSourceSelect::populateConnectionList : type "+type);   
+  /*QSettings settings;
+  QStringList keys = settings.subkeyList("/PostgreSQL/connections");
+  QStringList::Iterator it = keys.begin();
+  cmbConnections->clear();
+  while (it != keys.end())
+  {
+    cmbConnections->insertItem(*it);
+    ++it;
+  }
   
-  QStringList connlist=mConnMan->getConnections(type);
+  setConnectionListPosition();*/
+  qDebug("solo para checar");
+  QStringList connlist=mConnectionRegistry->connectionParametersList(type);
   cmbConnections->clear();
   //add the results to combo
   for (int i = 0; i < connlist.size(); ++i)
      cmbConnections->addItem(connlist.at(i));
-  cmbType->setCurrentIndex(cmbType->findText(type)); 
+  cmbType->setCurrentIndex(cmbType->findText(type));
 }
 void QgsDbSourceSelect::addNewConnection()
 {
-  QgsNewConnection *nc = new QgsNewConnection(this);
+  /*QgsNewConnection *nc = new QgsNewConnection(this);
 
   if (nc->exec())
   {
-    populateConnectionList(cmbType->currentText());
-  }
+    populateConnectionList();
+  }*/
+  QString type=cmbType->currentText();   
+  if (type.contains("OgrGeneric"))
+   {
+     QgsNewOgrGenericConnection *noc = new QgsNewOgrGenericConnection(this);
+     if (noc->exec())
+      {
+        populateConnectionList(cmbType->currentText());
+      }
+   }
+  else
+   {   
+     QgsNewConnection *nc = new QgsNewConnection(this);
+     if (nc->exec())
+      {
+        populateConnectionList(cmbType->currentText());
+      }
+   }  
 }
 void QgsDbSourceSelect::editConnection()
 {
-  QgsConnection conn=mConnMan->getConnectionDetails(cmbType->currentText(),cmbConnections->currentText());
-  QgsNewConnection *nc = new QgsNewConnection(this, &conn);
 
+  /*QgsNewConnection *nc = new QgsNewConnection(this, cmbConnections->currentText());
+
   if (nc->exec())
   {
     nc->saveConnection();
-    populateConnectionList(cmbType->currentText());
-  }
+  }*/
+  QString type=cmbType->currentText();  
+   QgsConnectionParameters conn=mConnectionRegistry->connectionParameters(type,cmbConnections->currentText());
+   if (type.contains("OgrGeneric"))
+   {
+     QgsNewOgrGenericConnection *noc = new QgsNewOgrGenericConnection(this,&conn);
+     if (noc->exec())
+      {
+        noc->saveConnection();             
+        populateConnectionList(cmbType->currentText());
+      }
+   }
+  else
+   {   
+     QgsNewConnection *nc = new QgsNewConnection(this,&conn);
+     if (nc->exec())
+      {
+        nc->saveConnection();            
+        populateConnectionList(cmbType->currentText());
+      }
+   }  
 }
 
 void QgsDbSourceSelect::deleteConnection()
 {
-   mConnMan->removeConnection(cmbType->currentText(),cmbConnections->currentText());   
-   populateConnectionList(cmbType->currentText());
-
+  QSettings settings;
+  QString key = "/Postgresql/connections/" + cmbConnections->currentText();
+  QString msg =
+    tr("Are you sure you want to remove the ") + cmbConnections->currentText() + tr(" connection and all associated settings?");
+  QMessageBox::StandardButton result = QMessageBox::information(this, tr("Confirm Delete"), msg, QMessageBox::Ok | QMessageBox::Cancel);
+  if (result == QMessageBox::Ok)
+  {
+    settings.removeEntry(key + "/host");
+    settings.removeEntry(key + "/database");
+    settings.removeEntry(key + "/username");
+    settings.removeEntry(key + "/password");
+    settings.removeEntry(key + "/port");
+    settings.removeEntry(key + "/save");
+    settings.removeEntry(key);
+    //if(!success){
+    //  QMessageBox::information(this,"Unable to Remove","Unable to remove the connection " + cmbConnections->currentText());
+    //}
+    cmbConnections->removeItem(cmbConnections->currentItem());  // populateConnectionList();
+    setConnectionListPosition();
+  }
 }
 void QgsDbSourceSelect::addTables()
 {
-  QString type=cmbType->currentText();
+  m_selectedTables.clear();
+
+  typedef QMap<int, QVector<QString> > schemaInfo;
+  QMap<QString, schemaInfo> dbInfo;
+
+  QItemSelection selection = mTablesTreeView->selectionModel()->selection();
+  QModelIndexList selectedIndices = selection.indexes();
+  QStandardItem* currentItem = 0;
+
+  QModelIndexList::const_iterator selected_it = selectedIndices.constBegin();
+  for(; selected_it != selectedIndices.constEnd(); ++selected_it)
+    {
+      if(!selected_it->parent().isValid())
+	{
+	  //top level items only contain the schema names
+	  continue;
+	}
+      currentItem = mTableModel.itemFromIndex(mProxyModel.mapToSource(*selected_it));
+      if(!currentItem)
+	{
+	  continue;
+	}
+      
+      QString currentSchemaName = currentItem->parent()->text();
+      
+      int currentRow = currentItem->row();
+      int currentColumn = currentItem->column();
+
+      if(dbInfo[currentSchemaName][currentRow].size() == 0)
+	{
+	  dbInfo[currentSchemaName][currentRow].resize(5);
+	}
+
+      dbInfo[currentSchemaName][currentRow][currentColumn] = currentItem->text();
+    }
   
-  //store the table info
+  //now traverse all the schemas and table infos
+  QString schemaName, tableName, geomColumnName, sql;
+  QString query;
 
-  for (int i = 0; i < lstTables->rowCount(); ++i)
-  {
-    if (lstTables->isItemSelected(lstTables->item(i, 0)))
+  QMap<QString, schemaInfo>::const_iterator schema_it = dbInfo.constBegin();
+  for(; schema_it != dbInfo.constEnd(); ++schema_it)
     {
-      QString table;                                               
-      //if(type.contains("Ogr",FALSE)>0)
-      // table = lstTables->item(i,1)->text(); 
-      //else 
-      // {                                              
-         table = lstTables->item(i,1)->text() + " sql=";
-         QTableWidgetItem* sqlItem = lstTables->item(i,2);
-         if (sqlItem)
-          table += sqlItem->text();
-      // }   
-      m_selectedTables += table;
+      schemaInfo scheme = schema_it.value();
+      schemaInfo::const_iterator entry_it = scheme.constBegin();
+      for(; entry_it != scheme.constEnd(); ++entry_it)
+	{
+	  schemaName = entry_it->at(0);
+	  tableName = entry_it->at(1);
+	  geomColumnName = entry_it->at(3);
+	  sql = entry_it->at(4);
+	 
+	  if(geomColumnName.contains(" AS "))
+	    {
+	      int a = geomColumnName.find(" AS ");
+	      QString typeName = geomColumnName.mid(a+4); //only the type name
+	      geomColumnName = geomColumnName.mid(0, a); //only the geom column name
+ 
+	      if(!sql.isEmpty())
+		{
+		  sql += " AND ";
+		}
+	      if( typeName=="POINT" ) 
+		{
+		  sql += QString("GeometryType(\"%1\") IN ('POINT','MULTIPOINT')").arg(geomColumnName);
+		} 
+	      else if(typeName=="LINESTRING") 
+		{
+		  sql += QString("GeometryType(\"%1\") IN ('LINESTRING','MULTILINESTRING')").arg(geomColumnName);
+		} 
+	      else if(typeName=="POLYGON") 
+		{
+		  sql += QString("GeometryType(\"%1\") IN ('POLYGON','MULTIPOLYGON')").arg(geomColumnName);
+		} 
+	      else 
+		{
+		  continue;
+		}
+	    }
+	  query = "\"" + schemaName + "\".\"" + tableName + "\" " + "(" + geomColumnName + ") sql=" + sql;
+	  m_selectedTables.push_back(query);
+	}
     }
-  }
 
-  // BEGIN CHANGES ECOS
-  if (m_selectedTables.empty() == true)
-    QMessageBox::information(this, tr("Select Table"), tr("You must select a table in order to add a Layer."));
+  if(m_selectedTables.empty())
+    {
+      QMessageBox::information(this, tr("Select Table"), tr("You must select a table in order to add a Layer."));
+    }
   else
-    accept();
-  // END CHANGES ECOS
-  
-  
+    {
+      accept();
+    }
 }
 
 void QgsDbSourceSelect::on_btnConnect_clicked()
 {
-  qDebug("QgsDbSourceSelect::on_btnConnect_clicked");   
-  QgsConnection conn=mConnMan->getConnectionDetails(cmbType->currentText(),cmbConnections->currentText());   
+  disconnect();   
+  QModelIndex rootItemIndex = mTableModel.indexFromItem(mTableModel.invisibleRootItem());
+  mTableModel.removeRows(0, mTableModel.rowCount(rootItemIndex), rootItemIndex);   
+  QgsConnectionParameters conn=mConnectionRegistry->connectionParameters(cmbType->currentText(),cmbConnections->currentText());
+  
+  
+  
   bool makeConnection=true;
   if (conn.password == QString::null)
       {
@@ -314,106 +452,173 @@
        conn.password=password;
        }   
  
-   
-  if (mConnMan->connect(cmbType->currentText(),conn))
+  bool searchPublicOnly = conn.publicOnly;
+  bool searchGeometryColumnsOnly = conn.geometryColumnsOnly;
+  
+  QgsDataSourceURI uri;
+  uri.setConnection(conn.type, 
+                    conn.host,
+		            conn.port,
+		            conn.database,
+		            conn.user,
+		            conn.password );
+
+  if (makeConnection)
+  {
+    m_connInfo = uri.connInfo();
+    QString type=cmbType->currentText();    
+    if (type.startsWith("Ogr"))
+      {
+        mDatabaseConnection= new QgsOgrDatabaseConnection(&conn); 
+      }
+    else
+      {
+        mDatabaseConnection= new QgsPostgresDatabaseConnection(&conn);                      
+      }  
+    if (mDatabaseConnection->connect())  
+      {
+        //load geometry tables to view                                 
+        //qDebug("Unable to get list of spatially enabled tables from the database");
+        //qDebug(PQerrorMessage(pd));
+      }
+    else
+      {
+          QMessageBox::warning(this, tr("Connection failed"),
+          tr
+          ("Connection to %1 on %2 failed. Either the database is down or your settings are incorrect.%3Check your username and password and try again.%4The database said:%5%6").
+          arg(conn.database).arg(conn.host).arg("\n\n").arg("\n\n").arg("\n").arg(mDatabaseConnection->error()));
+      }                                    
+         
+  
+      if (cmbConnections->count() > 0)
+        btnAdd->setEnabled(true);
+      }
+  
+
+  mTablesTreeView->sortByColumn(1, Qt::AscendingOrder);
+  mTablesTreeView->sortByColumn(0, Qt::AscendingOrder);
+
+  //if we have only one schema item, expand it by default
+  int numTopLevelItems = mTableModel.invisibleRootItem()->rowCount();
+  if(numTopLevelItems < 2 || mTableModel.tableCount() < 20)
     {
-      // Database successfully opened; we can now issue SQL commands.
-      // create the pixmaps for the layer types if we haven't already
-      // done so.
-      m_connInfo="type="+conn.type
-                +" host="+conn.host
-                +" dbname="+conn.database
-                +" port="+conn.port
-                +" user="+conn.user
-                +" password='"+conn.password+"'"; 
-                
-     if (mLayerIcons.count() == 0)
-       {
-         QString myThemePath = QgsApplication::themePath();
-                mLayerIcons.insert("POINT",
-                                    qMakePair(tr("Point layer"), 
-                                    QIcon(myThemePath+"/mIconPointLayer.png")));
-                mLayerIcons.insert("MULTIPOINT", 
-                                   qMakePair(tr("Multi-point layer"), 
-                                   mLayerIcons.value("POINT").second));
+      //expand all the toplevel items
+      for(int i = 0; i < numTopLevelItems; ++i)
+	{
+	  mTablesTreeView->expand(mProxyModel.mapFromSource(mTableModel.indexFromItem(mTableModel.invisibleRootItem()->child(i))));
+	}
+    }    
+       
+  //**********************************************   
+  /*if(mColumnTypeThread)
+  {
+    mColumnTypeThread->stop();
+    mColumnTypeThread=0;
+  }
 
-                mLayerIcons.insert("LINESTRING",
-                                   qMakePair(tr("Linestring layer"), 
-                                   QIcon(myThemePath+"/mIconLineLayer.png")));
-                mLayerIcons.insert("MULTILINESTRING",
-                                   qMakePair(tr("Multi-linestring layer"), 
-                                   mLayerIcons.value("LINESTRING").second));
+  QModelIndex rootItemIndex = mTableModel.indexFromItem(mTableModel.invisibleRootItem());
+  mTableModel.removeRows(0, mTableModel.rowCount(rootItemIndex), rootItemIndex);
 
-                mLayerIcons.insert("POLYGON",
-                                   qMakePair(tr("Polygon layer"), 
-                                   QIcon(myThemePath+"/mIconPolygonLayer.png")));
-                mLayerIcons.insert("MULTIPOLYGON",
-                                   qMakePair(tr("Multi-polygon layer"),
-                                   mLayerIcons.value("POLYGON").second));
+  // populate the table list
+  QSettings settings;
 
-                mLayerIcons.insert("GEOMETRY",
-                                   qMakePair(tr("Mixed geometry layer"), 
-                                   QIcon(myThemePath+"/mIconGeometryLayer.png")));
-                mLayerIcons.insert("GEOMETRYCOLLECTION",
-                                   qMakePair(tr("Geometry collection layer"), 
-                                   mLayerIcons.value("GEOMETRY").second));
+  bool makeConnection = true;
+  QString key = "/PostgreSQL/connections/" + cmbConnections->currentText();
 
-                mLayerIcons.insert("WAITING",
-                                   qMakePair(tr("Waiting for layer type"), 
-                                   QIcon(myThemePath+"/mIconWaitingForLayerType.png")));
-                mLayerIcons.insert("UNKNOWN",
-                                   qMakePair(tr("Unknown layer type"), 
-                                   QIcon(myThemePath+"/mIconUnknownLayerType.png")));
-       }                          
-       lstTables->clear();
-       lstTables->setRowCount(0);
-       lstTables->setHorizontalHeaderLabels(mColumnLabels);
+  QString database = settings.readEntry(key + "/database");
+  QString username = settings.readEntry(key + "/username");
+  QString password = settings.readEntry(key + "/password");
 
-       QStringList tables=mConnMan->getConnection()->getGeometryTables();
-       for (int i = 0; i < tables.size(); ++i)
-        { 
-            QString toolTipText;
-            const QIcon* p;      
-            QString geometryType=mConnMan->getConnection()->getTableGeometry(tables.at(i));      
-            if (mLayerIcons.contains(geometryType))
-             {
-               p = &(mLayerIcons.value(geometryType).second);
-               toolTipText = mLayerIcons.value(geometryType).first;
-               qDebug(geometryType); 
-             }
-            else
-             {
-	          qDebug(("Unknown geometry type of '" + geometryType + "'.").toLocal8Bit().data());
-              p = &(mLayerIcons.value("UNKNOWN").second);
-              toolTipText = mLayerIcons.value("UNKNOWN").first;
-             } 
-            if (p != 0)
-             {
-              QTableWidgetItem *iconItem = new QTableWidgetItem();
-              iconItem->setIcon(*p);
-              iconItem->setToolTip(toolTipText);
-              QTableWidgetItem *textItem = new QTableWidgetItem(tables.at(i));
-              int row = lstTables->rowCount();
-              lstTables->setRowCount(row+1);
-              lstTables->setItem(row, 0, iconItem);
-              lstTables->setItem(row, 1, textItem);
-             }
+  if (password == QString::null)
+  {
+    // get password from user 
+    makeConnection = false;
+    QString password = QInputDialog::getText(tr("Password for ") + username,
+        tr("Please enter your password:"),
+        QLineEdit::Password, QString::null, &makeConnection, this);
+    // allow null password entry in case its valid for the database
+  }
+
+  QgsDataSourceURI uri;
+  uri.setConnection( settings.readEntry(key + "/host"),
+		     settings.readEntry(key + "/port"),
+		     database,
+		     settings.readEntry(key + "/username"),
+		     password );
+
+  bool searchPublicOnly = settings.readBoolEntry(key + "/publicOnly");
+  bool searchGeometryColumnsOnly = settings.readBoolEntry(key + "/geometryColumnsOnly");
+
+  // Need to escape the password to allow for single quotes and backslashes
+
+  QgsDebugMsg("Connection info: " + uri.connInfo());
+
+  if (makeConnection)
+  {
+    m_connInfo = uri.connInfo();
+    //qDebug(m_connInfo);
+    // Tidy up an existing connection if one exists.
+    if (pd != 0)
+      PQfinish(pd);
+
+    pd = PQconnectdb(m_connInfo.toLocal8Bit().data());
+    //  std::cout << pd->ErrorMessage();
+    if (PQstatus(pd) == CONNECTION_OK)
+    {
+      //qDebug("Connection succeeded");
+      // tell the DB that we want text encoded in UTF8
+      PQsetClientEncoding(pd, "UNICODE");
+
+      // get the list of suitable tables and columns and populate the UI
+      geomCol details;
+
+      if(getTableInfo(pd, searchGeometryColumnsOnly, searchPublicOnly))	
+      {
+        // Start the thread that gets the geometry type for relations that
+        // may take a long time to return
+        if (mColumnTypeThread != NULL)
+        {
+           connect(mColumnTypeThread, SIGNAL(setLayerType(QString,QString,QString,QString)),
+                   this, SLOT(setLayerType(QString,QString,QString,QString)));
+	   connect(this, SIGNAL(finished()),
+	           mColumnTypeThread, SLOT(stop()) );
+
+            // Do it in a thread.
+            mColumnTypeThread->start();
         }
-        
+      }
+      else
+      {
+        qDebug("Unable to get list of spatially enabled tables from the database");
+        qDebug(PQerrorMessage(pd));
+      }
+      // BEGIN CHANGES ECOS
+      if (cmbConnections->count() > 0)
+        btnAdd->setEnabled(true);
+      // END CHANGES ECOS
+    }
+    else
+    {
+      QMessageBox::warning(this, tr("Connection failed"),
+          tr
+          ("Connection to %1 on %2 failed. Either the database is down or your settings are incorrect.%3Check your username and password and try again.%4The database said:%5%6").
+          arg(settings.readEntry(key + "/database")).arg(settings.readEntry(key + "/host")).arg("\n\n").arg("\n\n").arg("\n").arg(PQerrorMessage(pd)));
+    }
+  }
 
-        // And tidy up the columns & rows
-        lstTables->resizeColumnsToContents();
-        lstTables->resizeRowsToContents();
-                    
-      
-    } else
+  mTablesTreeView->sortByColumn(1, Qt::AscendingOrder);
+  mTablesTreeView->sortByColumn(0, Qt::AscendingOrder);
+
+  //if we have only one schema item, expand it by default
+  int numTopLevelItems = mTableModel.invisibleRootItem()->rowCount();
+  if(numTopLevelItems < 2 || mTableModel.tableCount() < 20)
     {
-     QMessageBox::information(this, tr("Connection"), tr("Connection failed - Check settings and try again.\n\nExtended error information:\n") +mConnMan->getError());
-    }
-    
-    if (cmbConnections->count() > 0)
-        btnAdd->setEnabled(true);
-  
+      //expand all the toplevel items
+      for(int i = 0; i < numTopLevelItems; ++i)
+	{
+	  mTablesTreeView->expand(mProxyModel.mapFromSource(mTableModel.indexFromItem(mTableModel.invisibleRootItem()->child(i))));
+	}
+    }*/
 }
 
 QStringList QgsDbSourceSelect::selectedTables()
@@ -421,68 +626,296 @@
   return m_selectedTables;
 }
 
+QString QgsDbSourceSelect::connInfo()
+{
+  return m_connInfo;
+}
 
-void QgsDbSourceSelect::setSql(QTableWidgetItem *item)
+void QgsDbSourceSelect::setSql(const QModelIndex& index)
 {
-/*  int row = lstTables->row(item);
-  QString tableText = lstTables->item(row, 1)->text();
+  if(!index.parent().isValid())
+    {
+      qWarning("schema item found");
+      return;
+    }
 
-  QTableWidgetItem* sqlItem = lstTables->item(row, 2);
-  QString sqlText;
-  if (sqlItem)
-    sqlText = sqlItem->text();
-  // Parse out the table name
-  QString table = tableText.left(tableText.find("(")); */
-  /*assert(pd != 0);
+  if(pd == 0)
+    {
+      return;
+    }
+  
+  //create "Schema"."Table" and find out existing sql string
+  QModelIndex schemaSibling = index.sibling(index.row(), 0);
+  QModelIndex tableSibling = index.sibling(index.row(), 1);
+  if(!schemaSibling.isValid() || !tableSibling.isValid())
+    {
+      return;
+    }
+
+  QString schemaName = mTableModel.itemFromIndex(mProxyModel.mapToSource(schemaSibling))->text();
+  QString tableName = mTableModel.itemFromIndex(mProxyModel.mapToSource(tableSibling))->text(); 
+  QString tableString = "\"" + schemaName + "\".\"" + tableName + "\"";
+  qWarning(tableString);
+
+  QString currentSql;
+  QModelIndex sqlSibling = index.sibling(index.row(), 4);
+  if(sqlSibling.isValid())
+    {
+      currentSql = mTableModel.itemFromIndex(mProxyModel.mapToSource(sqlSibling))->text();
+    }
+
   // create a query builder object
-  QgsPgQueryBuilder * pgb = new QgsPgQueryBuilder(table, pd, this);
+  QgsPgQueryBuilder * pgb = new QgsPgQueryBuilder(tableString, pd, this); 
   // set the current sql in the query builder sql box
-  pgb->setSql(sqlText);
+  pgb->setSql(currentSql);
   // set the PG connection object so it can be used to fetch the
   // fields for the table, get sample values, and test the query
   pgb->setConnection(pd);
   // show the dialog
   if(pgb->exec())
   {
-    // if user accepts, store the sql for the layer so it can be used
-    // if and when the layer is added to the map
-    if (!sqlItem)
+    mTableModel.setSql(mProxyModel.mapToSource(index), pgb->sql());
+  }
+}
+
+void QgsDbSourceSelect::addSearchGeometryColumn(const QString &schema, const QString &table, const QString &column)
+{
+  // store the column details and do the query in a thread
+ /* if (mColumnTypeThread == NULL)
+  {
+    mColumnTypeThread = new QgsGeomColumnTypeThread();
+    mColumnTypeThread->setConnInfo(m_connInfo);
+  }
+  mColumnTypeThread->addGeometryColumn(schema, table, column);*/
+}
+
+bool QgsDbSourceSelect::getTableInfo(PGconn *pg, bool searchGeometryColumnsOnly, bool searchPublicOnly)
+{
+ /* bool ok = false;
+  QApplication::setOverrideCursor(Qt::waitCursor);
+  
+  QString sql = "select * from geometry_columns";
+  sql += " order by f_table_schema,f_table_name";
+
+  PGresult *result = PQexec(pg, sql.toLocal8Bit().data());
+  if (result)
+  {
+    for (int idx = 0; idx < PQntuples(result); idx++)
     {
-      sqlItem = new QTableWidgetItem();
-      lstTables->setItem(row, 2, sqlItem);
+      // Be a bit paranoid and check that the table actually
+      // exists. This is not done as a subquery in the query above
+      // because I can't get it to work correctly when there are tables
+      // with capital letters in the name.
+
+      // Take care to deal with tables with the same name but in different schema.
+      QString tableName = PQgetvalue(result, idx, PQfnumber(result, "f_table_name"));
+      QString schemaName = PQgetvalue(result, idx, PQfnumber(result, "f_table_schema"));
+      sql = "select oid from pg_class where relname = '" + tableName + "'";
+      if (schemaName.length() > 0)
+	sql +=" and relnamespace = (select oid from pg_namespace where nspname = '" +
+	  schemaName + "')";
+
+      PGresult* exists = PQexec(pg, sql.toLocal8Bit().data());
+      if (PQntuples(exists) == 1)
+      {
+        QString column = PQgetvalue(result, idx, PQfnumber(result, "f_geometry_column"));
+        QString type = PQgetvalue(result, idx, PQfnumber(result, "type"));
+        
+	QString as = "";
+	if(type=="GEOMETRY" && !searchGeometryColumnsOnly) 
+	  {
+	    addSearchGeometryColumn(schemaName, tableName,  column);
+	    as=type="WAITING";
+	  }
+
+	mTableModel.addTableEntry(type, schemaName, tableName, column, "");
+      }
+      PQclear(exists);
     }
-    sqlItem->setText(pgb->sql());
-    // Ensure that the current row remains selected
-    lstTables->setItemSelected(lstTables->item(row,0), true);
-    lstTables->setItemSelected(lstTables->item(row,1), true);
-    lstTables->setItemSelected(lstTables->item(row,2), true);
+    ok = true;
   }
-  // delete the query builder object
-  delete pgb;*/
+  PQclear(result);
+
+  //search for geometry columns in tables that are not in the geometry_columns metatable
+  
+
+  QApplication::restoreOverrideCursor();
+  if (searchGeometryColumnsOnly)
+    {
+      return ok;
+    }
+
+   // Now have a look for geometry columns that aren't in the
+  // geometry_columns table. This code is specific to postgresql,
+  // but an equivalent query should be possible in other
+  // databases.
+  sql = "select pg_class.relname, pg_namespace.nspname, pg_attribute.attname, "
+    "pg_class.relkind from "
+    "pg_attribute, pg_class, pg_type, pg_namespace where pg_type.typname = 'geometry' and "
+    "pg_attribute.atttypid = pg_type.oid and pg_attribute.attrelid = pg_class.oid ";
+
+  if (searchPublicOnly)
+    sql += "and pg_namespace.nspname = 'public' ";
+
+  sql += "and cast(pg_class.relname as character varying) not in "
+    "(select f_table_name from geometry_columns) "
+    "and pg_namespace.oid = pg_class.relnamespace "
+    "and pg_class.relkind in ('v', 'r')"; // only from views and relations (tables)
+  
+  result = PQexec(pg, sql.toLocal8Bit().data());
+
+  for (int i = 0; i < PQntuples(result); i++)
+  {
+    // Have the column name, schema name and the table name. The concept of a
+    // catalog doesn't exist in postgresql so we ignore that, but we
+    // do need to get the geometry type.
+
+    // Make the assumption that the geometry type for the first
+    // row is the same as for all other rows. 
+
+    QString table  = PQgetvalue(result, i, 0); // relname
+    QString schema = PQgetvalue(result, i, 1); // nspname
+    QString column = PQgetvalue(result, i, 2); // attname
+    QString relkind = PQgetvalue(result, i, 3); // relation kind
+
+    addSearchGeometryColumn(schema, table, column);
+    //details.push_back(geomPair(fullDescription(schema, table, column, "WAITING"), "WAITING"));
+    mTableModel.addTableEntry("Waiting", schema, table, column, "");
+  }
+  ok = true;
+
+  PQclear(result);
+  return ok;*/
+  return true;
 }
 
+bool QgsDbSourceSelect::getGeometryColumnInfo(PGconn *pg, 
+                geomCol& details, bool searchGeometryColumnsOnly,
+                                              bool searchPublicOnly)
+{
+ /* bool ok = false;
 
-QString QgsDbSourceSelect::encoding()
-{
-  return mEncodingComboBox->currentText();
+  QApplication::setOverrideCursor(Qt::waitCursor);
+
+  QString sql = "select * from geometry_columns";
+  // where f_table_schema ='" + settings.readEntry(key + "/database") + "'";
+  sql += " order by f_table_schema,f_table_name";
+  //qDebug("Fetching tables using: " + sql);
+  PGresult *result = PQexec(pg, sql.toLocal8Bit().data());
+  if (result)
+  {
+    QString msg;
+    QTextOStream(&msg) << "Fetched " << PQntuples(result) << " tables from database";
+    //qDebug(msg);
+    for (int idx = 0; idx < PQntuples(result); idx++)
+    {
+      // Be a bit paranoid and check that the table actually
+      // exists. This is not done as a subquery in the query above
+      // because I can't get it to work correctly when there are tables
+      // with capital letters in the name.
+
+      // Take care to deal with tables with the same name but in different schema.
+      QString tableName = PQgetvalue(result, idx, PQfnumber(result, "f_table_name"));
+      QString schemaName = PQgetvalue(result, idx, PQfnumber(result, "f_table_schema"));
+      sql = "select oid from pg_class where relname = '" + tableName + "'";
+      if (schemaName.length() > 0)
+	sql +=" and relnamespace = (select oid from pg_namespace where nspname = '" +
+	  schemaName + "')";
+
+      PGresult* exists = PQexec(pg, sql.toLocal8Bit().data());
+      if (PQntuples(exists) == 1)
+      {
+        QString column = PQgetvalue(result, idx, PQfnumber(result, "f_geometry_column"));
+        QString type = PQgetvalue(result, idx, PQfnumber(result, "type"));
+        
+	QString as = "";
+	if(type=="GEOMETRY" && !searchGeometryColumnsOnly) {
+	  addSearchGeometryColumn(schemaName, tableName,  column);
+	  as=type="WAITING";
+	}
+
+	details.push_back(geomPair(fullDescription(schemaName, tableName, column, as), type));
+      }
+      PQclear(exists);
+    }
+    ok = true;
+  }
+  PQclear(result);
+
+  QApplication::restoreOverrideCursor();
+
+  if (searchGeometryColumnsOnly)
+    return ok;
+
+  // Now have a look for geometry columns that aren't in the
+  // geometry_columns table. This code is specific to postgresql,
+  // but an equivalent query should be possible in other
+  // databases.
+  sql = "select pg_class.relname, pg_namespace.nspname, pg_attribute.attname, "
+    "pg_class.relkind from "
+    "pg_attribute, pg_class, pg_type, pg_namespace where pg_type.typname = 'geometry' and "
+    "pg_attribute.atttypid = pg_type.oid and pg_attribute.attrelid = pg_class.oid ";
+
+  if (searchPublicOnly)
+    sql += "and pg_namespace.nspname = 'public' ";
+
+  sql += "and cast(pg_class.relname as character varying) not in "
+    "(select f_table_name from geometry_columns) "
+    "and pg_namespace.oid = pg_class.relnamespace "
+    "and pg_class.relkind in ('v', 'r')"; // only from views and relations (tables)
+  
+  result = PQexec(pg, sql.toLocal8Bit().data());
+
+  for (int i = 0; i < PQntuples(result); i++)
+  {
+    // Have the column name, schema name and the table name. The concept of a
+    // catalog doesn't exist in postgresql so we ignore that, but we
+    // do need to get the geometry type.
+
+    // Make the assumption that the geometry type for the first
+    // row is the same as for all other rows. 
+
+    QString table  = PQgetvalue(result, i, 0); // relname
+    QString schema = PQgetvalue(result, i, 1); // nspname
+    QString column = PQgetvalue(result, i, 2); // attname
+    QString relkind = PQgetvalue(result, i, 3); // relation kind
+
+    addSearchGeometryColumn(schema, table, column);
+    details.push_back(geomPair(fullDescription(schema, table, column, "WAITING"), "WAITING"));
+  }
+  ok = true;
+
+  PQclear(result);
+
+  return ok;*/
+  return true;
 }
+
 void QgsDbSourceSelect::showHelp()
 {
   QgsContextHelp::run(context_id);
 }
-
+QString QgsDbSourceSelect::fullDescription(QString schema, QString table, 
+					   QString column, QString type)
+{
+  QString full_desc = "";
+  if (schema.length() > 0)
+    full_desc = '"' + schema + "\".\"";
+  full_desc += table + "\" (" + column + ") " + type;
+  return full_desc;
+}
 void QgsDbSourceSelect::dbChanged()
 {
   // Remember which database was selected.
-  mConnMan->setSelectedType(cmbType->currentText());
-  mConnMan->setSelected(cmbType->currentText(),cmbConnections->currentText());
-  qDebug("Saving last connection position");
+  QSettings settings;
+  settings.writeEntry("/PostgreSQL/connections/selected", 
+		      cmbConnections->currentText());
 }
 
 void QgsDbSourceSelect::setConnectionListPosition()
 {
-  qDebug("Setting connection list position"); 
-  QString toSelect = mConnMan->getSelected(cmbType->currentText());
+  
+  QString toSelect = mConnectionRegistry->selected(cmbType->currentText());
   // Does toSelect exist in cmbConnections?
   bool set = false;
   for (int i = 0; i < cmbConnections->count(); ++i)
@@ -507,10 +940,95 @@
     else
       cmbConnections->setCurrentItem(cmbConnections->count()-1);
   }
+  /*QSettings settings;
+  // If possible, set the item currently displayed database
+  QString toSelect = settings.readEntry("/PostgreSQL/connections/selected");
+  // Does toSelect exist in cmbConnections?
+  bool set = false;
+  for (int i = 0; i < cmbConnections->count(); ++i)
+    if (cmbConnections->text(i) == toSelect)
+    {
+      cmbConnections->setCurrentItem(i);
+      set = true;
+      break;
+    }
+  // If we couldn't find the stored item, but there are some, 
+  // default to the last item (this makes some sense when deleting
+  // items as it allows the user to repeatidly click on delete to
+  // remove a whole lot of items).
+  if (!set && cmbConnections->count() > 0)
+  {
+    // If toSelect is null, then the selected connection wasn't found
+    // by QSettings, which probably means that this is the first time
+    // the user has used qgis with database connections, so default to
+    // the first in the list of connetions. Otherwise default to the last.
+    if (toSelect.isNull())
+      cmbConnections->setCurrentItem(0);
+    else
+      cmbConnections->setCurrentItem(cmbConnections->count()-1);
+  }*/
 }
 
+void QgsDbSourceSelect::setSearchExpression(const QString& regexp)
+{
+  
+}
 
-QString QgsDbSourceSelect::connInfo()
+/*
+void QgsGeomColumnTypeThread::setConnInfo(QString s)
 {
-  return m_connInfo;
+  mConnInfo = s;
 }
+
+void QgsGeomColumnTypeThread::addGeometryColumn(QString schema, QString table, QString column)
+{
+  schemas.push_back(schema);
+  tables.push_back(table);
+  columns.push_back(column);
+}
+
+void QgsGeomColumnTypeThread::stop()
+{
+  mStopped=true;
+}
+
+void QgsGeomColumnTypeThread::getLayerTypes()
+{
+  mStopped=false;
+
+  PGconn *pd = PQconnectdb(mConnInfo.toLocal8Bit().data());
+  if (PQstatus(pd) == CONNECTION_OK)
+  {
+    PQsetClientEncoding(pd, "UNICODE");
+
+    for (uint i = 0; i<schemas.size(); i++)
+    {
+      QString query = QgsDbSourceSelect::makeGeomQuery(schemas[i],
+                                                       tables[i],
+                                                       columns[i]);
+      PGresult* gresult = PQexec(pd, query.toLocal8Bit().data());
+      QString type;
+      if (PQresultStatus(gresult) == PGRES_TUPLES_OK) {
+	QStringList types;
+
+	for(int j=0; j<PQntuples(gresult); j++) {
+		QString type = PQgetvalue(gresult, j, 0);
+		if(type!="")
+		  types += type;
+	}
+
+	type = types.join(",");
+      }
+      PQclear(gresult);
+
+      if(mStopped)
+        break;
+
+      // Now tell the layer list dialog box...
+      emit setLayerType(schemas[i], tables[i], columns[i], type);
+    }
+  }
+
+  PQfinish(pd);
+}
+*/

Modified: branches/ogr-plugin-branch/src/app/qgsdbsourceselect.h
===================================================================
--- branches/ogr-plugin-branch/src/app/qgsdbsourceselect.h	2008-02-14 19:16:45 UTC (rev 8159)
+++ branches/ogr-plugin-branch/src/app/qgsdbsourceselect.h	2008-02-15 21:20:17 UTC (rev 8160)
@@ -18,8 +18,12 @@
 #ifndef QGSDBSOURCESELECT_H
 #define QGSDBSOURCESELECT_H
 #include "ui_qgsdbsourceselectbase.h"
+#include "qgsconnectionregistry.h"
+#include "qgsdatabaseconnection.h"
 #include "qgisgui.h"
-#include "qgsconnectionmanager.h"
+#include "qgsdbfilterproxymodel.h"
+#include "qgsdbtablemodel.h"
+
 extern "C"
 {
 #include <libpq-fe.h>
@@ -43,12 +47,12 @@
  * \brief Dialog to create connections and add tables from PostgresQL.
  *
  * This dialog allows the user to define and save connection information
- * for PostGIS enabled PostgresQL databases. The user can then connect and add 
+ * for PostGIS enabled PostgreSQL databases. The user can then connect and add 
  * tables from the database to the map canvas.
  */
 class QgsDbSourceSelect : public QDialog, private Ui::QgsDbSourceSelectBase 
 {
-  Q_OBJECT
+ Q_OBJECT
  public:
 
     //! Constructor
@@ -61,20 +65,20 @@
     void editConnection();
     //! Deletes the selected connection
     void deleteConnection();
-   
+     
     //! Determines the tables the user selected and closes the dialog
     void addTables();
     //! String list containing the selected tables
     QStringList selectedTables();
     //! Connection info (database, host, user, password)
     QString connInfo();
-    QStringList m_selectedTables;
-    //! Return the name of the selected encoding (e.g. UTf-8, ISO-8559-1, etc/)
-    QString encoding();
     // Store the selected database
     void dbChanged();
-    
-    public slots:
+    // Utility function to construct the query for finding out the
+    // geometry type of a column
+    static QString makeGeomQuery(QString schema, QString table, QString column);
+
+ public slots:
     /*! Connects to the database using the stored connection parameters. 
     * Once connected, available layers are displayed.
     */
@@ -83,17 +87,26 @@
       void on_btnNew_clicked();
       void on_btnEdit_clicked();
       void on_btnDelete_clicked();
-      void on_lstTables_itemDoubleClicked(QTableWidgetItem *);
-      void setSql(QTableWidgetItem *);
+      void on_mSearchOptionsButton_clicked();
+      void on_mSearchTableEdit_textChanged(const QString & text);
+      void on_mSearchColumnComboBox_currentIndexChanged(const QString & text);
+      void on_mSearchModeComboBox_currentIndexChanged(const QString & text);
+      void setSql(const QModelIndex& index);
       void on_btnHelp_clicked();
-      void on_cmbType_activated(int);
       void on_cmbConnections_activated(int);
       void setLayerType(QString schema, QString table, QString column,
                         QString type);
+      //!Sets a new regular expression to the model
+      void setSearchExpression(const QString& regexp);
       //! Populate the connection list combo box
-      void populateConnectionList(QString type);                  
-                    
+      void populateConnectionList(QString type);
  private:
+    enum columns {
+	dbssType=0,
+	dbssDetail,
+	dbssSql,
+	dbssColumns,
+    };
 
     typedef std::pair<QString, QString> geomPair;
     typedef std::list<geomPair > geomCol;
@@ -102,32 +115,39 @@
 			       geomCol& details, 
                                bool searchGeometryColumnsOnly,
                                bool searchPublicOnly);
-                               
-   
+
+    /**Inserts information about the spatial tables into mTableModel*/
+    bool getTableInfo(PGconn *pg, bool searchGeometryColumnsOnly, bool searchPublicOnly);
+
+    // queue another query for the thread
+    void addSearchGeometryColumn(const QString &schema, const QString &table, const QString &column);
+
     // Set the position of the database connection list to the last
     // used one. 
     void setConnectionListPosition();
     // Show the context help for the dialog
     void showHelp();
-    
+    // Combine the schema, table and column data into a single string
+    // useful for display to the user
+    QString fullDescription(QString schema, QString table, QString column, QString type);
     // The column labels
     QStringList mColumnLabels;
     // Our thread for doing long running queries
     QgsGeomColumnTypeThread* mColumnTypeThread;
     QString m_connInfo;
-    //QStringList m_selectedTables;
+    QStringList m_selectedTables;
     // Storage for the range of layer type icons
     QMap<QString, QPair<QString, QIcon> > mLayerIcons;
     //! Pointer to the qgis application mainwindow
     QgisApp *qgisApp;
     PGconn *pd;
-    
-    QgsConnectionManager* mConnMan;
-    QgsConnection mConn;
+    QgsConnectionRegistry* mConnectionRegistry;
     static const int context_id = 939347163;
+    //! Model that acts as datasource for mTableTreeWidget
+    QgsDbTableModel mTableModel;
+    QgsDbFilterProxyModel mProxyModel;
+    QgsDatabaseConnection* mDatabaseConnection;
 };
 
 
-
-
 #endif // QGSDBSOURCESELECT_H

Modified: branches/ogr-plugin-branch/src/app/qgsnewconnection.cpp
===================================================================
--- branches/ogr-plugin-branch/src/app/qgsnewconnection.cpp	2008-02-14 19:16:45 UTC (rev 8159)
+++ branches/ogr-plugin-branch/src/app/qgsnewconnection.cpp	2008-02-15 21:20:17 UTC (rev 8160)
@@ -26,12 +26,14 @@
 {
 #include <libpq-fe.h>
 }
-QgsNewConnection::QgsNewConnection(QWidget *parent, const QgsConnection* conn, Qt::WFlags fl)
+QgsNewConnection::QgsNewConnection(QWidget *parent, const QgsConnectionParameters* conn, Qt::WFlags fl)
 : QDialog(parent, fl)
 {
   setupUi(this);
+  //create member objects
+  mConnReg=new QgsConnectionRegistry;
   //set the type of connection
-  QString type=connManager.getSelectedType();
+  QString type=mConnReg->selectedType();
   cmbType->setCurrentIndex(cmbType->findText(type)); 
   
   if (conn!=NULL)
@@ -41,10 +43,7 @@
       txtDatabase->setText(conn->database);
       if (conn->save)
         txtPassword->setText(conn->password);
-      /*QString port = settings.readEntry(key + "/port");
-      if(port.length() ==0){
-      	port = "5432";
-      }*/
+      
       txtPort->setText(conn->port);
       txtUsername->setText(conn->user);
       if (conn->publicOnly)
@@ -62,10 +61,7 @@
       else   
          chkStorePassword->setCheckState(Qt::Unchecked);
       txtName->setText(conn->name);
-      qDebug("QgsNewConnection::QgsNewConnection : type "+conn->type);
       cmbType->setCurrentText(conn->type);
-      
-     
     }
   
 }
@@ -99,45 +95,48 @@
 
 QgsNewConnection::~QgsNewConnection()
 {
-  //delete connManager;                                   
+  delete mConnReg;                                   
 }
 void QgsNewConnection::testConnection()
 {
-  // following line uses Qt SQL plugin - currently not used
-  // QSqlDatabase *testCon = QSqlDatabase::addDatabase("QPSQL7","testconnection");
-  QgsConnectionManager* connMan=new QgsConnectionManager;
-  QgsConnection conn;
+     
+  QgsDatabaseConnection* connection=NULL;   
+  QgsConnectionParameters connPar;
   
-  conn.type=cmbType->currentText();
-  conn.name=txtName->text();
-  conn.host=txtHost->text();
-  conn.database=txtDatabase->text();
-  conn.port=txtPort->text();
-  conn.user=txtUsername->text();
-  conn.password=txtPassword->text();
-  conn.geometryColumnsOnly=cb_geometryColumnsOnly->isChecked();
-  conn.publicOnly=cb_publicSchemaOnly->isChecked();
-  conn.selected=txtName->text();
-  conn.save=chkStorePassword->isChecked();
+  connPar.type=cmbType->currentText();
+  connPar.name=txtName->text();
+  connPar.host=txtHost->text();
+  connPar.database=txtDatabase->text();
+  connPar.port=txtPort->text();
+  connPar.user=txtUsername->text();
+  connPar.password=txtPassword->text();
+  connPar.geometryColumnsOnly=cb_geometryColumnsOnly->isChecked();
+  connPar.publicOnly=cb_publicSchemaOnly->isChecked();
+  connPar.selected=txtName->text();
+  connPar.save=chkStorePassword->isChecked();
   
-  qDebug("QgsNewConnection::testConnection: before connect");
-  
-  if (connMan->connect(cmbType->currentText(),conn))
+  if (connPar.type.startsWith("Ogr"))
     {
-      // Database successfully opened; we can now issue SQL commands.
-      QMessageBox::information(this, tr("Test connection"), tr("Connection to %1 was successful").arg(txtDatabase->text()));
+      connection=new QgsOgrDatabaseConnection(&connPar);
+    }
+  else
+    {
+      connection=new QgsPostgresDatabaseConnection(&connPar);               
+    }    
+  if (connection->connect())
+    {
+      QMessageBox::information(this, tr("Test connection"), tr("Connection to %1 was successful").arg(txtName->text()));
     } else
     {
-      QMessageBox::information(this, tr("Test connection"), tr("Connection failed - Check settings and try again.\n\nExtended error information:\n") +connMan->getError());
+      QMessageBox::information(this, tr("Test connection"), tr("Connection failed - Check settings and try again.\n\nExtended error information:\n") +connection->error());
     }
- qDebug("QgsNewConnection::testConnection: after connect");
- delete connMan;
+ delete connection;   
+  
 }
 
 void QgsNewConnection::saveConnection()
 {
-  QgsConnection conn;   
-  
+  QgsConnectionParameters conn;   
   conn.type=cmbType->currentText();
   conn.name=txtName->text();
   conn.host=txtHost->text();
@@ -154,9 +153,9 @@
   conn.selected=txtName->text();
   conn.save=chkStorePassword->isChecked();
   
-  connManager.saveConnection(conn);
-  connManager.setSelectedType(conn.type);
-  connManager.setSelected(conn.type,conn.name);                       
+  mConnReg->saveConnection(conn);
+  mConnReg->setSelectedType(conn.type);
+  mConnReg->setSelected(conn.type,conn.name);                       
   accept();
 }
 

Modified: branches/ogr-plugin-branch/src/app/qgsnewconnection.h
===================================================================
--- branches/ogr-plugin-branch/src/app/qgsnewconnection.h	2008-02-14 19:16:45 UTC (rev 8159)
+++ branches/ogr-plugin-branch/src/app/qgsnewconnection.h	2008-02-15 21:20:17 UTC (rev 8160)
@@ -19,8 +19,13 @@
 #define QGSNEWCONNECTION_H
 #include "ui_qgsnewconnectionbase.h"
 #include "qgisgui.h"
-//fred
-#include "qgsconnectionmanager.h"
+
+#include "qgsconnectionparameters.h"
+#include "qgsconnectionregistry.h"
+#include "qgsdatabaseconnection.h"
+#include "qgsogrdatabaseconnection.h"
+#include "qgspostgresdatabaseconnection.h"
+
 /*! \class QgsNewConnection
  * \brief Dialog to allow the user to configure and save connection
  * information for a PostgresQl database
@@ -30,7 +35,7 @@
   Q_OBJECT
   public:
     //! Constructor
-    QgsNewConnection(QWidget *parent = 0, const QgsConnection* conn=0, Qt::WFlags fl = QgisGui::ModalDialogFlags);
+    QgsNewConnection(QWidget *parent = 0, const QgsConnectionParameters* conn=0, Qt::WFlags fl = QgisGui::ModalDialogFlags);
     //! Destructor
     ~QgsNewConnection();
     //! Tests the connection using the parameters supplied
@@ -47,7 +52,7 @@
     void on_cb_geometryColumnsOnly_clicked();
   private:
     //fred      
-    QgsConnectionManager connManager;      
+    QgsConnectionRegistry* mConnReg;
     static const int context_id = 929865718;
 };
 

Modified: branches/ogr-plugin-branch/src/core/qgsdatasourceuri.cpp
===================================================================
--- branches/ogr-plugin-branch/src/core/qgsdatasourceuri.cpp	2008-02-14 19:16:45 UTC (rev 8159)
+++ branches/ogr-plugin-branch/src/core/qgsdatasourceuri.cpp	2008-02-15 21:20:17 UTC (rev 8160)
@@ -250,11 +250,38 @@
 
 QString QgsDataSourceURI::uri() const
 { 
-  return connInfo()
+  QString connString="";
+                                 
+  if (mType=="OgrMySQL")
+     { 
+      connString="MySQL:"+mDatabase+","+
+                 "host="+mHost+","+
+                 "user="+mUsername+","+
+                 "password="+mPassword;
+     }
+  else if (mType=="OgrPostgreSQL")
+     {
+      connString="PG:dbname="+mDatabase+" "+
+                 "host="+mHost+" "+
+                 "user="+mUsername+" "+
+                 "password="+mPassword;
+     }      
+  else if (mType=="OgrOracle")
+     {
+      connString="OCI:"+mUsername+"/"+
+                 mPassword+"@"+
+                 mHost+"/"+
+                 mDatabase;
+     }           
+  else
+     {
+        connString=connInfo()
        + QString(" table=%1 (%2) sql=%3")
                 .arg( quotedTablename() )
                 .arg( mGeometryColumn )
-                .arg( mSql );
+                .arg( mSql );         
+     }
+  return connString;                         
 }
 
 QString QgsDataSourceURI::quotedTablename() const

Modified: branches/ogr-plugin-branch/src/ui/qgsdbsourceselectbase.ui
===================================================================
--- branches/ogr-plugin-branch/src/ui/qgsdbsourceselectbase.ui	2008-02-14 19:16:45 UTC (rev 8159)
+++ branches/ogr-plugin-branch/src/ui/qgsdbsourceselectbase.ui	2008-02-15 21:20:17 UTC (rev 8160)
@@ -5,8 +5,8 @@
    <rect>
     <x>0</x>
     <y>0</y>
-    <width>510</width>
-    <height>475</height>
+    <width>384</width>
+    <height>457</height>
    </rect>
   </property>
   <property name="windowTitle" >
@@ -77,6 +77,11 @@
             <string>OgrOracle</string>
            </property>
           </item>
+          <item>
+           <property name="text" >
+            <string>OgrGeneric</string>
+           </property>
+          </item>
          </widget>
         </item>
         <item>
@@ -137,50 +142,95 @@
      <property name="title" >
       <string>Tables:</string>
      </property>
-     <layout class="QVBoxLayout" >
+     <layout class="QGridLayout" >
       <property name="margin" >
        <number>9</number>
       </property>
       <property name="spacing" >
        <number>6</number>
       </property>
-      <item>
-       <widget class="QTableWidget" name="lstTables" >
-        <property name="mouseTracking" >
-         <bool>true</bool>
-        </property>
-        <property name="editTriggers" >
-         <set>QAbstractItemView::NoEditTriggers</set>
-        </property>
+      <item row="0" column="0" >
+       <widget class="QTreeView" name="mTablesTreeView" >
         <property name="selectionMode" >
          <enum>QAbstractItemView::MultiSelection</enum>
         </property>
-        <property name="selectionBehavior" >
-         <enum>QAbstractItemView::SelectRows</enum>
+       </widget>
+      </item>
+     </layout>
+    </widget>
+   </item>
+   <item>
+    <layout class="QHBoxLayout" >
+     <property name="margin" >
+      <number>0</number>
+     </property>
+     <property name="spacing" >
+      <number>6</number>
+     </property>
+     <item>
+      <spacer>
+       <property name="orientation" >
+        <enum>Qt::Horizontal</enum>
+       </property>
+       <property name="sizeHint" >
+        <size>
+         <width>305</width>
+         <height>25</height>
+        </size>
+       </property>
+      </spacer>
+     </item>
+     <item>
+      <widget class="QPushButton" name="mSearchOptionsButton" >
+       <property name="text" >
+        <string>Search options...</string>
+       </property>
+      </widget>
+     </item>
+    </layout>
+   </item>
+   <item>
+    <widget class="QGroupBox" name="mSearchGroupBox" >
+     <property name="title" >
+      <string/>
+     </property>
+     <layout class="QGridLayout" >
+      <property name="margin" >
+       <number>9</number>
+      </property>
+      <property name="spacing" >
+       <number>6</number>
+      </property>
+      <item row="0" column="0" >
+       <widget class="QLabel" name="mSearchLabel" >
+        <property name="text" >
+         <string>Search:</string>
         </property>
-        <property name="showGrid" >
-         <bool>false</bool>
+       </widget>
+      </item>
+      <item row="2" column="0" colspan="2" >
+       <widget class="QLabel" name="mSearchModeLabel" >
+        <property name="text" >
+         <string>Search mode:</string>
         </property>
-        <property name="gridStyle" >
-         <enum>Qt::SolidLine</enum>
+       </widget>
+      </item>
+      <item row="2" column="2" >
+       <widget class="QComboBox" name="mSearchModeComboBox" />
+      </item>
+      <item row="1" column="0" colspan="2" >
+       <widget class="QLabel" name="mSearchColumnsLabel" >
+        <property name="text" >
+         <string>Search in columns:</string>
         </property>
-        <column>
-         <property name="text" >
-          <string>Type</string>
-         </property>
-        </column>
-        <column>
-         <property name="text" >
-          <string>Name</string>
-         </property>
-        </column>
-        <column>
-         <property name="text" >
-          <string>Sql</string>
-         </property>
-        </column>
        </widget>
       </item>
+      <item row="1" column="2" >
+       <widget class="QComboBox" name="mSearchColumnComboBox" />
+      </item>
+      <item row="0" column="1" colspan="2" >
+       <widget class="QLineEdit" name="mSearchTableEdit" />
+      </item>
      </layout>
     </widget>
    </item>
@@ -284,7 +334,6 @@
   <tabstop>btnNew</tabstop>
   <tabstop>btnEdit</tabstop>
   <tabstop>btnDelete</tabstop>
-  <tabstop>lstTables</tabstop>
   <tabstop>mEncodingComboBox</tabstop>
   <tabstop>btnHelp</tabstop>
   <tabstop>btnAdd</tabstop>



More information about the QGIS-commit mailing list