spatialite improvements:

- support geometry column name
- remove unnecessary id field
- fix windows build
- better identifier quoting and utf-8 support
- update python binding
- fix some translation strings



git-svn-id: http://svn.osgeo.org/qgis/trunk@13250 c8812cc2-4d05-0410-92ff-de0c093fc19c
This commit is contained in:
jef 2010-04-05 17:16:25 +00:00
parent eaf30b211c
commit e1d82b1a82
12 changed files with 327 additions and 499 deletions

2
debian/control.sid vendored
View File

@ -8,7 +8,7 @@ Build-Depends: debhelper (>= 7), libgdal1-dev, libpq-dev,
sharutils, sip4 (>= 4.5), libqt4-core (>=4.4.0), libqt4-dev (>=4.4.0), libqt4-gui (>=4.4.0),
libqt4-sql (>=4.4.0), python-qt4 (>=4.1.0), python-qt4-dev (>=4.1.0),
python-sip4-dev (>= 4.5.0), libfontconfig1-dev, libxi-dev, libxrandr-dev, libxrender-dev, libice-dev,
libsm-dev, pyqt4-dev-tools, libqwt5-qt4-dev
libsm-dev, pyqt4-dev-tools, libqwt5-qt4-dev, libspatialite-dev
Build-Conflicts: libqgis-dev, qgis-dev
Standards-Version: 3.8.4
XS-Python-Version: current

View File

@ -133,6 +133,10 @@ static void qtgui_UpdatePyArgv(PyObject *argvlist, int argc, char **argv)
//! Returns the path to the master qgis.db file.
static const QString qgisMasterDbFilePath();
//! Returns the path to the spatialite template db file.
//! @note added in 1.5
static const QString qgisSpatialiteDbTemplatePath();
//! Returns the path to the settings directory in user's home dir
static const QString qgisSettingsDirPath();

View File

@ -213,6 +213,11 @@
#include "postgres/qgspgsourceselect.h"
#endif
#ifdef HAVE_SPATIALITE
extern "C"
{
#include <sqlite3.h>
#include <spatialite.h>
}
#include "qgsspatialitesourceselect.h"
#include "qgsnewspatialitelayerdialog.h"
#endif
@ -937,15 +942,15 @@ void QgisApp::createActions()
// Layer Menu Items
mActionNewVectorLayer = new QAction( getThemeIcon( "mActionNewVectorLayer.png" ), tr( "New Vector Layer (shapefile)..." ), this );
shortcuts->registerAction( mActionNewVectorLayer, tr( "Ctrl+Shift+N", "Create a New Vector Layer (shapefile)" ) );
mActionNewVectorLayer->setStatusTip( tr( "Create a New Vector Layer (shapefile)" ) );
mActionNewVectorLayer = new QAction( getThemeIcon( "mActionNewVectorLayer.png" ), tr( "New Shapefile Layer..." ), this );
shortcuts->registerAction( mActionNewVectorLayer, tr( "Ctrl+Shift+N", "Create a New Shapefile layer" ) );
mActionNewVectorLayer->setStatusTip( tr( "Create a New Shapefile layer" ) );
connect( mActionNewVectorLayer, SIGNAL( triggered() ), this, SLOT( newVectorLayer() ) );
#ifdef HAVE_SPATIALITE
mActionNewSpatialiteLayer = new QAction( getThemeIcon( "mActionNewVectorLayer.png" ), tr( "New Spatialite Layer ..." ), this );
shortcuts->registerAction( mActionNewSpatialiteLayer, tr( "Ctrl+Shift+S", "Create a New Spatialite Layer " ) );
mActionNewSpatialiteLayer->setStatusTip( tr( "Create a New Spatialite Layer " ) );
mActionNewSpatialiteLayer = new QAction( getThemeIcon( "mActionNewVectorLayer.png" ), tr( "New SpatiaLite Layer ..." ), this );
shortcuts->registerAction( mActionNewSpatialiteLayer, tr( "Ctrl+Shift+S", "Create a New SpatiaLite Layer " ) );
mActionNewSpatialiteLayer->setStatusTip( tr( "Create a New SpatiaLite Layer " ) );
connect( mActionNewSpatialiteLayer, SIGNAL( triggered() ), this, SLOT( newSpatialiteLayer() ) );
#endif
@ -1420,13 +1425,13 @@ void QgisApp::createMenus()
mLayerMenu = menuBar()->addMenu( tr( "&Layer" ) );
#ifdef HAVE_SPATIALITE
QMenu *newLayerMenu = mLayerMenu->addMenu( tr( "New ") );
QMenu *newLayerMenu = mLayerMenu->addMenu( tr( "New" ) );
newLayerMenu->addAction( mActionNewVectorLayer );
newLayerMenu->addAction( mActionNewSpatialiteLayer );
#else
mLayerMenu->addAction( mActionNewVectorLayer );
#endif
mLayerMenu->addAction( mActionAddOgrLayer );
mLayerMenu->addAction( mActionAddRasterLayer );
#ifdef HAVE_POSTGRESQL
@ -3097,6 +3102,18 @@ void QgisApp::newVectorLayer()
addVectorLayers( fileNames, enc, "file" );
}
static QString quotedIdentifier( QString id )
{
id.replace( "\"", "\"\"" );
return id.prepend( "\"" ).append( "\"" );
}
static QString quotedValue( QString value )
{
value.replace( "'", "''" );
return value.prepend( "'" ).append( "'" );
}
void QgisApp::newSpatialiteLayer()
{
if ( mMapCanvas && mMapCanvas->isDrawing() )
@ -3115,6 +3132,7 @@ void QgisApp::newSpatialiteLayer()
QString crsId = spatialiteDialog.selectedCrsId();
QString databaseName = spatialiteDialog.databaseName();
QString newLayerName = spatialiteDialog.layerName();
QString newGeometryColumn = spatialiteDialog.geometryColumn();
//QgsDebugMsg( QString( "New file format will be: %1" ).arg( fileformat ) );
// Get the list containing the name/type pairs for each attribute
@ -3122,188 +3140,95 @@ void QgisApp::newSpatialiteLayer()
// Build up the sql statement for creating the table
//
QString sql = QString("create table %1 (id integer primary key autoincrement").arg(newLayerName);
QString sql = QString( "create table %1(" ).arg( quotedIdentifier( newLayerName ) );
// iterate through the field names and add them to the create statement
// (use indexed access since this is just as fast as iterators
for ( int i = 0; i < items->size(); ++i )
for ( int i = 0; i < items->size(); ++i )
{
QStringList field = items->at(i);
sql += QString(", %1 %2").arg(field.at(0)).arg(field.at(1));
QStringList field = items->at( i );
if ( i > 0 )
sql += ",";
sql += QString( "%1 %2" ).arg( quotedIdentifier( field.at( 0 ) ) ).arg( field.at( 1 ) );
}
// complete the create table statement
sql += ")";
std::cout << "Creating table in database " << databaseName.toUtf8().data() << std::endl;
std::cout << sql.toUtf8().data() << std::endl; // OK
QgsDebugMsg( QString( "Creating table in database %1" ).arg( databaseName ) );
QgsDebugMsg( sql ); // OK
QString sqlAddGeom = QString("select AddGeometryColumn('%1', 'geom', %2, '%3', 2)").arg(newLayerName).arg(crsId).arg(geometrytype);
std::cout << sqlAddGeom.toUtf8().data() << std::endl; // OK
QString sqlCreateIndex = QString("select CreateSpatialIndex('%1', 'geom')").arg(newLayerName);
std::cout << sqlCreateIndex.toUtf8().data() << std::endl; // OK
QString sqlAddGeom = QString( "select AddGeometryColumn(%1,%2,%3,%4,2)" )
.arg( quotedValue( newLayerName ) )
.arg( quotedValue( newGeometryColumn ) )
.arg( crsId )
.arg( quotedValue( geometrytype ) );
QgsDebugMsg( sqlAddGeom ); // OK
QString sqlCreateIndex = QString( "select CreateSpatialIndex(%1,%2)" ).arg( quotedValue( newLayerName ) ).arg( quotedValue( newGeometryColumn ) );
QgsDebugMsg( sqlCreateIndex ); // OK
spatialite_init( 0 );
sqlite3 *db;
int rc = sqlite3_open( databaseName.toUtf8(), &db );
if ( rc != SQLITE_OK )
{
QMessageBox::warning( this, "Spatialite Database", tr( "Unable to open the database: %1").arg(databaseName ) );
QMessageBox::warning( this,
tr( "SpatiaLite Database" ),
tr( "Unable to open the database: %1" ).arg( databaseName ) );
}
else
{
char * errmsg;
rc = sqlite3_exec( db, sql.toUtf8(), NULL, NULL, &errmsg);
rc = sqlite3_exec( db, sql.toUtf8(), NULL, NULL, &errmsg );
if ( rc != SQLITE_OK )
{
QMessageBox::warning( this, tr( "Error deleting bookmark" ),
tr( "Failed to create the Spatialite table %1. The database returned:\n%2" ).arg( newLayerName ).arg( errmsg ) );
QMessageBox::warning( this,
tr( "Error Creating SpatiaLite Table" ),
tr( "Failed to create the SpatiaLite table %1. The database returned:\n%2" ).arg( newLayerName ).arg( errmsg ) );
sqlite3_free( errmsg );
}
else
{
// create the geometry column and the spatial index
rc = sqlite3_exec( db, sqlAddGeom.toUtf8(), NULL, NULL, &errmsg);
rc = sqlite3_exec( db, sqlAddGeom.toUtf8(), NULL, NULL, &errmsg );
if ( rc != SQLITE_OK )
{
QMessageBox::warning( this, tr( "Error Creating Geometry Column" ),
tr( "Failed to create the geometry column. The database returned:\n%1" ).arg( errmsg ) );
QMessageBox::warning( this,
tr( "Error Creating Geometry Column" ),
tr( "Failed to create the geometry column. The database returned:\n%1" ).arg( errmsg ) );
sqlite3_free( errmsg );
}
else
{
// create the spatial index
rc = sqlite3_exec( db, sqlCreateIndex.toUtf8(), NULL, NULL, &errmsg);
if ( rc != SQLITE_OK )
{
QMessageBox::warning( this, tr( "Error Creating Spatial Index" ),
tr( "Failed to create the spatial index. The database returned:\n%1" ).arg( errmsg ) );
sqlite3_free( errmsg );
}
// create the spatial index
rc = sqlite3_exec( db, sqlCreateIndex.toUtf8(), NULL, NULL, &errmsg );
if ( rc != SQLITE_OK )
{
QMessageBox::warning( this,
tr( "Error Creating Spatial Index" ),
tr( "Failed to create the spatial index. The database returned:\n%1" ).arg( errmsg ) );
sqlite3_free( errmsg );
}
QgsVectorLayer *layer = new QgsVectorLayer( QString( "dbname=%1 table=%2(%3) sql=" )
.arg( databaseName )
.arg( newLayerName )
.arg( newGeometryColumn ), newLayerName, "spatialite" );
if ( layer->isValid() )
{
// register this layer with the central layers registry
QgsMapLayerRegistry::instance()->addMapLayer( layer );
}
else
{
QgsDebugMsg( newLayerName + " is an invalid layer - not loaded" );
QMessageBox::critical( this, tr( "Invalid Layer" ), tr( "%1 is an invalid layer and cannot be loaded." ).arg( newLayerName ) );
delete layer;
}
}
}
}
/*
bool haveLastUsedFilter = false; // by default, there is no last
// used filter
QString enc;
QString fileName;
QSettings settings; // where we keep last used filter in
// persistent state
haveLastUsedFilter = settings.contains( "/UI/lastVectorFileFilter" );
QString lastUsedFilter = settings.value( "/UI/lastVectorFileFilter",
QVariant( QString::null ) ).toString();
QString lastUsedDir = settings.value( "/UI/lastVectorFileFilterDir",
"." ).toString();
QgsDebugMsg( "Saving vector file dialog without filters: " );
QgsEncodingFileDialog* openFileDialog = new QgsEncodingFileDialog( this,
tr( "Save As" ), lastUsedDir, "", QString( "" ) );
// allow for selection of more than one file
openFileDialog->setFileMode( QFileDialog::AnyFile );
openFileDialog->setAcceptMode( QFileDialog::AcceptSave );
openFileDialog->setConfirmOverwrite( true );
if ( haveLastUsedFilter ) // set the filter to the last one used
{
openFileDialog->selectFilter( lastUsedFilter );
}
int res;
while (( res = openFileDialog->exec() ) == QDialog::Accepted )
{
fileName = openFileDialog->selectedFiles().first();
if ( fileformat == "ESRI Shapefile" )
{
if ( !isValidShapeFileName( fileName ) )
{
fileName += ".shp";
}
if ( !isValidShapeFileName( fileName ) )
{
QMessageBox::information( this,
tr( "New Shapefile" ),
tr( "Shapefiles must end on .shp" ) );
continue;
}
}
break;
}
if ( res == QDialog::Rejected )
{
delete openFileDialog;
return;
}
enc = openFileDialog->encoding();
// If the file exists, delete it otherwise we'll end up loading that
// file, which can cause problems (e.g., if the file contains
// linestrings, but we're wanting to create points, we'll end up
// with a linestring file).
if ( fileformat == "ESRI Shapefile" )
{
QgsVectorFileWriter::deleteShapeFile( fileName );
}
else
{
QFile::remove( fileName );
}
settings.setValue( "/UI/lastVectorFileFilter", openFileDialog->selectedFilter() );
settings.setValue( "/UI/lastVectorFileFilterDir", openFileDialog->directory().absolutePath() );
delete openFileDialog;
//try to create the new layer with OGRProvider instead of QgsVectorFileWriter
QgsProviderRegistry * pReg = QgsProviderRegistry::instance();
QString ogrlib = pReg->library( "ogr" );
// load the data provider
QLibrary* myLib = new QLibrary( ogrlib );
bool loaded = myLib->load();
if ( loaded )
{
QgsDebugMsg( "ogr provider loaded" );
typedef bool ( *createEmptyDataSourceProc )( const QString&, const QString&, const QString&, QGis::WkbType,
const std::list<std::pair<QString, QString> >&, const QgsCoordinateReferenceSystem * );
createEmptyDataSourceProc createEmptyDataSource = ( createEmptyDataSourceProc ) cast_to_fptr( myLib->resolve( "createEmptyDataSource" ) );
if ( createEmptyDataSource )
{
if ( geometrytype != QGis::WKBUnknown )
{
QgsCoordinateReferenceSystem srs( crsId, QgsCoordinateReferenceSystem::InternalCrsId );
createEmptyDataSource( fileName, fileformat, enc, geometrytype, attributes, &srs );
}
else
{
QgsDebugMsg( "geometry type not recognised" );
return;
}
}
else
{
QgsDebugMsg( "Resolving newEmptyDataSource(...) failed" );
}
}
//then add the layer to the view
QStringList fileNames;
fileNames.append( fileName );
//todo: the last parameter will change accordingly to layer type
addVectorLayers( fileNames, enc, "file" );
*/
}
void QgisApp::fileOpen()
{
if ( mMapCanvas && mMapCanvas->isDrawing() )
@ -5026,6 +4951,7 @@ void QgisApp::loadPythonSupport()
mActionPluginSeparator2 = mPluginMenu->addSeparator();
mPluginMenu->addAction( mActionShowPythonDialog );
std::cout << "Python support ENABLED :-) " << std::endl; // OK
}
}

View File

@ -18,20 +18,14 @@
***************************************************************************/
/* $Id$ */
/*
extern "C"
{
#include <spatialite/sqlite3.h>
#include <spatialite/gaiageo.h>
#include <spatialite.h>
}
*/
#include "qgsnewspatialitelayerdialog.h"
#include "qgsspatialitesridsdialog.h"
#include "qgsapplication.h"
#include "qgisapp.h" // <- for theme icons
#include "qgslogger.h"
//#include <sqlite3.h>
#include <QPushButton>
#include <QSettings>
#include <QLineEdit>
@ -66,10 +60,9 @@ QgsNewSpatialiteLayerDialog::QgsNewSpatialiteLayerDialog( QWidget *parent, Qt::W
++it;
}
settings.endGroup();
mApplyButton = buttonBox->button( QDialogButtonBox::Apply );
mApplyButton->setEnabled( false );
mApplyButton->setDefault( true );
connect( buttonBox->button( QDialogButtonBox::Apply ), SIGNAL( clicked() ), this, SLOT( apply() ) );
mOkButton = buttonBox->button( QDialogButtonBox::Ok );
mOkButton->setEnabled( false );
mOkButton->setDefault( true );
// Set the SRID box to a default of WGS84
leSRID->setText( "4326" );
@ -85,17 +78,17 @@ QgsNewSpatialiteLayerDialog::~QgsNewSpatialiteLayerDialog()
void QgsNewSpatialiteLayerDialog::createNewDb()
{
// QMessageBox::information( 0, tr( "Spatialite Layer" ), tr( "Create new db clicked" ) );
QString fileName = QFileDialog::getSaveFileName(this, tr("New Spatialite Database File"),
".",
tr("Spatialite (*.sqlite *.db )"));
QString fileName = QFileDialog::getSaveFileName( this, tr( "New SpatiaLite Database File" ),
".",
tr( "SpatiaLite (*.sqlite *.db )" ) );
if ( !fileName.isEmpty() )
{
mDatabaseComboBox->insertItem( 0, fileName );
mDatabaseComboBox->setCurrentIndex(0);
mDatabaseComboBox->setCurrentIndex( 0 );
createDb();
needNewDb = true;
}
}
}
void QgsNewSpatialiteLayerDialog::on_mTypeBox_currentIndexChanged( int index )
{
@ -136,6 +129,9 @@ QString QgsNewSpatialiteLayerDialog::selectedType() const
{
return "MULTIPOLYGON";
}
Q_ASSERT( "no type selected" == 0 );
return "";
}
QString QgsNewSpatialiteLayerDialog::selectedCrsId() const
@ -143,67 +139,11 @@ QString QgsNewSpatialiteLayerDialog::selectedCrsId() const
return leSRID->text();
}
void QgsNewSpatialiteLayerDialog::apply()
{
// Check to see if the db exists and if not create it
createDb();
// Init spatialite
spatialite_init( 0 );
QString newLayerName = leLayerName->text();
int rc = sqlite3_open_v2( mDatabaseComboBox->currentText().toUtf8(), &db, SQLITE_OPEN_READWRITE, NULL );
if ( rc != SQLITE_OK )
{
QMessageBox::warning( this, "Spatialite Database", tr( "Unable to open the database"));
}
else
{
char * errmsg;
QString sql = QString("CREATE TABLE %1 (id integer primary key autoincrement, name text)").arg( newLayerName );
rc = sqlite3_exec( db, sql.toUtf8(), NULL, NULL, &errmsg);
if ( rc != SQLITE_OK )
{
QMessageBox::warning( this, tr( "Error Creating Table" ),
tr( "Failed to create the Spatialite table. The database returned:\n%1" ).arg( errmsg ) );
sqlite3_free( errmsg );
}
else
{
// get the geometry type
QString geomType = selectedType();
// create the geometry column and the spatial index
sql = QString("select AddGeometryColumn('%1', 'geom', %2, '%3', 2)").arg( newLayerName ).arg( leSRID->text() ).arg( geomType );
rc = sqlite3_exec( db, sql.toUtf8(), NULL, NULL, &errmsg);
if ( rc != SQLITE_OK )
{
QMessageBox::warning( this, tr( "Error Creating Geometry Column" ),
tr( "Failed to create the geometry column. The database returned:\n%1" ).arg( errmsg ) );
sqlite3_free( errmsg );
}
else
{
// create the spatial index
sql = QString("select CreateSpatialIndex('%1', 'geom')").arg( newLayerName );
rc = sqlite3_exec( db, sql.toUtf8(), NULL, NULL, &errmsg);
if ( rc != SQLITE_OK )
{
QMessageBox::warning( this, tr( "Error Creating Spatial Index" ),
tr( "Failed to create the spatial index. The database returned:\n%1" ).arg( errmsg ) );
sqlite3_free( errmsg );
}
else
{
QMessageBox::information( 0, tr( "Spatialite Layer" ), tr( "Layer created" ) );
}
}
}
}
}
void QgsNewSpatialiteLayerDialog::on_leLayerName_textChanged( QString text )
{
if ( leLayerName->text().length() > 0 && mAttributeView->topLevelItemCount() > 0)
if ( leLayerName->text().length() > 0 && mAttributeView->topLevelItemCount() > 0 )
{
mApplyButton->setEnabled( true );
mOkButton->setEnabled( true );
}
}
@ -214,10 +154,10 @@ void QgsNewSpatialiteLayerDialog::on_mAddAttributeButton_clicked()
QString myName = mNameEdit->text();
//use userrole to avoid translated type string
QString myType = mTypeBox->itemData( mTypeBox->currentIndex(), Qt::UserRole ).toString();
mAttributeView->addTopLevelItem( new QTreeWidgetItem( QStringList() << myName << myType ) );
mAttributeView->addTopLevelItem( new QTreeWidgetItem( QStringList() << myName << myType ) );
if ( mAttributeView->topLevelItemCount() > 0 && leLayerName->text().length() > 0 )
{
mApplyButton->setEnabled( true );
mOkButton->setEnabled( true );
}
mNameEdit->clear();
}
@ -228,7 +168,7 @@ void QgsNewSpatialiteLayerDialog::on_mRemoveAttributeButton_clicked()
delete mAttributeView->currentItem();
if ( mAttributeView->topLevelItemCount() == 0 )
{
mApplyButton->setEnabled( false );
mOkButton->setEnabled( false );
}
}
@ -238,11 +178,11 @@ void QgsNewSpatialiteLayerDialog::on_pbnFindSRID_clicked()
int rc = sqlite3_open( mDatabaseComboBox->currentText().toUtf8().data(), &db );
if ( rc != SQLITE_OK )
{
QMessageBox::warning( this, "Spatialite Database", tr( "Unable to open the database: %1").arg(mDatabaseComboBox->currentText() ) );
QMessageBox::warning( this, tr( "Spatialite Database" ), tr( "Unable to open the database: %1").arg(mDatabaseComboBox->currentText() ) );
}
*/
// set the SRID from a list returned from the selected Spatialite database
QgsSpatialiteSridsDialog *sridDlg = new QgsSpatialiteSridsDialog(this);
QgsSpatialiteSridsDialog *sridDlg = new QgsSpatialiteSridsDialog( this );
if ( sridDlg->load( mDatabaseComboBox->currentText() ) )
{
if ( sridDlg->exec() )
@ -255,7 +195,7 @@ void QgsNewSpatialiteLayerDialog::on_pbnFindSRID_clicked()
}
}
// Create a QList of QStringList objects that define the layer attributes.
// Create a QList of QStringList objects that define the layer attributes.
// Each QStringList contains the field name and its type.
QList<QStringList> * QgsNewSpatialiteLayerDialog::attributes() const
{
@ -267,8 +207,8 @@ QList<QStringList> * QgsNewSpatialiteLayerDialog::attributes() const
QStringList items;
items << item->text( 0 );
items << item->text( 1 );
list->append(items);
list->append( items );
//QString type = QString( "%1;%2;%3" ).arg( item->text( 1 ) ).arg( item->text( 2 ) ).arg( item->text( 3 ) );
//at.push_back( std::make_pair( item->text( 0 ), type ) );
//QgsDebugMsg( QString( "appending %1//%2" ).arg( item->text( 0 ) ).arg( type ) );
@ -286,6 +226,12 @@ QString QgsNewSpatialiteLayerDialog::layerName() const
{
return leLayerName->text();
}
QString QgsNewSpatialiteLayerDialog::geometryColumn() const
{
return leGeometryColumn->text();
}
bool QgsNewSpatialiteLayerDialog::createDb()
{
QFile newDb( mDatabaseComboBox->currentText() );
@ -298,28 +244,24 @@ bool QgsNewSpatialiteLayerDialog::createDb()
QFileInfo fullPath = QFileInfo( mDatabaseComboBox->currentText() );
QDir path = fullPath.dir();
qWarning("making this dir: %s", path.absolutePath().toUtf8().data());
qWarning( "making this dir: %s", path.absolutePath().toUtf8().data() );
// Must be sure there is destination directory ~/.qgis
QDir().mkpath( path.absolutePath( ) );
qWarning("Copying %s ", spatialiteTemplate.toUtf8().data());
qWarning("to %s", newDb.fileName().toUtf8().data());
qWarning( "Copying %s ", spatialiteTemplate.toUtf8().data() );
qWarning( "to %s", newDb.fileName().toUtf8().data() );
//now copy the template db file into the chosen location
bool isDbFileCopied = spatialiteTemplateDb.copy( newDb.fileName() );
if ( !isDbFileCopied )
if ( !spatialiteTemplateDb.copy( newDb.fileName() ) )
{
// QMessageBox::warning( this, "Spatialite Database", tr( "Unable to copy the template database to your new location" ));
QMessageBox::warning( 0, tr( "SpatiaLite Database" ), tr( "Could not copy the template database to new location" ) );
return false;
}
else
{
QMessageBox::information( 0, tr( "Spatialite Database" ), tr( "Created new database!" ) );
QMessageBox::information( 0, tr( "SpatiaLite Database" ), tr( "Created new database!" ) );
}
}
return true;
return true;
}

View File

@ -1,7 +1,7 @@
/***************************************************************************
QgsNewSpatialiteLayerDialog.h - description
-------------------
begin : 2010-03-19
begin : 2010-03-19
copyright : (C) 2010 by Gary Sherman
email : gsherman@mrcc.com
***************************************************************************/
@ -17,18 +17,18 @@
/* $Id$ */
#ifndef qgsnewspatialitelayerdialog_H
#define qgsnewspatialitelayerdialog_H
#include <sqlite3.h>
extern "C"
{
#include <spatialite/headers/spatialite.h>
}
//#include <sqlite3.h>
#include "ui_qgsnewspatialitelayerdialogbase.h"
#include "qgisgui.h"
#include "qgscontexthelp.h"
#include "qgis.h"
extern "C"
{
#include <sqlite3.h>
}
class QgsNewSpatialiteLayerDialog: public QDialog, private Ui::QgsNewSpatialiteLayerDialogBase
{
Q_OBJECT
@ -45,6 +45,8 @@ class QgsNewSpatialiteLayerDialog: public QDialog, private Ui::QgsNewSpatialiteL
QString databaseName() const;
/**Returns the layer name to be created */
QString layerName() const;
/**Returns the geometry column name */
QString geometryColumn() const;
/**Returns the selected crs id*/
QString selectedCrsId() const;
/** Create a new database */
@ -57,11 +59,11 @@ class QgsNewSpatialiteLayerDialog: public QDialog, private Ui::QgsNewSpatialiteL
void on_pbnFindSRID_clicked();
void on_leLayerName_textChanged( QString text );
void createNewDb();
void apply();
void on_buttonBox_helpRequested() { QgsContextHelp::run( metaObject()->className() ); }
private:
QPushButton *mApplyButton;
QPushButton *mOkButton;
int mCrsId;
sqlite3 *db;
bool needNewDb;

View File

@ -300,7 +300,7 @@ void QgsSpatiaLiteSourceSelect::on_btnNew_clicked()
QString myFile = QFileDialog::getOpenFileName( this,
tr( "Choose a SpatiaLite/SQLite DB to open" ),
lastUsedDir, QObject::tr( "SQLite DB (*.sqlite);;All files (*.*)" ) );
lastUsedDir, QObject::tr( "SQLite DB (*.sqlite *.db);;All files (*.*)" ) );
if ( myFile.isEmpty() )
return;
@ -507,8 +507,8 @@ bool QgsSpatiaLiteSourceSelect::getTableInfo( sqlite3 * handle )
{
for ( i = 1; i <= rows; i++ )
{
QString tableName = results[( i * columns ) + 0];
QString column = results[( i * columns ) + 1];
QString tableName = QString::fromUtf8( results[( i * columns ) + 0] );
QString column = QString::fromUtf8( results[( i * columns ) + 1] );
QString type = results[( i * columns ) + 2];
if ( isDeclaredHidden( handle, tableName, column ) )
continue;
@ -534,8 +534,8 @@ bool QgsSpatiaLiteSourceSelect::getTableInfo( sqlite3 * handle )
{
for ( i = 1; i <= rows; i++ )
{
QString tableName = results[( i * columns ) + 0];
QString column = results[( i * columns ) + 1];
QString tableName = QString::fromUtf8( results[( i * columns ) + 0] );
QString column = QString::fromUtf8( results[( i * columns ) + 1] );
QString type = results[( i * columns ) + 2];
if ( isDeclaredHidden( handle, tableName, column ) )
continue;
@ -561,8 +561,8 @@ bool QgsSpatiaLiteSourceSelect::getTableInfo( sqlite3 * handle )
{
for ( i = 1; i <= rows; i++ )
{
QString tableName = results[( i * columns ) + 0];
QString column = results[( i * columns ) + 1];
QString tableName = QString::fromUtf8( results[( i * columns ) + 0] );
QString column = QString::fromUtf8( results[( i * columns ) + 1] );
QString type = results[( i * columns ) + 2];
if ( isDeclaredHidden( handle, tableName, column ) )
continue;

View File

@ -19,7 +19,7 @@
#include <QMessageBox>
#include "qgsspatialitesridsdialog.h"
QgsSpatialiteSridsDialog::QgsSpatialiteSridsDialog( QWidget *parent, Qt::WFlags fl )
: QDialog( parent, fl )
: QDialog( parent, fl )
{
setupUi( this );
db = 0;
@ -29,13 +29,13 @@ QgsSpatialiteSridsDialog::QgsSpatialiteSridsDialog( QWidget *parent, Qt::WFlags
QgsSpatialiteSridsDialog::~QgsSpatialiteSridsDialog()
{
sqlite3_close( db );
sqlite3_close( db );
}
QString QgsSpatialiteSridsDialog::selectedSrid()
{
return twSrids->currentItem()->text(0);
return twSrids->currentItem()->text( 0 );
}
bool QgsSpatialiteSridsDialog::load(QString dbName)
bool QgsSpatialiteSridsDialog::load( QString dbName )
{
mDbName = dbName;
bool status = true;
@ -44,43 +44,43 @@ bool QgsSpatialiteSridsDialog::load(QString dbName)
int rc = sqlite3_open_v2( dbName.toUtf8(), &db, SQLITE_OPEN_READONLY, NULL );
if ( rc != SQLITE_OK )
{
QMessageBox::warning( this, "Spatialite Database", tr( "Unable to open the database"));
QMessageBox::warning( this, tr( "SpatiaLite Database" ), tr( "Unable to open the database" ) );
return false;
}
}
// load up the srid table
// prepare the sql statement
const char *pzTail;
sqlite3_stmt *ppStmt;
QString sql = "select auth_srid, auth_name, ref_sys_name from spatial_ref_sys order by srid asc";
// load up the srid table
// prepare the sql statement
const char *pzTail;
sqlite3_stmt *ppStmt;
QString sql = "select auth_srid, auth_name, ref_sys_name from spatial_ref_sys order by srid asc";
int rc = sqlite3_prepare( db, sql.toUtf8(), sql.toUtf8().length(), &ppStmt, &pzTail );
// XXX Need to free memory from the error msg if one is set
if ( rc == SQLITE_OK )
int rc = sqlite3_prepare( db, sql.toUtf8(), sql.toUtf8().length(), &ppStmt, &pzTail );
// XXX Need to free memory from the error msg if one is set
if ( rc == SQLITE_OK )
{
// get the first row of the result set
while ( sqlite3_step( ppStmt ) == SQLITE_ROW )
{
// get the first row of the result set
while ( sqlite3_step( ppStmt ) == SQLITE_ROW )
{
QTreeWidgetItem *item = new QTreeWidgetItem( twSrids );
// srid
item->setText (0, QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 0 ) ) );
item->setText (1, QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 1 ) ) );
// name
item->setText( 2, QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 2 ) ) );
// proj4 text
item->setText( 3, QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 3 ) ) );
QTreeWidgetItem *item = new QTreeWidgetItem( twSrids );
// srid
item->setText( 0, QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 0 ) ) );
item->setText( 1, QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 1 ) ) );
// name
item->setText( 2, QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 2 ) ) );
// proj4 text
item->setText( 3, QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 3 ) ) );
}
twSrids->sortByColumn( 0, Qt::AscendingOrder );
}
else
{
// XXX query failed -- warn the user some how
QMessageBox::warning(0, "Error", QString( "Failed to load SRIDS: %1" ).arg( sqlite3_errmsg( db ) ) );
status = false;
}
// close the statement
sqlite3_finalize( ppStmt );
twSrids->sortByColumn( 0, Qt::AscendingOrder );
}
else
{
// XXX query failed -- warn the user some how
QMessageBox::warning( 0, tr( "Error" ), tr( "Failed to load SRIDS: %1" ).arg( sqlite3_errmsg( db ) ) );
status = false;
}
// close the statement
sqlite3_finalize( ppStmt );
return status;
}
void QgsSpatialiteSridsDialog::on_pbnFilter_clicked()
@ -102,7 +102,7 @@ void QgsSpatialiteSridsDialog::on_pbnFilter_clicked()
{
search = "ref_sys_name";
}
QString sql = QString("select auth_srid, auth_name, ref_sys_name from spatial_ref_sys where %1 like '%").arg(search) + leSearch->text() + QString("%' order by srid asc");
QString sql = QString( "select auth_srid, auth_name, ref_sys_name from spatial_ref_sys where %1 like '%" ).arg( search ) + leSearch->text() + QString( "%' order by srid asc" );
//QMessageBox::information(0, "Sql", sql);
int rc = sqlite3_prepare( db, sql.toUtf8(), sql.toUtf8().length(), &ppStmt, &pzTail );
@ -116,8 +116,8 @@ void QgsSpatialiteSridsDialog::on_pbnFilter_clicked()
{
QTreeWidgetItem *item = new QTreeWidgetItem( twSrids );
// srid
item->setText (0, QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 0 ) ) );
item->setText (1, QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 1 ) ) );
item->setText( 0, QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 0 ) ) );
item->setText( 1, QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 1 ) ) );
// name
item->setText( 2, QString::fromUtf8(( const char * )sqlite3_column_text( ppStmt, 2 ) ) );
// proj4 text
@ -129,7 +129,7 @@ void QgsSpatialiteSridsDialog::on_pbnFilter_clicked()
else
{
// XXX query failed -- warn the user some how
QMessageBox::warning(0, "Error", QString( "Failed to load SRIDS: %1" ).arg( sqlite3_errmsg( db ) ) );
QMessageBox::warning( 0, tr( "Error" ), tr( "Failed to load SRIDS: %1" ).arg( sqlite3_errmsg( db ) ) );
}
// close the statement
sqlite3_finalize( ppStmt );

View File

@ -23,20 +23,24 @@
#include "qgscontexthelp.h"
#include "qgis.h"
#include <sqlite3.h>
class QgsSpatialiteSridsDialog: public QDialog, private Ui::QgsSpatialiteSridsDialogBase
extern "C"
{
Q_OBJECT
public:
QgsSpatialiteSridsDialog( QWidget *parent = 0, Qt::WFlags fl = QgisGui::ModalDialogFlags);
~QgsSpatialiteSridsDialog();
bool load(QString dbName);
QString selectedSrid();
public slots:
void on_pbnFilter_clicked();
private:
sqlite3 *db;
QString mDbName;
#include <sqlite3.h>
}
class QgsSpatialiteSridsDialog: public QDialog, private Ui::QgsSpatialiteSridsDialogBase
{
Q_OBJECT
public:
QgsSpatialiteSridsDialog( QWidget *parent = 0, Qt::WFlags fl = QgisGui::ModalDialogFlags );
~QgsSpatialiteSridsDialog();
bool load( QString dbName );
QString selectedSrid();
public slots:
void on_pbnFilter_clicked();
private:
sqlite3 *db;
QString mDbName;
};
#endif //QgsSpatialiteSridsDialog_H

View File

@ -90,6 +90,7 @@ class CORE_EXPORT QgsApplication: public QApplication
static const QString qgisMasterDbFilePath();
//! Returns the path to the spatialite template db file.
//! @note added in 1.5
static const QString qgisSpatialiteDbTemplatePath();
//! Returns the path to the settings directory in user's home dir

View File

@ -14,8 +14,6 @@ email : a.furieri@lqt.it
* *
***************************************************************************/
#include <cassert>
#include <qgis.h>
#include <qgsapplication.h>
#include <qgsfeature.h>
@ -41,8 +39,14 @@ const QString SPATIALITE_DESCRIPTION = "SpatiaLite data provider";
QMap < QString, QgsSpatiaLiteProvider::SqliteHandles * >QgsSpatiaLiteProvider::SqliteHandles::handles;
QgsSpatiaLiteProvider::QgsSpatiaLiteProvider( QString const &uri ): QgsVectorDataProvider( uri ),
geomType( QGis::WKBUnknown ), sqliteHandle( NULL ), sqliteStatement( NULL ), mSrid( -1 ), spatialIndexRTree( false ), spatialIndexMbrCache( false )
QgsSpatiaLiteProvider::QgsSpatiaLiteProvider( QString const &uri )
: QgsVectorDataProvider( uri )
, geomType( QGis::WKBUnknown )
, sqliteHandle( NULL )
, sqliteStatement( NULL )
, mSrid( -1 )
, spatialIndexRTree( false )
, spatialIndexMbrCache( false )
{
QgsDataSourceURI anUri = QgsDataSourceURI( uri );
@ -69,7 +73,7 @@ QgsSpatiaLiteProvider::QgsSpatiaLiteProvider( QString const &uri ): QgsVectorDat
numberFeatures = 0;
valid = false;
QgsLogger::critical( "Invalid SpatiaLite layer" );
QgsDebugMsg( "Invalid SpatiaLite layer" );
closeDb();
return;
}
@ -90,7 +94,7 @@ QgsSpatiaLiteProvider::QgsSpatiaLiteProvider( QString const &uri ): QgsVectorDat
numberFeatures = 0;
valid = false;
QgsLogger::critical( "Invalid SpatiaLite layer" );
QgsDebugMsg( "Invalid SpatiaLite layer" );
closeDb();
return;
}
@ -99,7 +103,7 @@ QgsSpatiaLiteProvider::QgsSpatiaLiteProvider( QString const &uri ): QgsVectorDat
numberFeatures = 0;
valid = false;
QgsLogger::critical( "Invalid SpatiaLite layer" );
QgsDebugMsg( "Invalid SpatiaLite layer" );
closeDb();
return;
}
@ -109,7 +113,7 @@ QgsSpatiaLiteProvider::QgsSpatiaLiteProvider( QString const &uri ): QgsVectorDat
{
valid = false;
QgsLogger::critical( "Invalid SpatiaLite layer" );
QgsDebugMsg( "Invalid SpatiaLite layer" );
return;
}
//fill type names into sets
@ -171,7 +175,9 @@ void QgsSpatiaLiteProvider::loadFields()
if ( strcasecmp( type, "int" ) == 0 ||
strcasecmp( type, "integer" ) == 0 ||
strcasecmp( type, "bigint" ) == 0 ||
strcasecmp( type, "smallint" ) == 0 || strcasecmp( type, "tinyint" ) == 0 || strcasecmp( type, "boolean" ) == 0 )
strcasecmp( type, "smallint" ) == 0 ||
strcasecmp( type, "tinyint" ) == 0 ||
strcasecmp( type, "boolean" ) == 0 )
{
fieldType = QVariant::Int;
}
@ -200,9 +206,7 @@ error:
// unexpected error
if ( errMsg != NULL )
{
QString error = "loadFields() SQL error: ";
error = errMsg;
QgsLogger::critical( error );
QgsDebugMsg( QString( "SQL error: %1" ).arg( QString::fromUtf8( errMsg ) ) );
sqlite3_free( errMsg );
}
}
@ -223,22 +227,20 @@ bool QgsSpatiaLiteProvider::featureAtId( int featureId, QgsFeature & feature, bo
{
const QgsField & fld = field( *it );
const QString & fieldname = fld.name();
sql += ", \"";
sql += fieldname;
sql += "\"";
sql += "," + quotedIdentifier( fieldname );
}
if ( fetchGeometry )
{
sql += QString( ", AsBinary(\"%1\")" ).arg( mGeometryColumn );
sql += QString( ", AsBinary(%1)" ).arg( quotedIdentifier( mGeometryColumn ) );
}
sql += QString( " FROM \"%1\" WHERE ROWID = %2" ).arg( mTableName ).arg( featureId );
sql += QString( " FROM %1 WHERE ROWID = %2" ).arg( quotedIdentifier( mTableName ) ).arg( featureId );
if ( sqlite3_prepare_v2( sqliteHandle, sql.toUtf8().constData(), -1, &stmt, NULL ) != SQLITE_OK )
{
// some error occurred
QString errCause = sqlite3_errmsg( sqliteHandle );
QString msg = tr( "SQLite error: %1\n\nSQL: %2" ).arg( sql ).arg( errCause );
QgsLogger::critical( msg );
QgsDebugMsg( QString( "SQLite error: %1\n\nSQL: %2" )
.arg( sql )
.arg( QString::fromUtf8( sqlite3_errmsg( sqliteHandle ) ) ) );
return false;
}
@ -314,7 +316,7 @@ bool QgsSpatiaLiteProvider::featureAtId( int featureId, QgsFeature & feature, bo
}
if ( mFetchGeom )
{
QString geoCol = QString( "AsBinary(\"%1\")" ).arg( mGeometryColumn );
QString geoCol = QString( "AsBinary(%1)" ).arg( quotedIdentifier( mGeometryColumn ) );
if ( strcasecmp( geoCol.toUtf8().constData(), sqlite3_column_name( stmt, ic ) ) == 0 )
{
if ( sqlite3_column_type( stmt, ic ) == SQLITE_BLOB )
@ -339,9 +341,7 @@ bool QgsSpatiaLiteProvider::featureAtId( int featureId, QgsFeature & feature, bo
else
{
// some unexpected error occurred
QString error = "sqlite3_step() error: ";
error += sqlite3_errmsg( sqliteHandle );
QgsLogger::critical( error );
QgsDebugMsg( QString( "sqlite3_step() error: %1" ).arg( QString::fromUtf8( sqlite3_errmsg( sqliteHandle ) ) ) );
sqlite3_finalize( stmt );
return false;
}
@ -355,13 +355,13 @@ bool QgsSpatiaLiteProvider::nextFeature( QgsFeature & feature )
feature.setValid( false );
if ( !valid )
{
QgsLogger::critical( "Read attempt on an invalid SpatiaLite data source" );
QgsDebugMsg( "Read attempt on an invalid SpatiaLite data source" );
return false;
}
if ( sqliteStatement == NULL )
{
QgsLogger::critical( "Invalid current SQLite statement" );
QgsDebugMsg( "Invalid current SQLite statement" );
return false;
}
@ -438,7 +438,7 @@ bool QgsSpatiaLiteProvider::nextFeature( QgsFeature & feature )
}
if ( mFetchGeom )
{
QString geoCol = QString( "AsBinary(\"%1\")" ).arg( mGeometryColumn );
QString geoCol = QString( "AsBinary(%1)" ).arg( quotedIdentifier( mGeometryColumn ) );
if ( strcasecmp( geoCol.toUtf8().constData(), sqlite3_column_name( sqliteStatement, ic ) ) == 0 )
{
if ( sqlite3_column_type( sqliteStatement, ic ) == SQLITE_BLOB )
@ -463,9 +463,7 @@ bool QgsSpatiaLiteProvider::nextFeature( QgsFeature & feature )
else
{
// some unexpected error occurred
QString error = "sqlite3_step() error: ";
error += sqlite3_errmsg( sqliteHandle );
QgsLogger::critical( error );
QgsDebugMsg( QString( "sqlite3_step() error: %1" ).arg( QString::fromUtf8( sqlite3_errmsg( sqliteHandle ) ) ) );
sqlite3_finalize( sqliteStatement );
sqliteStatement = NULL;
return false;
@ -512,7 +510,7 @@ void QgsSpatiaLiteProvider::select( QgsAttributeList fetchAttributes, QgsRectang
if ( !valid )
{
QgsLogger::critical( "Read attempt on an invalid SpatiaLite data source" );
QgsDebugMsg( "Read attempt on an invalid SpatiaLite data source" );
return;
}
@ -528,15 +526,13 @@ void QgsSpatiaLiteProvider::select( QgsAttributeList fetchAttributes, QgsRectang
{
const QgsField & fld = field( *it );
const QString & fieldname = fld.name();
sql += ", \"";
sql += fieldname;
sql += "\"";
sql += "," + quotedIdentifier( fieldname );
}
if ( fetchGeometry )
{
sql += QString( ", AsBinary(\"%1\")" ).arg( mGeometryColumn );
sql += QString( ", AsBinary(%1)" ).arg( quotedIdentifier( mGeometryColumn ) );
}
sql += QString( " FROM \"%1\"" ).arg( mTableName );
sql += QString( " FROM %1" ).arg( quotedIdentifier( mTableName ) );
QString whereClause;
@ -551,7 +547,7 @@ void QgsSpatiaLiteProvider::select( QgsAttributeList fetchAttributes, QgsRectang
arg( QString::number( rect.xMinimum(), 'f', 6 ) ).
arg( QString::number( rect.yMinimum(), 'f', 6 ) ).
arg( QString::number( rect.xMaximum(), 'f', 6 ) ).arg( QString::number( rect.yMaximum(), 'f', 6 ) );
whereClause += QString( "Intersects(\"%1\", BuildMbr(%2)) AND " ).arg( mGeometryColumn ).arg( mbr );
whereClause += QString( "Intersects(%1, BuildMbr(%2)) AND " ).arg( quotedIdentifier( mGeometryColumn ) ).arg( mbr );
}
if ( mVShapeBased )
{
@ -560,7 +556,7 @@ void QgsSpatiaLiteProvider::select( QgsAttributeList fetchAttributes, QgsRectang
arg( QString::number( rect.xMinimum(), 'f', 6 ) ).
arg( QString::number( rect.yMinimum(), 'f', 6 ) ).
arg( QString::number( rect.xMaximum(), 'f', 6 ) ).arg( QString::number( rect.yMaximum(), 'f', 6 ) );
whereClause += QString( "MbrIntersects(\"%1\", BuildMbr(%2))" ).arg( mGeometryColumn ).arg( mbr );
whereClause += QString( "MbrIntersects(%1, BuildMbr(%2))" ).arg( quotedIdentifier( mGeometryColumn ) ).arg( mbr );
}
else
{
@ -572,7 +568,7 @@ void QgsSpatiaLiteProvider::select( QgsAttributeList fetchAttributes, QgsRectang
mbrFilter += QString( "ymin <= %1 AND " ).arg( QString::number( rect.yMaximum(), 'f', 6 ) );
mbrFilter += QString( "ymax >= %1" ).arg( QString::number( rect.yMinimum(), 'f', 6 ) );
QString idxName = QString( "idx_%1_%2" ).arg( mIndexTable ).arg( mIndexGeometry );
whereClause += QString( "ROWID IN (SELECT pkid FROM \"%1\" WHERE %2)" ).arg( idxName ).arg( mbrFilter );
whereClause += QString( "ROWID IN (SELECT pkid FROM %1 WHERE %2)" ).arg( quotedIdentifier( idxName ) ).arg( mbrFilter );
}
else if ( spatialIndexMbrCache )
{
@ -582,7 +578,7 @@ void QgsSpatiaLiteProvider::select( QgsAttributeList fetchAttributes, QgsRectang
arg( QString::number( rect.yMinimum(), 'f', 6 ) ).
arg( QString::number( rect.xMaximum(), 'f', 6 ) ).arg( QString::number( rect.yMaximum(), 'f', 6 ) );
QString idxName = QString( "cache_%1_%2" ).arg( mIndexTable ).arg( mIndexGeometry );
whereClause += QString( "ROWID IN (SELECT rowid FROM \"%1\" WHERE mbr = FilterMbrIntersects(%2))" ).arg( idxName ).arg( mbr );
whereClause += QString( "ROWID IN (SELECT rowid FROM %1 WHERE mbr = FilterMbrIntersects(%2))" ).arg( quotedIdentifier( idxName ) ).arg( mbr );
}
else
{
@ -591,7 +587,7 @@ void QgsSpatiaLiteProvider::select( QgsAttributeList fetchAttributes, QgsRectang
arg( QString::number( rect.xMinimum(), 'f', 6 ) ).
arg( QString::number( rect.yMinimum(), 'f', 6 ) ).
arg( QString::number( rect.xMaximum(), 'f', 6 ) ).arg( QString::number( rect.yMaximum(), 'f', 6 ) );
whereClause += QString( "MbrIntersects(\"%1\", BuildMbr(%2))" ).arg( mGeometryColumn ).arg( mbr );
whereClause += QString( "MbrIntersects(%1, BuildMbr(%2))" ).arg( quotedIdentifier( mGeometryColumn ) ).arg( mbr );
}
}
}
@ -617,9 +613,7 @@ void QgsSpatiaLiteProvider::select( QgsAttributeList fetchAttributes, QgsRectang
if ( sqlite3_prepare_v2( sqliteHandle, sql.toUtf8().constData(), -1, &sqliteStatement, NULL ) != SQLITE_OK )
{
// some error occurred
QString errCause = sqlite3_errmsg( sqliteHandle );
QString msg = tr( "SQLite error: %1\n\nSQL: %2" ).arg( sql ).arg( errCause );
QgsLogger::critical( msg );
QgsDebugMsg( QString( "SQLite error: %1\n\nSQL: %2" ).arg( sql ).arg( QString::fromUtf8( sqlite3_errmsg( sqliteHandle ) ) ) );
sqliteStatement = NULL;
}
}
@ -752,9 +746,7 @@ error:
// unexpected error
if ( errMsg != NULL )
{
QString error = "minValue() SQL error: ";
error = errMsg;
QgsLogger::critical( error );
QgsDebugMsg( QString( "SQL error: %1" ).arg( QString::fromUtf8( errMsg ) ) );
sqlite3_free( errMsg );
}
return QVariant( QString::null );
@ -810,9 +802,7 @@ error:
// unexpected error
if ( errMsg != NULL )
{
QString error = "maxValue() SQL error: ";
error = errMsg;
QgsLogger::critical( error );
QgsDebugMsg( QString( "SQL error: %1" ).arg( QString::fromUtf8( errMsg ) ) );
sqlite3_free( errMsg );
}
return QVariant( QString::null );
@ -822,7 +812,6 @@ error:
void QgsSpatiaLiteProvider::uniqueValues( int index, QList < QVariant > &uniqueValues, int limit )
{
sqlite3_stmt *stmt = NULL;
char *errMsg = NULL;
QString sql;
QString txt;
@ -847,9 +836,7 @@ void QgsSpatiaLiteProvider::uniqueValues( int index, QList < QVariant > &uniqueV
if ( sqlite3_prepare_v2( sqliteHandle, sql.toUtf8().constData(), -1, &stmt, NULL ) != SQLITE_OK )
{
// some error occurred
QString errCause = sqlite3_errmsg( sqliteHandle );
QString msg = tr( "SQLite error: %1\n\nSQL: %2" ).arg( sql ).arg( errCause );
QgsLogger::critical( msg );
QgsDebugMsg( QString( "SQLite error: %1\n\nSQL: %2" ).arg( sql ).arg( QString::fromUtf8( sqlite3_errmsg( sqliteHandle ) ) ) );
return;
}
@ -885,28 +872,15 @@ void QgsSpatiaLiteProvider::uniqueValues( int index, QList < QVariant > &uniqueV
}
else
{
// some unexpected error occurred
const char *err = sqlite3_errmsg( sqliteHandle );
int len = strlen( err );
errMsg = ( char * ) sqlite3_malloc( len + 1 );
strcpy( errMsg, err );
goto abort;
QgsDebugMsg( QString( "SQL error:\n%1\n%2" ).arg( sql ).arg( QString::fromUtf8( sqlite3_errmsg( sqliteHandle ) ) ) );
sqlite3_finalize( stmt );
return;
}
}
sqlite3_finalize( stmt );
return;
abort:
QString msg = QString( "getUniqueValues SQL error:\n%1\n" ).arg( sql );
if ( errMsg )
{
msg += errMsg;
sqlite3_free( errMsg );
}
else
msg += "unknown cause";
QgsLogger::critical( msg );
}
bool QgsSpatiaLiteProvider::addFeatures( QgsFeatureList & flist )
@ -932,13 +906,17 @@ bool QgsSpatiaLiteProvider::addFeatures( QgsFeatureList & flist )
if ( !mPrimaryKey.isEmpty() )
{
sql = QString( "INSERT INTO \"%1\" (\"%2\", \"%3\"" ).
arg( mTableName ).arg( mPrimaryKey ).arg( mGeometryColumn );
values = QString( ") VALUES (NULL, GeomFromWKB(?, %1)" ).arg( mSrid );
sql = QString( "INSERT INTO %1(%2,%3" )
.arg( quotedIdentifier( mTableName ) )
.arg( quotedIdentifier( mPrimaryKey ) )
.arg( quotedIdentifier( mGeometryColumn ) );
values = QString( ") VALUES (NULL, GeomFromWKB(?,%1)" ).arg( mSrid );
}
else
{
sql = QString( "INSERT INTO \"%1\" (\"%2\"" ).arg( mTableName ).arg( mGeometryColumn );
sql = QString( "INSERT INTO %1(%2" )
.arg( quotedIdentifier( mTableName ) )
.arg( quotedIdentifier( mGeometryColumn ) );
values = QString( ") VALUES (GeomFromWKB(?, %1)" ).arg( mSrid );
}
@ -952,10 +930,8 @@ bool QgsSpatiaLiteProvider::addFeatures( QgsFeatureList & flist )
if ( fieldname.isEmpty() || fieldname == mGeometryColumn || fieldname == mPrimaryKey )
continue;
sql += ", \"";
sql += fieldname;
sql += "\"";
values += ", ?";
sql += "," + quotedIdentifier( fieldname );
values += ",?";
}
sql += values;
@ -965,9 +941,7 @@ bool QgsSpatiaLiteProvider::addFeatures( QgsFeatureList & flist )
if ( sqlite3_prepare_v2( sqliteHandle, sql.toUtf8().constData(), -1, &stmt, NULL ) != SQLITE_OK )
{
// some error occurred
QString errCause = sqlite3_errmsg( sqliteHandle );
QString msg = tr( "SQLite error: %1\n\nSQL: %2" ).arg( sql ).arg( errCause );
QgsLogger::critical( msg );
QgsDebugMsg( QString( "SQLite error: %1\n\nSQL: %2" ).arg( sql ).arg( sqlite3_errmsg( sqliteHandle ) ) );
return false;
}
@ -1061,15 +1035,11 @@ bool QgsSpatiaLiteProvider::addFeatures( QgsFeatureList & flist )
return true;
abort:
QString msg = QString( "addFeatures SQL error:\n%1\n" ).arg( sql );
QgsDebugMsg( QString( "SQL error:\n%1\n%2" ).arg( sql ).arg( errMsg ? QString::fromUtf8( errMsg ) : "unknown cause" ) );
if ( errMsg )
{
msg += errMsg;
sqlite3_free( errMsg );
}
else
msg += "unknown cause";
QgsLogger::critical( msg );
if ( toCommit )
{
@ -1095,15 +1065,13 @@ bool QgsSpatiaLiteProvider::deleteFeatures( const QgsFeatureIds & id )
}
toCommit = true;
sql = QString( "DELETE FROM \"%1\" WHERE ROWID = ?" ).arg( mTableName );
sql = QString( "DELETE FROM %1 WHERE ROWID=?" ).arg( quotedIdentifier( mTableName ) );
// SQLite prepared statement
if ( sqlite3_prepare_v2( sqliteHandle, sql.toUtf8().constData(), -1, &stmt, NULL ) != SQLITE_OK )
{
// some error occurred
QString errCause = sqlite3_errmsg( sqliteHandle );
QString msg = tr( "SQLite error: %1\n\nSQL: %2" ).arg( sql ).arg( errCause );
QgsLogger::critical( msg );
QgsDebugMsg( QString( "SQLite error: %1\n\nSQL: %2" ).arg( sql ).arg( QString::fromUtf8( sqlite3_errmsg( sqliteHandle ) ) ) );
return false;
}
@ -1144,15 +1112,11 @@ bool QgsSpatiaLiteProvider::deleteFeatures( const QgsFeatureIds & id )
return true;
abort:
QString msg = QString( "deleteFeatures SQL error:\n%1\n" ).arg( sql );
QgsDebugMsg( QString( "SQL error:\n%1\n%2" ).arg( sql ).arg( errMsg ? QString::fromUtf8( errMsg ) : "unknown cause" ) );
if ( errMsg )
{
msg += errMsg;
sqlite3_free( errMsg );
}
else
msg += "unknown cause";
QgsLogger::critical( msg );
if ( toCommit )
{
@ -1204,15 +1168,11 @@ bool QgsSpatiaLiteProvider::addAttributes( const QList<QgsField> &attributes )
return true;
abort:
QString msg = QString( "addAttributes SQL error:\n%1\n" ).arg( sql );
QgsDebugMsg( QString( "SQL error:\n%1\n%2" ).arg( sql ).arg( errMsg ? QString::fromUtf8( errMsg ) : "unknown cause" ) );
if ( errMsg )
{
msg += errMsg;
sqlite3_free( errMsg );
}
else
msg += "unknown cause";
QgsLogger::critical( msg );
if ( toCommit )
{
@ -1245,7 +1205,7 @@ bool QgsSpatiaLiteProvider::changeAttributeValues( const QgsChangedAttributesMap
if ( fid < 0 )
continue;
QString sql = QString( "UPDATE \"%1\" SET " ).arg( mTableName );
QString sql = QString( "UPDATE %1 SET " ).arg( quotedIdentifier( mTableName ) );
bool first = true;
const QgsAttributeMap & attrs = iter.value();
@ -1270,17 +1230,17 @@ bool QgsSpatiaLiteProvider::changeAttributeValues( const QgsChangedAttributesMap
if ( type == QVariant::Invalid )
{
// binding a NULL value
sql += QString( "\"%1\"=NULL" ).arg( fieldName );
sql += QString( "%1=NULL" ).arg( quotedIdentifier( fieldName ) );
}
else if ( type == QVariant::Int || type == QVariant::Double )
{
// binding a NUMERIC value
sql += QString( "\"%1\"=%2" ).arg( fieldName ).arg( siter->toString() );
sql += QString( "%1=%2" ).arg( quotedIdentifier( fieldName ) ).arg( siter->toString() );
}
else
{
// binding a TEXT value
sql += QString( "\"%1\"=%2" ).arg( fieldName ).arg( quotedValue( siter->toString() ) );
sql += QString( "%1=%2" ).arg( quotedIdentifier( fieldName ) ).arg( quotedValue( siter->toString() ) );
}
}
sql += QString( " WHERE ROWID=%1" ).arg( fid );
@ -1303,15 +1263,11 @@ bool QgsSpatiaLiteProvider::changeAttributeValues( const QgsChangedAttributesMap
return true;
abort:
QString msg = QString( "changeAttributeValues SQL error:\n%1\n" ).arg( sql );
QgsDebugMsg( QString( "SQL error:\n%1\n%2" ).arg( sql ).arg( errMsg ? QString::fromUtf8( errMsg ) : "unknown cause" ) );
if ( errMsg )
{
msg += errMsg;
sqlite3_free( errMsg );
}
else
msg += "unknown cause";
QgsLogger::critical( msg );
if ( toCommit )
{
@ -1338,16 +1294,16 @@ bool QgsSpatiaLiteProvider::changeGeometryValues( QgsGeometryMap & geometry_map
toCommit = true;
sql =
QString( "UPDATE \"%1\" SET \"%2\" = GeomFromWKB(?, %3) WHERE ROWID = ?" ).
arg( mTableName ).arg( mGeometryColumn ).arg( mSrid );
QString( "UPDATE %1 SET %2=GeomFromWKB(?, %3) WHERE ROWID = ?" )
.arg( quotedIdentifier( mTableName ) )
.arg( quotedIdentifier( mGeometryColumn ) )
.arg( mSrid );
// SQLite prepared statement
if ( sqlite3_prepare_v2( sqliteHandle, sql.toUtf8().constData(), -1, &stmt, NULL ) != SQLITE_OK )
{
// some error occurred
QString errCause = sqlite3_errmsg( sqliteHandle );
QString msg = tr( "SQLite error: %1\n\nSQL: %2" ).arg( sql ).arg( errCause );
QgsLogger::critical( msg );
QgsDebugMsg( QString( "SQLite error: %1\n\nSQL: %2" ).arg( sql ).arg( QString::fromUtf8( sqlite3_errmsg( sqliteHandle ) ) ) );
return false;
}
@ -1393,15 +1349,11 @@ bool QgsSpatiaLiteProvider::changeGeometryValues( QgsGeometryMap & geometry_map
return true;
abort:
QString msg = QString( "addFeatures SQL error:\n%1\n" ).arg( sql );
QgsDebugMsg( QString( "SQL error:\n%1\n%2" ).arg( sql ).arg( errMsg ? QString::fromUtf8( errMsg ) : "unknown cause" ) );
if ( errMsg )
{
msg += errMsg;
sqlite3_free( errMsg );
}
else
msg += "unknown cause";
QgsLogger::critical( msg );
if ( toCommit )
{
@ -1474,10 +1426,9 @@ QgsSpatiaLiteProvider::SqliteHandles * QgsSpatiaLiteProvider::SqliteHandles::ope
if ( sqlite3_open_v2( dbPath.toUtf8().constData(), &sqlite_handle, SQLITE_OPEN_READWRITE, NULL ) )
{
// failure
QString errCause = sqlite3_errmsg( sqlite_handle );
QString msg = tr( "Failure while connecting to: %1\n\n%2" ).arg( dbPath ).arg( errCause );
QgsLogger::critical( msg );
QgsDebugMsg( QString( "Failure while connecting to: %1\n%2" )
.arg( dbPath )
.arg( QString::fromUtf8( sqlite3_errmsg( sqlite_handle ) ) ) );
return NULL;
}
@ -1485,10 +1436,7 @@ QgsSpatiaLiteProvider::SqliteHandles * QgsSpatiaLiteProvider::SqliteHandles::ope
if ( checkMetadata( sqlite_handle ) == false )
{
// failure
QString errCause = tr( "invalid metadata tables" );
QString msg = tr( "Failure while connecting to: %1\n\n%2" ).arg( dbPath ).arg( errCause );
QgsLogger::critical( msg );
QgsDebugMsg( QString( "Failure while connecting to: %1\n\ninvalid metadata tables" ).arg( dbPath ) );
sqlite3_close( sqlite_handle );
return NULL;
}
@ -1514,8 +1462,8 @@ void QgsSpatiaLiteProvider::SqliteHandles::closeDb( QMap < QString, SqliteHandle
for ( i = handles.begin(); i != handles.end() && i.value() != handle; i++ )
;
assert( i.value() == handle );
assert( i.value()->ref > 0 );
Q_ASSERT( i.value() == handle );
Q_ASSERT( i.value()->ref > 0 );
if ( --i.value()->ref == 0 )
{
@ -1536,6 +1484,12 @@ void QgsSpatiaLiteProvider::SqliteHandles::sqliteClose()
}
}
QString QgsSpatiaLiteProvider::quotedIdentifier( QString id ) const
{
id.replace( "\"", "\"\"" );
return id.prepend( "\"" ).append( "\"" );
}
QString QgsSpatiaLiteProvider::quotedValue( QString value ) const
{
if ( value.isNull() )
@ -1563,15 +1517,23 @@ bool QgsSpatiaLiteProvider::checkLayerType()
QString sql = QString( "SELECT read_only FROM geometry_columns "
"LEFT JOIN geometry_columns_auth "
"USING (f_table_name, f_geometry_column) "
"WHERE f_table_name=%1 and f_geometry_column=%2" ).arg( quotedValue( mTableName ) ).
arg( quotedValue( mGeometryColumn ) );
"WHERE f_table_name=%1 and f_geometry_column=%2" )
.arg( quotedValue( mTableName ) )
.arg( quotedValue( mGeometryColumn ) );
ret = sqlite3_get_table( sqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg );
if ( ret != SQLITE_OK )
goto error;
if ( rows < 1 )
;
else
{
if ( errMsg && strcmp( errMsg, "no such table: geometry_columns_auth" ) == 0 )
{
sqlite3_free( errMsg );
sql = QString( "SELECT 0 FROM geometry_columns WHERE f_table_name=%1 and f_geometry_column=%2" )
.arg( quotedValue( mTableName ) )
.arg( quotedValue( mGeometryColumn ) );
ret = sqlite3_get_table( sqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg );
}
}
if ( ret == SQLITE_OK && rows == 1 )
{
mTableBased = true;
mReadOnly = false;
@ -1585,6 +1547,12 @@ bool QgsSpatiaLiteProvider::checkLayerType()
}
count++;
}
if ( errMsg )
{
QgsDebugMsg( QString( "sqlite error %1 [%2]" ).arg( sql ).arg( errMsg ) );
sqlite3_free( errMsg );
errMsg = 0;
}
sqlite3_free_table( results );
// checking if this one is a View-based layer
@ -1593,16 +1561,18 @@ bool QgsSpatiaLiteProvider::checkLayerType()
arg( quotedValue( mGeometryColumn ) );
ret = sqlite3_get_table( sqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg );
if ( ret != SQLITE_OK )
goto error;
if ( rows < 1 )
;
else
if ( ret == SQLITE_OK && rows == 1 )
{
mViewBased = true;
mReadOnly = true;
count++;
}
if ( errMsg )
{
QgsDebugMsg( QString( "sqlite error %1 [%2]" ).arg( sql ).arg( errMsg ) );
sqlite3_free( errMsg );
errMsg = 0;
}
sqlite3_free_table( results );
// checking if this one is a VirtualShapefile-based layer
@ -1611,34 +1581,22 @@ bool QgsSpatiaLiteProvider::checkLayerType()
arg( quotedValue( mGeometryColumn ) );
ret = sqlite3_get_table( sqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg );
if ( ret != SQLITE_OK )
goto error;
if ( rows < 1 )
;
else
if ( ret == SQLITE_OK && rows == 1 )
{
mVShapeBased = true;
mReadOnly = true;
count++;
}
if ( errMsg )
{
QgsDebugMsg( QString( "sqlite error %1 [%2]" ).arg( sql ).arg( errMsg ) );
sqlite3_free( errMsg );
errMsg = 0;
}
sqlite3_free_table( results );
// cheching for validity
if ( count != 1 )
return false;
return true;
error:
// unexpected error
if ( errMsg != NULL )
{
QString errCause = errMsg;
QString msg = QString( "checkLayerType SQL error: %1\n\n%2" ).arg( sql ).arg( errCause );
QgsLogger::critical( msg );
sqlite3_free( errMsg );
}
return false;
// checking for validity
return count == 1;
}
bool QgsSpatiaLiteProvider::getGeometryDetails()
@ -1729,9 +1687,7 @@ error:
// unexpected error
if ( errMsg != NULL )
{
QString errCause = errMsg;
QString msg = QString( "getTableGeometryDetails SQL error: %1\n\n%2" ).arg( sql ).arg( errCause );
QgsLogger::critical( msg );
QgsDebugMsg( QString( "SQL error: %1\n\n%2" ).arg( sql ).arg( errMsg ? QString::fromUtf8( errMsg ) : "unknown cause" ) );
sqlite3_free( errMsg );
}
return false;
@ -1814,9 +1770,7 @@ error:
// unexpected error
if ( errMsg != NULL )
{
QString errCause = errMsg;
QString msg = QString( "getViewGeometryDetails SQL error: %1\n\n%2" ).arg( sql ).arg( errCause );
QgsLogger::critical( msg );
QgsDebugMsg( QString( "SQL error: %1\n\n%2" ).arg( sql ).arg( errMsg ? QString::fromUtf8( errMsg ) : "unknown cause" ) );
sqlite3_free( errMsg );
}
return false;
@ -1886,9 +1840,7 @@ error:
// unexpected error
if ( errMsg != NULL )
{
QString errCause = errMsg;
QString msg = QString( "getVShapeGeometryDetails SQL error: %1\n\n%2" ).arg( sql ).arg( errCause );
QgsLogger::critical( msg );
QgsDebugMsg( QString( "SQL error: %1\n\n%2" ).arg( sql ).arg( errMsg ? QString::fromUtf8( errMsg ) : "unknown cause" ) );
sqlite3_free( errMsg );
}
return false;
@ -1925,9 +1877,7 @@ error:
// unexpected error
if ( errMsg != NULL )
{
QString errCause = errMsg;
QString msg = QString( "getSridDetails SQL error: %1\n\n%2" ).arg( sql ).arg( errCause );
QgsLogger::critical( msg );
QgsDebugMsg( QString( "SQL error: %1\n\n%2" ).arg( sql ).arg( errMsg ? QString::fromUtf8( errMsg ) : "unknown cause" ) );
sqlite3_free( errMsg );
}
return false;
@ -1976,9 +1926,7 @@ error:
// unexpected error
if ( errMsg != NULL )
{
QString error = "getTableSummary() SQL error: ";
error = errMsg;
QgsLogger::critical( error );
QgsDebugMsg( QString( "SQL error: %1\n\n%2" ).arg( sql ).arg( errMsg ? QString::fromUtf8( errMsg ) : "unknown cause" ) );
sqlite3_free( errMsg );
}
return false;
@ -1990,7 +1938,7 @@ const QgsField & QgsSpatiaLiteProvider::field( int index ) const
if ( it == attributeFields.constEnd() )
{
QgsLogger::critical( "Field " + QString::number( index ) + " not found." );
QgsDebugMsg( QString( "Field %1 not found." ).arg( index ) );
}
return it.value();

View File

@ -356,6 +356,7 @@ class QgsSpatiaLiteProvider: public QgsVectorDataProvider
*/
//void sqliteOpen();
void closeDb();
QString quotedIdentifier( QString id ) const;
QString quotedValue( QString value ) const;
bool checkLayerType();
bool getGeometryDetails();

View File

@ -403,7 +403,7 @@
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Apply|QDialogButtonBox::Close|QDialogButtonBox::Help</set>
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Help|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>