Skip to content
Permalink
Browse files

Update ExecuteSQL to be configurable with expressions

  • Loading branch information
pblottiere committed Apr 26, 2018
1 parent b13ba37 commit aef2b6e3e731ff0ffc0ffe79e0f0e0121561dae1
@@ -30,6 +30,8 @@
QgsWkbTypes,
QgsProcessingAlgorithm,
QgsProcessingParameterMultipleLayers,
QgsProcessingParameterDefinition,
QgsExpression,
QgsProcessingParameterString,
QgsProcessingParameterEnum,
QgsProcessingParameterCrs,
@@ -40,6 +42,21 @@
from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm


class ParameterExecuteSql(QgsProcessingParameterDefinition):

def __init__(self, name='', description=''):
super().__init__(name, description)
self.setMetadata({
'widget_wrapper': 'processing.algs.qgis.ui.ExecuteSQLWidget.ExecuteSQLWidgetWrapper'
})

def type(self):
return 'execute_sql'

def clone(self):
return ParameterExecuteSql(self.name(), self.description())


class ExecuteSQL(QgisAlgorithm):

""" This algorithm allows executing an SQL query on a set of input
@@ -71,9 +88,7 @@ def initAlgorithm(self, config=None):
description=self.tr('Additional input datasources (called input1, .., inputN in the query)'),
optional=True))

self.addParameter(QgsProcessingParameterString(name=self.INPUT_QUERY,
description=self.tr('SQL query'),
multiLine=True))
self.addParameter(ParameterExecuteSql(name=self.INPUT_QUERY, description=self.tr('SQL query')))

self.addParameter(QgsProcessingParameterString(name=self.INPUT_UID_FIELD,
description=self.tr('Unique identifier field'), optional=True))
@@ -120,7 +135,9 @@ def processAlgorithm(self, parameters, context, feedback):
raise QgsProcessingException(
self.tr('Empty SQL. Please enter valid SQL expression and try again.'))
else:
df.setQuery(query)
localContext = self.createExpressionContext(parameters, context)
expandedQuery = QgsExpression.replaceExpressionText(query, localContext)
df.setQuery(expandedQuery)

if uid_field:
df.setUid(uid_field)
@@ -0,0 +1,135 @@
# -*- coding: utf-8 -*-

"""
***************************************************************************
ExecuteSQLWidget.py
---------------------
Date : November 2017
Copyright : (C) 2017 by Paul Blottiere
Email : blottiere dot paul at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""

__author__ = 'Paul Blottiere'
__date__ = 'November 2018'
__copyright__ = '(C) 2018, Paul Blottiere'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

import os

from qgis.PyQt import uic
from qgis.PyQt.QtWidgets import QTreeWidgetItem
from qgis.PyQt.QtCore import Qt

from qgis.core import (QgsApplication,
QgsExpressionContextScope,
QgsProcessingParameterString,
QgsProcessingParameterNumber,
QgsExpression,
QgsProcessingModelChildParameterSource,
QgsProcessingParameterFile,
QgsProcessingParameterField,
QgsProcessingOutputString,
QgsProcessingParameterExpression,
QgsProcessingOutputFile)

from qgis.gui import QgsFieldExpressionWidget

from processing.gui.wrappers import (WidgetWrapper,
dialogTypes,
DIALOG_MODELER)

pluginPath = os.path.dirname(__file__)
WIDGET, BASE = uic.loadUiType(os.path.join(pluginPath, 'ExecuteSQLWidgetBase.ui'))


class ExecuteSQLWidget(BASE, WIDGET):

def __init__(self, dialog):
super(ExecuteSQLWidget, self).__init__(None)
self.setupUi(self)
self.dialog = dialog
self.dialogType = dialogTypes[dialog.__class__.__name__]

self.mExpressionWidget = QgsFieldExpressionWidget()

# add model parameters in context scope if called from modeler
if self.dialogType == DIALOG_MODELER:
strings = dialog.getAvailableValuesOfType(
[QgsProcessingParameterString, QgsProcessingParameterNumber], [])
model_params = [dialog.resolveValueDescription(s) for s in strings]

scope = QgsExpressionContextScope()
for param in model_params:
var = QgsExpressionContextScope.StaticVariable(param)
scope.addVariable(var)

self.mExpressionWidget.appendScope(scope)

self.mHLayout.insertWidget(0, self.mExpressionWidget)

self.mInsert.clicked.connect(self.insert)

def insert(self):
if self.mExpressionWidget.currentText():
exp = '[% {} %]'.format(self.mExpressionWidget.currentText())
self.mText.insertPlainText(exp)

def setValue(self, value):
text = value

if self.dialogType == DIALOG_MODELER:
if isinstance(value, list):
for v in value:
if isinstance(v, QgsProcessingModelChildParameterSource) \
and v.source() == QgsProcessingModelChildParameterSource.ExpressionText:
text = v.expressionText()

self.mText.setPlainText(text)

def value(self):
value = self.mText.toPlainText()

if self.dialogType == DIALOG_MODELER:
expression_values = self._expressionValues(value)
if len(expression_values) > 1:
value = expression_values

return value

def _expressionValues(self, text):
strings = self.dialog.getAvailableValuesOfType(
[QgsProcessingParameterString, QgsProcessingParameterNumber], [])
model_params = [(self.dialog.resolveValueDescription(s), s) for s in strings]

variables = QgsExpression.referencedVariables(text)
expression_values = []
expression_values.append(QgsProcessingModelChildParameterSource.fromExpressionText(text))

for k, v in model_params:
if k in variables:
expression_values.append(v)

return expression_values


class ExecuteSQLWidgetWrapper(WidgetWrapper):

def createWidget(self):
return ExecuteSQLWidget(self.dialog)

def setValue(self, value):
self.widget.setValue(value)

def value(self):
return self.widget.value()
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="3" column="0" rowspan="2" colspan="2">
<layout class="QVBoxLayout" name="verticalLayout">
<property name="topMargin">
<number>10</number>
</property>
<item>
<widget class="QPlainTextEdit" name="mText"/>
</item>
<item>
<layout class="QHBoxLayout" name="mHLayout">
<property name="spacing">
<number>6</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<item>
<widget class="QPushButton" name="mInsert">
<property name="text">
<string>Insert</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

0 comments on commit aef2b6e

Please sign in to comment.
You can’t perform that action at this time.