QueryDataSourceDialog.cpp
Go to the documentation of this file.
1 /* Copyright (C) 2008 National Institute For Space Research (INPE) - Brazil.
2 
3  This file is part of the TerraLib - a Framework for building GIS enabled applications.
4 
5  TerraLib is free software: you can redistribute it and/or modify
6  it under the terms of the GNU Lesser General Public License as published by
7  the Free Software Foundation, either version 3 of the License,
8  or (at your option) any later version.
9 
10  TerraLib is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU Lesser General Public License for more details.
14 
15  You should have received a copy of the GNU Lesser General Public License
16  along with TerraLib. See COPYING. If not, write to
17  TerraLib Team at <terralib-team@terralib.org>.
18  */
19 
20 /*!
21  \file terralib/qt/widgets/query/QueryDataSourceDialog.cpp
22 
23  \brief This file defines a class for a Query DataSource Dialog Dialog.
24 */
25 
26 // TerraLib
27 #include "../../../common/StringUtils.h"
28 #include "../../../dataaccess/dataset/DataSet.h"
29 #include "../../../dataaccess/dataset/DataSetAdapter.h"
30 #include "../../../dataaccess/dataset/DataSetTypeConverter.h"
31 #include "../../../dataaccess/dataset/DataSetType.h"
32 #include "../../../dataaccess/dataset/ObjectIdSet.h"
33 #include "../../../dataaccess/datasource/DataSourceCapabilities.h"
34 #include "../../../dataaccess/datasource/DataSourceInfoManager.h"
35 #include "../../../dataaccess/datasource/DataSourceInfo.h"
36 #include "../../../dataaccess/datasource/DataSourceManager.h"
37 #include "../../../dataaccess/query/SQLDialect.h"
38 #include "../../../dataaccess/query/SQLFunctionEncoder.h"
39 #include "../../../dataaccess/utils/Utils.h"
40 #include "../../../datatype/NumericProperty.h"
41 #include "../../../datatype/SimpleProperty.h"
42 #include "../../../datatype/StringProperty.h"
43 #include "../../../geometry/GeometryProperty.h"
44 #include "../../../maptools/DataSetLayer.h"
45 #include "../datasource/selector/DataSourceSelectorDialog.h"
46 #include "../layer/utils/DataSet2Layer.h"
47 #include "../utils/ScopedCursor.h"
48 #include "QueryDataSourceDialog.h"
49 #include "ui_QueryDataSourceDialogForm.h"
50 
51 // Qt
52 #include <QCursor>
53 #include <QFileDialog>
54 #include <QGridLayout>
55 #include <QMessageBox>
56 #include <QTextStream>
57 
58 // STL
59 #include <cassert>
60 #include <memory>
61 
62 // Boost
63 #include <boost/filesystem.hpp>
64 #include <boost/uuid/random_generator.hpp>
65 #include <boost/uuid/uuid_io.hpp>
66 
68 
70  : QDialog(parent, f),
71  m_ui(new Ui::QueryDataSourceDialogForm)
72 {
73  m_ui->setupUi(this);
74 
75  m_ui->m_applyToolButton->setIcon(QIcon::fromTheme("media-playback-start-green"));
76  m_ui->m_clearToolButton->setIcon(QIcon::fromTheme("edit-clear"));
77  m_ui->m_applySelToolButton->setIcon(QIcon::fromTheme("pointer-selection"));
78  m_ui->m_targetDatasourceToolButton->setIcon(QIcon::fromTheme("datasource"));
79  m_ui->m_createLayerlToolButton->setIcon(QIcon::fromTheme("layer-new"));
80 
81 
82  m_ui->m_saveSqlToolButton->setIcon(QIcon::fromTheme("document-save-as"));
83  m_ui->m_openSqlToolButton->setIcon(QIcon::fromTheme("document-open"));
84 
85  //table view
87  m_ui->m_tableView->setModel(m_tableModel);
88 
89  //dataset display
91 
92  m_appMapDisplay = 0;
93 
94  QGridLayout* displayGridLayout = new QGridLayout(m_ui->m_displayWidget);
95  displayGridLayout->setContentsMargins(0, 0, 0, 0);
96  displayGridLayout->addWidget(m_dataSetDisplay);
97 
98  // Signals¨& slots
99  connect(m_ui->m_dataSourceComboBox, SIGNAL(activated(int)), this, SLOT(onDataSourceSelected(int)));
100  connect(m_ui->m_baseDataSetComboBox, SIGNAL(activated(int)), this, SLOT(onBaseDataSetSelected(int)));
101  connect(m_ui->m_dataSetListWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(onDataSetItemClicked(QListWidgetItem*)));
102  connect(m_ui->m_applyToolButton, SIGNAL(clicked()), this, SLOT(onApplyPushButtonClicked()));
103  connect(m_ui->m_clearToolButton, SIGNAL(clicked()), this, SLOT(onClearPushButtonClicked()));
104  connect(m_ui->m_saveSqlToolButton, SIGNAL(clicked()), this, SLOT(onSaveSqlToolButtonClicked()));
105  connect(m_ui->m_openSqlToolButton, SIGNAL(clicked()), this, SLOT(onOpenSqlToolButtonClicked()));
106  connect(m_ui->m_sqlEditorTextEdit, SIGNAL(textChanged()), this, SLOT(onSQLEditorTextChanged()));
107  connect(m_ui->m_applySelToolButton, SIGNAL(clicked()), this, SLOT(onApplySelToolButtonClicked()));
108  connect(m_ui->m_createLayerlToolButton, SIGNAL(pressed()), this, SLOT(onCreateLayerToolButtonClicked()));
109  connect(m_ui->m_targetDatasourceToolButton, SIGNAL(pressed()), this, SLOT(onTargetDatasourceToolButtonPressed()));
110  connect(m_ui->m_targetFileToolButton, SIGNAL(pressed()), this, SLOT(onTargetFileToolButtonPressed()));
111  connect(m_ui->m_pkTableComboBox, SIGNAL(activated(int)), this, SLOT(onPkTableComboBoxSelected(int)));
112 
113  //load data sources information
115 
116  //
117  m_ui->m_helpPushButton->setPageReference("widgets/query/query_datasource.html");
118 }
119 
121 {
122  m_keyWords.clear();
123 }
124 
125 void te::qt::widgets::QueryDataSourceDialog::setLayerList(std::list<te::map::AbstractLayerPtr> layerList)
126 {
127  m_layerList = layerList;
128 
129  if(m_ui->m_baseDataSetComboBox->count() > 0)
130  onBaseDataSetSelected(0);
131 }
132 
134 {
135  m_appMapDisplay = appMapDisplay;
136 }
137 
139 {
140  m_ui->m_dataSourceComboBox->clear();
141 
142  std::map<std::string, te::da::DataSourceInfoPtr>::const_iterator it = te::da::DataSourceInfoManager::getInstance().begin();
143  std::map<std::string, te::da::DataSourceInfoPtr>::const_iterator itend =te::da::DataSourceInfoManager::getInstance().end();
144 
145  while(it != itend)
146  {
147  te::da::DataSourcePtr ds = te::da::GetDataSource(it->second->getId());
148 
149  const te::da::SQLDialect* dialect = ds->getDialect();
150 
151  if (dialect)
152  m_ui->m_dataSourceComboBox->addItem(it->second->getTitle().c_str(), QVariant(it->second->getId().c_str()));
153 
154  ++it;
155  }
156 
157  if(m_ui->m_dataSourceComboBox->count() != 0)
158  onDataSourceSelected(m_ui->m_dataSourceComboBox->currentIndex());
159 }
160 
162 {
163  m_keyWords.clear();
164 
165  // add defaul SQL key words
166  m_keyWords.insert(std::map<std::string, Qt::GlobalColor>::value_type("SELECT", Qt::blue));
167  m_keyWords.insert(std::map<std::string, Qt::GlobalColor>::value_type("FROM", Qt::blue));
168  m_keyWords.insert(std::map<std::string, Qt::GlobalColor>::value_type("WHERE", Qt::blue));
169  m_keyWords.insert(std::map<std::string, Qt::GlobalColor>::value_type("JOIN", Qt::blue));
170  m_keyWords.insert(std::map<std::string, Qt::GlobalColor>::value_type("INNER", Qt::blue));
171  m_keyWords.insert(std::map<std::string, Qt::GlobalColor>::value_type("LEFT", Qt::blue));
172  m_keyWords.insert(std::map<std::string, Qt::GlobalColor>::value_type("RIGHT", Qt::blue));
173  m_keyWords.insert(std::map<std::string, Qt::GlobalColor>::value_type("AS", Qt::blue));
174  m_keyWords.insert(std::map<std::string, Qt::GlobalColor>::value_type("GROUP", Qt::blue));
175  m_keyWords.insert(std::map<std::string, Qt::GlobalColor>::value_type("ORDER", Qt::blue));
176  m_keyWords.insert(std::map<std::string, Qt::GlobalColor>::value_type("BY", Qt::blue));
177 
178  //add data source specific key words
179  std::string dataSourceId = m_ui->m_dataSourceComboBox->itemData(m_ui->m_dataSourceComboBox->currentIndex()).toString().toStdString();
180 
181  te::da::DataSourcePtr ds = te::da::GetDataSource(dataSourceId);
182 
183  const te::da::SQLDialect* dialect = ds->getDialect();
184 
185  std::vector<std::string> names = dialect->getRegisteredNames();
186 
187  for(std::size_t t = 0; t < names.size(); ++t)
188  {
189  QString s = names[t].c_str();
190  QString sUpper = s.toUpper();
191 
192  m_keyWords.insert(std::map<std::string, Qt::GlobalColor>::value_type(sUpper.toStdString(), Qt::red));
193  }
194 
195 }
196 
198 {
199  m_ui->m_baseDataSetComboBox->clear();
200  m_ui->m_dataSetListWidget->clear();
201  m_ui->m_attrDataSetListWidget->clear();
202  m_ui->m_pkTableComboBox->clear();
203  m_ui->m_pkAttrComboBox->clear();
204 
205  std::string dataSourceId = m_ui->m_dataSourceComboBox->itemData(index).toString().toStdString();
206 
207  te::da::DataSourcePtr ds = te::da::GetDataSource(dataSourceId);
208 
209  if(!ds->isOpened())
210  ds->open();
211 
212  std::vector<std::string> dataSetNames;
213  te::da::GetDataSetNames(dataSetNames, dataSourceId);
214 
215  for(std::size_t t = 0; t < dataSetNames.size(); ++t)
216  {
217  m_ui->m_baseDataSetComboBox->addItem(dataSetNames[t].c_str());
218  m_ui->m_dataSetListWidget->addItem(dataSetNames[t].c_str());
219  m_ui->m_pkTableComboBox->addItem(dataSetNames[t].c_str());
220  }
221 
222  if(m_ui->m_baseDataSetComboBox->count() > 0)
223  onBaseDataSetSelected(0);
224 
225  if (m_ui->m_pkTableComboBox->count() > 0)
226  onPkTableComboBoxSelected(0);
227 
228  buildMap();
229 }
230 
232 {
233  std::string dataSet = m_ui->m_baseDataSetComboBox->itemText(index).toStdString();
234 
235  m_ui->m_layerComboBox->clear();
236 
237  std::list<te::map::AbstractLayerPtr>::iterator it = m_layerList.begin();
238 
239  while(it != m_layerList.end())
240  {
242 
243  std::auto_ptr<te::da::DataSetType> dsType = l->getSchema();
244 
245  te::map::DataSetLayer* dsLayer = dynamic_cast<te::map::DataSetLayer*>(l.get());
246 
247  if(dsLayer && dsType->getName() == dataSet)
248  m_ui->m_layerComboBox->addItem(l->getTitle().c_str(), QVariant::fromValue(l));
249 
250  ++it;
251  }
252 
253  m_ui->m_pkTableComboBox->setCurrentIndex(index);
254  onPkTableComboBoxSelected(index);
255 }
256 
258 {
259  m_ui->m_attrDataSetListWidget->clear();
260 
261  if(!item)
262  return;
263 
264  std::string dataSourceId = m_ui->m_dataSourceComboBox->itemData(m_ui->m_dataSourceComboBox->currentIndex()).toString().toStdString();
265 
266  std::string dataSetName = item->text().toStdString();
267 
268  te::da::DataSetType* dsType = te::da::GetDataSetType(dataSetName, dataSourceId);
269 
270  std::vector<te::dt::Property*> propVec = dsType->getProperties();
271 
272  for(std::size_t t = 0; t < propVec.size(); ++t)
273  {
274  m_ui->m_attrDataSetListWidget->addItem(propVec[t]->getName().c_str());
275  }
276 
277  delete dsType;
278 }
279 
281 {
282  std::string dataSetName = m_ui->m_pkTableComboBox->itemText(index).toStdString();
283 
284  std::string dataSourceId = m_ui->m_dataSourceComboBox->itemData(m_ui->m_dataSourceComboBox->currentIndex()).toString().toStdString();
285 
286  te::da::DataSetType* dsType = te::da::GetDataSetType(dataSetName, dataSourceId);
287 
288  std::vector<te::dt::Property*> propVec = dsType->getProperties();
289 
290  for (std::size_t t = 0; t < propVec.size(); ++t)
291  {
292  m_ui->m_pkAttrComboBox->addItem(propVec[t]->getName().c_str());
293  }
294 
295  delete dsType;
296 }
297 
299 {
300  te::qt::widgets::ScopedCursor cursor(Qt::WaitCursor);
301 
302  m_ui->m_sqlEditorTextEdit->setFocus();
303 
304  if (m_ui->m_sqlEditorTextEdit->toPlainText().isEmpty())
305  {
306  return;
307  }
308 
309  std::string dataSourceId = m_ui->m_dataSourceComboBox->itemData(m_ui->m_dataSourceComboBox->currentIndex()).toString().toStdString();
310 
311  te::da::DataSourcePtr ds = te::da::GetDataSource(dataSourceId);
312 
313  std::string dataSetName = m_ui->m_baseDataSetComboBox->currentText().toStdString();
314 
315  te::da::DataSetTypePtr dsType(te::da::GetDataSetType(dataSetName, dataSourceId));
316 
317  std::string sql = "";
318 
319  if(m_ui->m_sqlEditorTextEdit->textCursor().selectedText().isEmpty())
320  sql = m_ui->m_sqlEditorTextEdit->toPlainText().toStdString();
321  else
322  sql = m_ui->m_sqlEditorTextEdit->textCursor().selectedText().toStdString();
323 
324  //get dataset
325  std::auto_ptr<te::da::DataSet> dataSet;
326 
327  try
328  {
329  dataSet = ds->query(sql);
330  }
331  catch(const std::exception& e)
332  {
333  m_dataSetDisplay->clear();
334  m_tableModel->setDataSet(0, ds->getEncoding());
335 
336  std::string errorMessage = "SQL Error: ";
337  errorMessage += e.what();
338  errorMessage += "\n";
339  errorMessage += "-------------------------------------------------------------------------\n";
340 
341  m_ui->m_logPlainTextEdit->appendPlainText(errorMessage.c_str());
342 
343  m_ui->m_tabWidget->setCurrentIndex(1);
344 
345  return;
346  }
347 
348  std::string message = "SQL Done: ";
349  message += sql;
350  message += "\n";
351  message += "-------------------------------------------------------------------------\n";
352 
353  m_ui->m_logPlainTextEdit->appendPlainText(message.c_str());
354 
355  //draw dataset
356  m_dataSetDisplay->clear();
357 
358  bool draw = false;
359  for(std::size_t t = 0; t < dataSet->getNumProperties(); ++t)
360  {
361  int type = dataSet->getPropertyDataType(t);
362 
363  if(type == te::dt::GEOMETRY_TYPE)
364  {
365  draw = true;
366  break;
367  }
368  }
369 
370  if(draw)
371  m_dataSetDisplay->draw(dsType, ds, dataSet.get());
372  else
373  m_dataSetDisplay->clear();
374 
375  //show dataset on table
376  m_tableModel->setDataSet(dataSet.release(), ds->getEncoding());
377 
378  m_ui->m_tabWidget->setCurrentIndex(0);
379 }
380 
382 {
383  m_ui->m_sqlEditorTextEdit->clear();
384 
385  m_dataSetDisplay->clear();
386 
387  m_tableModel->setDataSet(0, te::common::LATIN1);
388 }
389 
391 {
392  disconnect(m_ui->m_sqlEditorTextEdit, SIGNAL(textChanged()), this, SLOT(onSQLEditorTextChanged()));
393 
394  QString sql = m_ui->m_sqlEditorTextEdit->toPlainText();
395 
396  int curPos = m_ui->m_sqlEditorTextEdit->textCursor().position();
397 
398  disconnect(m_ui->m_sqlEditorTextEdit, SIGNAL(textChanged()), this, SLOT(onSQLEditorTextChanged()));
399 
400  m_ui->m_sqlEditorTextEdit->clear();
401 
402  QStringList words = sql.split(' ');
403 
404  bool isAttrValue = false;
405 
406  for(int i = 0; i < words.size(); ++i)
407  {
408  QString w = words.value(i).toUpper();
409 
410  std::string strW = w.toStdString();
411 
412  std::map<std::string, Qt::GlobalColor>::iterator it = m_keyWords.find(strW);
413 
414  bool removeAttrValue = false;
415 
416  if(it != m_keyWords.end())
417  {
418  m_ui->m_sqlEditorTextEdit->setFontWeight(QFont::Bold);
419  m_ui->m_sqlEditorTextEdit->setTextColor(it->second);
420  }
421  else
422  {
423  bool okNum = false;
424 
425  words.value(i).toDouble(&okNum);
426 
427  m_ui->m_sqlEditorTextEdit->setFontWeight(QFont::Normal);
428 
429  if(okNum)
430  m_ui->m_sqlEditorTextEdit->setTextColor(Qt::darkGreen);
431  else
432  {
433  if(!strW.empty())
434  {
435  std::string initChar = strW.substr(0, 1);
436  if(!isAttrValue && (initChar == "'" || initChar == "\""))
437  isAttrValue = true;
438 
439  if(strW.size() > 1)
440  {
441  std::string lastChar = strW.substr(strW.size() - 1, 1);
442  if(isAttrValue && (lastChar == "'" || lastChar == "\""))
443  removeAttrValue = true;
444  }
445  }
446 
447  if(isAttrValue)
448  m_ui->m_sqlEditorTextEdit->setTextColor(Qt::magenta);
449  else
450  m_ui->m_sqlEditorTextEdit->setTextColor(Qt::black);
451  }
452  }
453 
454  m_ui->m_sqlEditorTextEdit->insertPlainText(words.value(i));
455 
456  if(removeAttrValue)
457  isAttrValue = false;
458 
459  if(i < words.size() - 1)
460  m_ui->m_sqlEditorTextEdit->insertPlainText(" ");
461  }
462 
463  QTextCursor c = m_ui->m_sqlEditorTextEdit->textCursor();
464  c.setPosition(curPos);
465  m_ui->m_sqlEditorTextEdit->setTextCursor(c);
466 
467  connect(m_ui->m_sqlEditorTextEdit, SIGNAL(textChanged()), this, SLOT(onSQLEditorTextChanged()));
468 }
469 
471 {
472  //select file
473  QString path = QFileDialog::getSaveFileName(this, tr("Set a SQL file..."), "", tr("SQL File *.sql"));
474 
475  if(path.isNull())
476  return;
477 
478  //open file
479  QFile file(path);
480 
481  if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
482  {
483  QMessageBox::warning(this, tr("Query DataSource"), file.errorString());
484  return;
485  }
486 
487  // save to file
488  QTextStream out(&file);
489 
490  out << m_ui->m_sqlEditorTextEdit->toPlainText();
491 
492  file.close();
493 }
494 
496 {
497  //select file
498  QString path = QFileDialog::getOpenFileName(this, tr("Select a SQL file..."), "", tr("SQL File *.sql"));
499 
500  if(path.isNull())
501  return;
502 
503  //open file
504  QFile file(path);
505 
506  if(!file.open(QIODevice::ReadOnly))
507  {
508  QMessageBox::warning(this, tr("Query DataSource"), file.errorString());
509  return;
510  }
511 
512  // show file
513  QTextStream in(&file);
514 
515  m_ui->m_sqlEditorTextEdit->clear();
516 
517  while(!in.atEnd())
518  {
519  QString line = in.readLine();
520 
521  m_ui->m_sqlEditorTextEdit->append(line);
522  }
523 
524  file.close();
525 }
526 
528 {
529  if(m_ui->m_sqlEditorTextEdit->toPlainText().isEmpty())
530  {
531  QMessageBox::information(this, tr("Warning"), tr("SQL not defined."));
532  return;
533  }
534 
535  QVariant varLayer = m_ui->m_layerComboBox->itemData(m_ui->m_layerComboBox->currentIndex(), Qt::UserRole);
536  te::map::AbstractLayerPtr layer = varLayer.value<te::map::AbstractLayerPtr>();
537 
538  if(!layer.get())
539  {
540  QMessageBox::warning(this, tr("Query DataSource"), tr("No layer selected."));
541  return;
542  }
543 
544  te::qt::widgets::ScopedCursor cursor(Qt::WaitCursor);
545 
546  std::string dataSourceId = m_ui->m_dataSourceComboBox->itemData(m_ui->m_dataSourceComboBox->currentIndex()).toString().toStdString();
547 
548  te::da::DataSourcePtr ds = te::da::GetDataSource(dataSourceId);
549 
550  std::string dataSetName = m_ui->m_baseDataSetComboBox->currentText().toStdString();
551 
552  te::da::DataSetTypePtr dsType(te::da::GetDataSetType(dataSetName, dataSourceId));
553 
554  std::string sql = "";
555 
556  if(m_ui->m_sqlEditorTextEdit->textCursor().selectedText().isEmpty())
557  sql = m_ui->m_sqlEditorTextEdit->toPlainText().toStdString();
558  else
559  sql = m_ui->m_sqlEditorTextEdit->textCursor().selectedText().toStdString();
560 
561  //get dataset
562  std::auto_ptr<te::da::DataSet> dataSet;
563 
564  try
565  {
566  dataSet = ds->query(sql);
567  }
568  catch(...)
569  {
570  QMessageBox::warning(this, tr("Query DataSource"), tr("Error executing SQL."));
571  return;
572  }
573 
574  try
575  {
576  if(m_ui->m_newSelRadioButton->isChecked())
577  {
578  // Generates the oids
579  dataSet->moveBeforeFirst();
580  te::da::ObjectIdSet* oids = te::da::GenerateOIDSet(dataSet.get(), dsType.get());
581 
582  oids->setExpressionByInClause();
583 
584  layer->clearSelected();
585  layer->select(oids);
586  }
587  else if(m_ui->m_addSelRadioButton->isChecked())
588  {
589  // Generates the oids
590  dataSet->moveBeforeFirst();
591  te::da::ObjectIdSet* oids = te::da::GenerateOIDSet(dataSet.get(), dsType.get());
592 
593  oids->setExpressionByInClause();
594 
595  layer->select(oids);
596  }
597 
598  if(m_appMapDisplay)
599  {
600  m_appMapDisplay->refresh();
601  }
602  }
603  catch(te::common::Exception& e)
604  {
605  QMessageBox::warning(this, tr("Query DataSource"), tr("Error selecting objects: ") + e.what());
606  return;
607  }
608  QMessageBox::information(this, tr("Query DataSource"), tr("Selection done."));
609 }
610 
611 
613 {
614  // check input parameters
615  if(m_ui->m_sqlEditorTextEdit->toPlainText().isEmpty())
616  {
617  QMessageBox::information(this, tr("Warning"), tr("SQL not defined."));
618  return;
619  }
620 
621  if(m_ui->m_repositoryLineEdit->text().isEmpty())
622  {
623  QMessageBox::information(this, tr("Warning"), tr("Define a repository for the result."));
624  return;
625  }
626 
627  if(m_ui->m_newLayerNameLineEdit->text().isEmpty())
628  {
629  QMessageBox::information(this, tr("Warning"), tr("Define a name for the resulting layer."));
630  return;
631  }
632 
633  te::qt::widgets::ScopedCursor cursor(Qt::WaitCursor);
634 
635  //create dataset
636  std::string dataSourceId = m_ui->m_dataSourceComboBox->itemData(m_ui->m_dataSourceComboBox->currentIndex()).toString().toStdString();
637 
638  te::da::DataSourcePtr ds = te::da::GetDataSource(dataSourceId);
639 
640  std::string inputDataSetName = m_ui->m_baseDataSetComboBox->currentText().toStdString();
641 
642  te::da::DataSetTypePtr inputDataSetType(te::da::GetDataSetType(inputDataSetName, dataSourceId));
643 
644  std::string sql = "";
645 
646  if(m_ui->m_sqlEditorTextEdit->textCursor().selectedText().isEmpty())
647  sql = m_ui->m_sqlEditorTextEdit->toPlainText().toStdString();
648  else
649  sql = m_ui->m_sqlEditorTextEdit->textCursor().selectedText().toStdString();
650 
651  std::auto_ptr<te::da::DataSet> dataSet;
652 
653  try
654  {
655  dataSet = ds->query(sql);
656  }
657  catch(...)
658  {
659  QMessageBox::warning(this, tr("Query DataSource"), tr("Error executing SQL."));
660  return;
661  }
662 
663  if (dataSet->size() == 0)
664  {
665  QMessageBox::warning(this, tr("Query DataSource"), tr("Query result is empty."));
666  return;
667  }
668 
669  //create / get data source
670  te::da::DataSourcePtr outputDataSource;
671 
672  if(m_toFile)
673  {
674  //create new data source
675  boost::filesystem::path uri(m_ui->m_repositoryLineEdit->text().toStdString());
676 
677  std::map<std::string, std::string> dsInfo;
678  dsInfo["URI"] = uri.string();
679 
680  boost::uuids::basic_random_generator<boost::mt19937> gen;
681  boost::uuids::uuid u = gen();
682  std::string id_ds = boost::uuids::to_string(u);
683 
685  dsInfoPtr->setConnInfo(dsInfo);
686  dsInfoPtr->setTitle(uri.stem().string());
687  dsInfoPtr->setAccessDriver("OGR");
688  dsInfoPtr->setType("OGR");
689  dsInfoPtr->setDescription(uri.string());
690  dsInfoPtr->setId(id_ds);
691 
693 
694  outputDataSource = te::da::DataSourceManager::getInstance().get(id_ds, "OGR", dsInfoPtr->getConnInfo());
695  }
696  else
697  {
698  outputDataSource = te::da::GetDataSource(m_outputDatasource->getId());
699  }
700 
701  //get output dataset name
702  std::string dataSetName = m_ui->m_newLayerNameLineEdit->text().toStdString();
703 
704  std::size_t idx = dataSetName.find(".");
705  if (idx != std::string::npos)
706  dataSetName=dataSetName.substr(0,idx);
707 
708  //save data
709  std::auto_ptr<te::da::DataSetType> dsType(new te::da::DataSetType(dataSetName));
710 
711  dataSet->moveFirst();
712 
713  std::set<std::string> names;
714 
715  int srid = 0;
716 
717  for(std::size_t t = 0; t < dataSet->getNumProperties(); ++t)
718  {
719  //check if the property name its duplicated
720  std::string propName = dataSet->getPropertyName(t);
721 
722  int count = 1;
723  while(names.find(propName) != names.end())
724  {
725  propName += "_";
726  propName += te::common::Convert2String(count);
727  }
728 
729  names.insert(propName);
730 
731  //create output property
732  te::dt::Property* p = 0;
733  if(dataSet->getPropertyDataType(t) != te::dt::GEOMETRY_TYPE)
734  {
735  if (dataSet->getPropertyDataType(t) == te::dt::STRING_TYPE)
736  {
737  p = new te::dt::StringProperty(propName, te::dt::VAR_STRING, 255, false);
738  }
739  else if (dataSet->getPropertyDataType(t) == te::dt::NUMERIC_TYPE)
740  {
741  p = new te::dt::NumericProperty(propName, 0, 0, false);
742  }
743  else
744  p = new te::dt::SimpleProperty(propName, dataSet->getPropertyDataType(t));
745  }
746  else
747  {
748  std::auto_ptr<te::gm::Geometry> geom = dataSet->getGeometry(t);
749 
750  srid = geom->getSRID();
751 
752  p = new te::gm::GeometryProperty(propName, srid, geom->getGeomTypeId());
753  }
754 
755  //add property to output datasetype
756  if(p)
757  {
758  dsType->add(p);
759 
760  //check primary key
761  if (m_ui->m_pkCheckBox->isChecked())
762  {
763  std::string pkAttrName = m_ui->m_pkAttrComboBox->itemText(m_ui->m_pkAttrComboBox->currentIndex()).toStdString();
764 
766  {
767  std::string pkName = dataSetName + "_" + p->getName() + "_pk";
768  te::da::PrimaryKey* pk = new te::da::PrimaryKey(pkName, dsType.get());
769  pk->add(p->clone());
770  }
771  }
772  }
773  else
774  {
775  QMessageBox::warning(this, tr("Query DataSource"), tr("Error creating output dataset."));
776  return;
777  }
778  }
779 
780  dataSet->moveBeforeFirst();
781 
782  //create converter in case property name changed
783  te::da::DataSetTypeConverter* converter = new te::da::DataSetTypeConverter(dsType.get(), outputDataSource->getCapabilities(), outputDataSource->getEncoding());
784 
786 
787  std::auto_ptr<te::da::DataSetAdapter> dsAdapter(te::da::CreateAdapter(dataSet.get(), converter));
788 
789  //save data
790  std::map<std::string, std::string> options;
791 
792  outputDataSource->createDataSet(dsType.get(), options);
793 
794  outputDataSource->add(dataSetName, dsAdapter.get(), options);
795 
796  //create layer
797  try
798  {
799  te::qt::widgets::DataSet2Layer converter(outputDataSource->getId());
800 
801  te::da::DataSetTypePtr dt(outputDataSource->getDataSetType(dataSetName).release());
802 
803  te::map::AbstractLayerPtr layer = converter(dt);
804 
805  emit createNewLayer(layer);
806  }
807  catch(te::common::Exception& e)
808  {
809  QMessageBox::warning(this, tr("Query DataSource"), tr("Error creating layer. ") + e.what());
810  return;
811  }
812  QMessageBox::information(this, tr("Query DataSource"), tr("Layer created."));
813 }
814 
816 {
817  m_ui->m_newLayerNameLineEdit->clear();
818  m_ui->m_newLayerNameLineEdit->setEnabled(true);
819 
821  dlg.exec();
822 
823  std::list<te::da::DataSourceInfoPtr> dsPtrList = dlg.getSelecteds();
824 
825  if(dsPtrList.empty())
826  return;
827 
828  std::list<te::da::DataSourceInfoPtr>::iterator it = dsPtrList.begin();
829 
830  m_ui->m_repositoryLineEdit->setText(QString(it->get()->getTitle().c_str()));
831 
832  m_outputDatasource = *it;
833 
834  m_toFile = false;
835 }
836 
838 {
839  m_ui->m_newLayerNameLineEdit->clear();
840  m_ui->m_repositoryLineEdit->clear();
841 
842  QString fileName = QFileDialog::getSaveFileName(this, tr("Save as..."), QString(), tr("Shapefile (*.shp *.SHP);;"),0, QFileDialog::DontConfirmOverwrite);
843 
844  if (fileName.isEmpty())
845  return;
846 
847  boost::filesystem::path outfile(fileName.toStdString());
848 
849  m_ui->m_repositoryLineEdit->setText(outfile.string().c_str());
850 
851  m_ui->m_newLayerNameLineEdit->setText(outfile.leaf().string().c_str());
852 
853  m_ui->m_newLayerNameLineEdit->setEnabled(false);
854 
855  m_toFile = true;
856 }
TEDATAACCESSEXPORT DataSourcePtr GetDataSource(const std::string &datasourceId, const bool opened=true)
Search for a data source with the informed id in the DataSourceManager.
Definition: Utils.cpp:262
Geometric property.
te::da::SQLDialect * dialect
Definition: WFSDialect.h:1
void add(te::dt::Property *p)
It adds a property to the list of properties of the primary key.
Definition: PrimaryKey.h:123
te::qt::widgets::MapDisplay * m_appMapDisplay
boost::shared_ptr< DataSetType > DataSetTypePtr
Definition: DataSetType.h:653
An atomic property like an integer or double.
boost::shared_ptr< DataSource > DataSourcePtr
Definition: DataSource.h:1435
TEDATAACCESSEXPORT void AssociateDataSetTypeConverterSRID(DataSetTypeConverter *converter, const int &inputSRID, const int &outputSRID=TE_UNKNOWN_SRS)
Definition: Utils.cpp:670
A class that models the description of a dataset.
Definition: DataSetType.h:72
virtual const char * what() const
It outputs the exception message.
Definition: Exception.cpp:58
QueryDataSourceDialog(QWidget *parent=0, Qt::WindowFlags f=0)
virtual Property * clone() const =0
It returns a clone of the object.
It represents the SQL query dialect accepted by a given data source.
Definition: SQLDialect.h:55
std::string Convert2UCase(const std::string &value)
It converts a string to upper case.
Definition: StringUtils.h:166
te::qt::widgets::DataSetDisplay * m_dataSetDisplay
A widget to control the display of a set of layers.
Definition: MapDisplay.h:66
std::auto_ptr< Ui::QueryDataSourceDialogForm > m_ui
It models a property definition.
Definition: Property.h:59
An converter for DataSetType.
The type for arbitrary precison numbers, like numeric(p, q).
const std::vector< Property * > & getProperties() const
It returns the list of properties describing the CompositeProperty.
static DataSourceInfoManager & getInstance()
It returns a reference to the singleton instance.
This class represents a set of unique ids created in the same context. i.e. from the same data set...
Definition: ObjectIdSet.h:55
void setExpressionByInClause(const std::string source="")
te::qt::widgets::DataSetTableModel * m_tableModel
The type for string types: FIXED_STRING, VAR_STRING or STRING.
A map display for a dataset.
TEDATAACCESSEXPORT ObjectIdSet * GenerateOIDSet(DataSet *dataset, const DataSetType *type)
Definition: Utils.cpp:412
TEDATAACCESSEXPORT void GetDataSetNames(std::vector< std::string > &datasetNames, const std::string &datasourceId)
Definition: Utils.cpp:153
Q_DECLARE_METATYPE(te::map::AbstractLayerPtr)
This class is designed to declare objects to be thrown as exceptions by TerraLib. ...
Definition: Exception.h:58
void setLayerList(std::list< te::map::AbstractLayerPtr > layerList)
This method is used to set the list of layers.
const std::list< te::da::DataSourceInfoPtr > & getSelecteds() const
It describes a primary key (pk) constraint.
Definition: PrimaryKey.h:52
A dialog for selecting a data source.
void setAppMapDisplay(te::qt::widgets::MapDisplay *appMapDisplay)
A class that represents a data source component.
std::vector< std::string > getRegisteredNames() const
It gets the all registered names from registed functions.
Definition: SQLDialect.cpp:51
TEDATAACCESSEXPORT DataSetType * GetDataSetType(const std::string &name, const std::string &datasourceId)
Definition: Utils.cpp:228
A layer with reference to a dataset.
Definition: DataSetLayer.h:47
void onDataSetItemClicked(QListWidgetItem *item)
std::string Convert2String(boost::int16_t value)
It converts a short integer value to a string.
Definition: StringUtils.h:54
A table model representing a te::da::DataSet.
TEDATAACCESSEXPORT DataSetAdapter * CreateAdapter(DataSet *ds, DataSetTypeConverter *converter, bool isOwner=false)
Definition: Utils.cpp:644
boost::intrusive_ptr< AbstractLayer > AbstractLayerPtr
This file defines a class for a Query DataSource Dialog Dialog.
boost::shared_ptr< DataSourceInfo > DataSourceInfoPtr
An object that when created shows a cursor during its scope.
Definition: ScopedCursor.h:48
const std::string & getName() const
It returns the property name.
Definition: Property.h:127