sqlite accept aliased queries from db manager

Fixes #20674 - DB Manager - load sql query as layer with geom column

Well, not sure it really fixes that particular issue because it
is not really well described, but for sure this fixes the general
case of "SELECT * FROM my_table AS my_alias"
This commit is contained in:
Alessandro Pasotti 2018-12-08 11:15:49 +01:00
parent bc98f8667c
commit b5181f2c50
3 changed files with 17 additions and 5 deletions

View File

@ -147,13 +147,13 @@ class DlgSqlLayerWindow(QWidget, Ui_Dialog):
# Update from layer
# First the SQL from QgsDataSourceUri table
sql = uri.table()
sql = uri.table().replace('\n', ' ').strip()
if uri.keyColumn() == '_uid_':
match = re.search(r'^\(SELECT .+ AS _uid_,\* FROM \((.*)\) AS _subq_.+_\s*\)$', sql, re.S | re.X)
match = re.search(r'^\(SELECT .+ AS _uid_,\* FROM \((.*)\) AS _subq_.+_\s*\)$', sql, re.S | re.X | re.IGNORECASE)
if match:
sql = match.group(1)
else:
match = re.search(r'^\((SELECT .+ FROM .+)\)$', sql, re.S | re.X)
match = re.search(r'^\((SELECT .+ FROM .+)\)$', sql, re.S | re.X | re.IGNORECASE)
if match:
sql = match.group(1)
# Need to check on table() since the parentheses were removed by the regexp

View File

@ -602,7 +602,7 @@ class DlgSqlWindow(QWidget, Ui_Dialog):
def _getSqlQuery(self):
sql = self.editSql.selectedText()
if len(sql) == 0:
sql = self.editSql.text()
sql = self.editSql.text().replace('\n', ' ').strip()
return sql
def uniqueChanged(self):

View File

@ -4603,9 +4603,21 @@ bool QgsSpatiaLiteProvider::checkLayerType()
// 3. check if ROWID injection works
if ( ! queryGeomTableName.isEmpty() )
{
// Check if the whole sql is aliased (I couldn't find a sqlite API call to get this information)
QRegularExpression re { R"re(\s+AS\s+(\w+)\n?\)?$)re" };
re.setPatternOptions( QRegularExpression::PatternOption::MultilineOption |
QRegularExpression::PatternOption::CaseInsensitiveOption );
QRegularExpressionMatch match { re.match( mTableName ) };
regex.setPattern( QStringLiteral( R"re(\s+AS\s+(\w+)\n?\)?$)re" ) );
QString tableAlias;
if ( match.hasMatch() )
{
tableAlias = match.captured( 1 );
}
QString newSql( mQuery.replace( QStringLiteral( "SELECT " ),
QStringLiteral( "SELECT %1.%2, " )
.arg( quotedIdentifier( queryGeomTableName ), QStringLiteral( "ROWID" ) ),
.arg( quotedIdentifier( tableAlias.isEmpty() ? queryGeomTableName : tableAlias ),
QStringLiteral( "ROWID" ) ),
Qt::CaseInsensitive ) );
sql = QStringLiteral( "SELECT ROWID FROM %1 WHERE ROWID IS NOT NULL LIMIT 1" ).arg( newSql );
ret = sqlite3_get_table( mSqliteHandle, sql.toUtf8().constData(), &results, &rows, &columns, &errMsg );