Example #1
0
 def __init__(self, abstractDb, uiParameterJsonDict=None, parent=None):
     """Constructor."""
     super(self.__class__, self).__init__(parent)
     self.abstractDb = abstractDb
     self.setupUi(self)
     self.jsonBuilder = CustomJSONBuilder()
     self.populateSchemaCombo()
     self.hideWidgetList([
         self.singleValueLabel, self.singleValueComboBox,
         self.actionComboBox
     ])
     self.singleAttribute = True
     self.filterCustomSelectorWidget.setTitle(
         self.tr('Select filter values'))
     self.populateSingleValue.connect(self.populateWidgetWithSingleValue)
     self.populateListValue.connect(self.populateWidgetWithListValue)
     geomTypeDict = self.abstractDb.getGeomTypeDict()
     geomDict = self.abstractDb.getGeomDict(geomTypeDict)
     self.domainDict = self.abstractDb.getDbDomainDict(geomDict)
     self.inhTree = self.abstractDb.getInheritanceTreeDict()
     self.utils = Utils()
     self.actionDict = {
         self.tr('Add to Filter (Leave empty if filter is empty)'):
         'addEmpty',
         self.tr('Add to Filter (Add value to empty filter)'): 'add',
         self.tr('Remove from Filter'): 'remove'
     }
     self.populateFromUiParameterJsonDict(uiParameterJsonDict)
Example #2
0
 def __init__(self, abstractDb, uiParameterJsonDict=None, parent=None):
     """Constructor."""
     super(self.__class__, self).__init__(parent)
     self.setupUi(self)
     self.geomUiDict = {
         self.tr('Point'): {
             'sufix': 'p',
             'type': 'MULTIPOINT([epsg])'
         },
         self.tr('Line'): {
             'sufix': 'l',
             'type': 'MULTILINESTRING([epsg])'
         },
         self.tr('Area'): {
             'sufix': 'a',
             'type': 'MULTIPOLYGON([epsg])'
         }
     }
     header = self.tableWidget.horizontalHeader()
     header.setStretchLastSection(True)
     regex = QtCore.QRegExp('[a-z][a-z\_]*')
     validator = QtGui.QRegExpValidator(regex, self.classNameLineEdit)
     self.classNameLineEdit.setValidator(validator)
     regex2 = QtCore.QRegExp('[a-z]*')
     validator2 = QtGui.QRegExpValidator(regex2, self.categoryLineEdit)
     self.categoryLineEdit.setValidator(validator2)
     self.abstractDb = abstractDb
     self.populateSchemaCombo()
     self.jsonBuilder = CustomJSONBuilder()
     self.populateFromUiParameterJsonDict(uiParameterJsonDict)
Example #3
0
 def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
     """Constructor."""
     super(self.__class__, self).__init__(parent)
     self.abstractDb = abstractDb
     self.setupUi(self)
     self.jsonBuilder = CustomJSONBuilder()
     self.populateSchemaCombo()
     self.populateFromUiParameterJsonDict(uiParameterJsonDict)
Example #4
0
 def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
     """Constructor."""
     super(self.__class__, self).__init__(parent)
     self.abstractDb = abstractDb
     self.setupUi(self)
     regex = QtCore.QRegExp('[a-z]*')
     validator = QtGui.QRegExpValidator(regex, self.nameLineEdit)
     self.nameLineEdit.setValidator(validator)
     self.domainSetter = None
     self.jsonBuilder = CustomJSONBuilder()
     self.populateFromUiParameterJsonDict(uiParameterJsonDict)
Example #5
0
 def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
     """Constructor."""
     super(self.__class__, self).__init__(parent)
     self.abstractDb = abstractDb
     self.setupUi(self)
     self.jsonBuilder = CustomJSONBuilder()
     self.populateSchemaCombo()
     geomTypeDict = self.abstractDb.getGeomTypeDict()
     geomDict = self.abstractDb.getGeomDict(geomTypeDict)
     self.domainDict = self.abstractDb.getDbDomainDict(geomDict)
     self.utils = Utils()
     self.populateFromUiParameterJsonDict(uiParameterJsonDict)
Example #6
0
 def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
     """Constructor."""
     super(self.__class__, self).__init__(parent)
     self.setupUi(self)
     self.abstractDb = abstractDb
     self.populateDomainList()
     self.domainName = None
     self.domainDict = None
     self.filterClause = dict()
     self.jsonBuilder = CustomJSONBuilder()
     self.populateFromUiParameterJsonDict(uiParameterJsonDict)
Example #7
0
 def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
     """Constructor."""
     super(self.__class__, self).__init__(parent)
     self.setupUi(self) 
     header = self.tableWidget.horizontalHeader()
     header.setStretchLastSection(True)
     regex = QtCore.QRegExp('[a-z][a-z\_]*')
     validator = QtGui.QRegExpValidator(regex, self.domainNameLineEdit)
     self.domainNameLineEdit.setValidator(validator)
     self.abstractDb = abstractDb
     self.jsonBuilder = CustomJSONBuilder()
     self.tableWidget.setItemDelegate(ValidatedItemDelegate())
     self.oldBackground = None
     self.populateFromUiParameterJsonDict(uiParameterJsonDict)
Example #8
0
 def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
     """Constructor."""
     super(self.__class__, self).__init__(parent)
     self.setupUi(self)
     self.geomUiDict = {self.tr('Point'):{'sufix':'p','type':'MULTIPOINT([epsg])'}, self.tr('Line'):{'sufix':'l','type':'MULTILINESTRING([epsg])'}, self.tr('Area'):{'sufix':'a','type':'MULTIPOLYGON([epsg])'}} 
     header = self.tableWidget.horizontalHeader()
     header.setStretchLastSection(True)
     regex = QtCore.QRegExp('[a-z][a-z\_]*')
     validator = QtGui.QRegExpValidator(regex, self.classNameLineEdit)
     self.classNameLineEdit.setValidator(validator)
     regex2 = QtCore.QRegExp('[a-z]*')
     validator2 = QtGui.QRegExpValidator(regex2, self.categoryLineEdit)
     self.categoryLineEdit.setValidator(validator2)
     self.abstractDb = abstractDb
     self.populateSchemaCombo()
     self.jsonBuilder = CustomJSONBuilder()
     self.populateFromUiParameterJsonDict(uiParameterJsonDict)
 def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
     """Constructor."""
     super(self.__class__, self).__init__(parent)
     self.abstractDb = abstractDb
     self.setupUi(self)
     self.jsonBuilder = CustomJSONBuilder()
     self.populateSchemaCombo()
     self.hideWidgetList([self.singleValueLabel, self.singleValueComboBox, self.actionComboBox])
     self.singleAttribute = True
     self.filterCustomSelectorWidget.setTitle(self.tr('Select filter values'))
     self.populateSingleValue.connect(self.populateWidgetWithSingleValue)
     self.populateListValue.connect(self.populateWidgetWithListValue)
     geomTypeDict = self.abstractDb.getGeomTypeDict()
     geomDict = self.abstractDb.getGeomDict(geomTypeDict)
     self.domainDict = self.abstractDb.getDbDomainDict(geomDict)
     self.inhTree = self.abstractDb.getInheritanceTreeDict()
     self.utils = Utils()
     self.actionDict = {self.tr('Add to Filter (Leave empty if filter is empty)'):'addEmpty', self.tr('Add to Filter (Add value to empty filter)'):'add',self.tr('Remove from Filter'):'remove'}
     self.populateFromUiParameterJsonDict(uiParameterJsonDict)
Example #10
0
class NewDomainWidget(QtGui.QWidget, FORM_CLASS):
    def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
        """Constructor."""
        super(self.__class__, self).__init__(parent)
        self.setupUi(self) 
        header = self.tableWidget.horizontalHeader()
        header.setStretchLastSection(True)
        regex = QtCore.QRegExp('[a-z][a-z\_]*')
        validator = QtGui.QRegExpValidator(regex, self.domainNameLineEdit)
        self.domainNameLineEdit.setValidator(validator)
        self.abstractDb = abstractDb
        self.jsonBuilder = CustomJSONBuilder()
        self.tableWidget.setItemDelegate(ValidatedItemDelegate())
        self.oldBackground = None
        self.populateFromUiParameterJsonDict(uiParameterJsonDict)
    
    def populateFromUiParameterJsonDict(self, uiParameterJsonDict):
        """
        populates ui from  uiParameterJsonDict with the following keys:
        {
            'domainNameLineEdit': --text of domainNameLineEdit --
            'tableWidget': [lists of code and value tuples]
        }
        """
        if uiParameterJsonDict:
            self.domainNameLineEdit.setText(uiParameterJsonDict['domainNameLineEdit'])
            for domainItem in uiParameterJsonDict['tableWidget']:
                self.addItemInTableWidget(codeText = domainItem[0], valueText = domainItem[1])
    
    @pyqtSlot()
    def on_domainNameLineEdit_editingFinished(self):
        text = self.domainNameLineEdit.text()
        while text[-1] == '_':
            self.domainNameLineEdit.setText(text[0:-1])
            text = text[0:-1]
    
    @pyqtSlot(str)
    def on_domainNameLineEdit_textEdited(self, newText):
        if len(newText) > 1:
            if newText[-1] == '_' and newText[-2] == '_':
                    self.domainNameLineEdit.setText(newText[0:-1])
    
    @pyqtSlot(bool, name='on_addValuePushButton_clicked')
    def addItemInTableWidget(self, codeText = '', valueText = ''):
        index = self.tableWidget.rowCount()
        self.tableWidget.insertRow(index)
        codeItem = QtGui.QTableWidgetItem(codeText)
        valueItem = QtGui.QTableWidgetItem(valueText)
        self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, codeItem)
        self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, valueItem)
        if index == 0:
            self.oldBackground = self.tableWidget.item(0,0).background()     
    
    @pyqtSlot(bool)
    def on_removeValuePushButton_clicked(self):
        selected = self.tableWidget.selectedIndexes()
        rowList = [i.row() for i in selected]
        rowList.sort(reverse=True)
        for row in rowList:
            self.tableWidget.removeRow(row)
    
    @pyqtSlot(QTableWidgetItem)
    def on_tableWidget_itemChanged(self, widgetItem):
        if self.checkNull(widgetItem):
            return
        if self.tableWidget.currentColumn() == 0:
            self.checkUnique(widgetItem)
    
    def checkNull(self, widgetItem):
        if widgetItem.text() == '':
            widgetItem.setToolTip(self.tr('Enter a value!'))
            return True
        else:
            widgetItem.setToolTip('')
            return False
    
    def checkUnique(self, widgetItem):
        currentValue = widgetItem.text() 
        itemList = []
        for i in range(self.tableWidget.rowCount()):
            if i <> widgetItem.row():
                curItem = self.tableWidget.item(i, 0)
                itemList.append(curItem.text())
        if currentValue in itemList:
            widgetItem.setBackground(QtGui.QColor(230,124,127))
            self.tableWidget.setCurrentCell(widgetItem.row(), 0)
            widgetItem.setToolTip(self.tr('Code value already entered.'))
        else:
            if self.oldBackground:
                widgetItem.setBackground(self.oldBackground)
                widgetItem.setToolTip('')
    
    def getTitle(self):
        return self.title
    
    def setTitle(self, title):
        self.title = title
    
    def validate(self):
        if self.domainNameLineEdit.text() == '':
            return False
        if self.tableHasEmptyValue():
            return False
        if self.tableHasDuplicatedCode():
            return False 
        return True

    def validateDiagnosis(self):
        invalidatedReason = ''
        if self.domainNameLineEdit.text() == '':
            invalidatedReason += self.tr('A domain name must be chosen.\n')
        if self.tableHasEmptyValue():
            invalidatedReason += self.tr('There must be no empty codes or values.\n')
        if self.tableHasEmptyValue():
            invalidatedReason += self.tr('Codes must be unique.\n')
        return invalidatedReason

    def tableHasEmptyValue(self):
        for row in range(self.tableWidget.rowCount()):
            for column in range(self.tableWidget.columnCount()):
                if self.tableWidget.item(row,column).text() == '':
                    return True
        return False
    
    def tableHasDuplicatedCode(self):
        listOfCodes = []
        for row in range(self.tableWidget.rowCount()):
            code = self.tableWidget.item(row,0)
            if code not in listOfCodes:
                listOfCodes.append(code)
            else:
                return True
        return False

    def getJSONTag(self):
        if not self.validate():
            raise Exception(self.tr('Error in domain ')+ self.title + ' : ' + self.validateDiagnosis())
        domainName = self.domainNameLineEdit.text()
        valueDict = dict()
        for row in range(self.tableWidget.rowCount()):
            code = self.tableWidget.item(row,0).text()
            value = self.tableWidget.item(row,1).text()
            valueDict[code] = value
        return [self.jsonBuilder.addDomainTableElement(domainName, valueDict)]

    def getUiParameterJsonDict(self):
        """
        builds a dict with the following format:
        {
            'domainNameLineEdit': --text of domainNameLineEdit --
            'tableWidget': [lists of code and value tuples]
        }
        """
        uiParameterJsonDict = dict()
        uiParameterJsonDict['domainNameLineEdit'] = self.domainNameLineEdit.text()
        uiParameterJsonDict['tableWidget'] = []
        for row in range(self.tableWidget.rowCount()):
            code = self.tableWidget.item(row,0).text()
            value = self.tableWidget.item(row,1).text()
            uiParameterJsonDict['tableWidget'].append((code,value))
        return uiParameterJsonDict
Example #11
0
class NewClassWidget(QtGui.QWidget, FORM_CLASS):
    def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
        """Constructor."""
        super(self.__class__, self).__init__(parent)
        self.setupUi(self)
        self.geomUiDict = {self.tr('Point'):{'sufix':'p','type':'MULTIPOINT([epsg])'}, self.tr('Line'):{'sufix':'l','type':'MULTILINESTRING([epsg])'}, self.tr('Area'):{'sufix':'a','type':'MULTIPOLYGON([epsg])'}} 
        header = self.tableWidget.horizontalHeader()
        header.setStretchLastSection(True)
        regex = QtCore.QRegExp('[a-z][a-z\_]*')
        validator = QtGui.QRegExpValidator(regex, self.classNameLineEdit)
        self.classNameLineEdit.setValidator(validator)
        regex2 = QtCore.QRegExp('[a-z]*')
        validator2 = QtGui.QRegExpValidator(regex2, self.categoryLineEdit)
        self.categoryLineEdit.setValidator(validator2)
        self.abstractDb = abstractDb
        self.populateSchemaCombo()
        self.jsonBuilder = CustomJSONBuilder()
        self.populateFromUiParameterJsonDict(uiParameterJsonDict)
    
    def populateFromUiParameterJsonDict(self, uiParameterJsonDict):
        """
        populates ui from  uiParameterJsonDict with the following keys:
        {
            'schemaComboBox': --text of selected item on schemaComboBox --
            'categoryLineEdit': --text of categoryLineEdit --
            'classNameLineEdit' : --text of classNameLineEdit --
            'geomComboBoxIdx' : --index of selected item on schemaComboBox --
            'attrWidgetList' : [--list of uiParameterJsonDict from each attributeWidget--]
        }
        """
        if uiParameterJsonDict:
            idx = self.schemaComboBox.findText(uiParameterJsonDict['schemaComboBox'], flags = Qt.MatchExactly)
            self.schemaComboBox.setCurrentIndex(idx)
            self.categoryLineEdit.setText(uiParameterJsonDict['categoryLineEdit'])
            self.classNameLineEdit.setText(uiParameterJsonDict['classNameLineEdit'])
            self.geomComboBox.setCurrentIndex(int(uiParameterJsonDict['geomComboBoxIdx']))
            for attr in uiParameterJsonDict['attrWidgetList']:
                self.addCellWidget(uiParameterJsonDict=attr)
    
    def populateSchemaCombo(self):
        self.schemaComboBox.clear()
        schemaList = self.abstractDb.getGeometricSchemaList()
        for schema in schemaList:
            if schema not in ['views', 'validation']:
                self.schemaComboBox.addItem(schema)
    
    @pyqtSlot()
    def on_classNameLineEdit_editingFinished(self):
        text = self.classNameLineEdit.text()
        while text[-1] == '_':
            self.classNameLineEdit.setText(text[0:-1])
            text = text[0:-1]
    
    @pyqtSlot(str)
    def on_classNameLineEdit_textEdited(self, newText):
        if len(newText) > 1:
            if newText[-1] == '_' and newText[-2] == '_':
                    self.classNameLineEdit.setText(newText[0:-1])
    
    @pyqtSlot(bool, name='on_addAttributePushButton_clicked')
    def addCellWidget(self, uiParameterJsonDict = None):
        index = self.tableWidget.rowCount()
        self.tableWidget.insertRow(index)
        newAttribute = AddAttributeWidget(self.abstractDb, uiParameterJsonDict = uiParameterJsonDict)
        self.tableWidget.setCellWidget(index,0,newAttribute)

    @pyqtSlot(bool)
    def on_removePushButton_clicked(self):
        selected = self.tableWidget.selectedIndexes()
        rowList = [i.row() for i in selected]
        rowList.sort(reverse=True)
        for row in rowList:
            self.tableWidget.removeRow(row)
    
    def getTitle(self):
        return self.title
    
    def setTitle(self, title):
        self.title = title
    
    def getChildWidgetList(self):
        childWidgetList = []
        for i in range(self.tableWidget.rowCount()):
            childWidgetList.append(self.tableWidget.cellWidget(i,0))
        return childWidgetList
    
    def validate(self):
        if self.categoryLineEdit.text() == '':
            return False
        if self.classNameLineEdit.text() == '':
            return False
        if self.geomComboBox.currentIndex() == 0:
            return False
        #TODO: validate attributes
        return True

    def validateDiagnosis(self):
        invalidatedReason = ''
        if self.categoryLineEdit.text() == '':
            invalidatedReason += self.tr('Class must have a category.\n')
        if self.classNameLineEdit.text() == '':
            invalidatedReason += self.tr('Class must have a name.\n')
        if self.geomComboBox.currentIndex() == 0:
            invalidatedReason += self.tr('Class must have a geometric primitive.\n')
        #TODO: validate attributes
        return invalidatedReason

    def getJSONTag(self):
        if not self.validate():
            raise Exception(self.tr('Error in class ')+ self.title + ' : ' + self.validateDiagnosis())
        schema = self.schemaComboBox.currentText()
        name = '_'.join([ self.categoryLineEdit.text(), self.classNameLineEdit.text(), self.geomUiDict[self.geomComboBox.currentText()]['sufix'] ])
        widgetList = self.getChildWidgetList()
        attrList = []
        #create pk attr
        pkItem = self.jsonBuilder.buildAttributeElement('id', 'serial', True, False)
        attrList.append(pkItem)
        #create geom attr
        geomItem = self.jsonBuilder.buildAttributeElement('geom', self.geomUiDict[self.geomComboBox.currentText()]['type'], False, False)
        attrList.append(geomItem)
        for widget in widgetList:
            newAttrJson = widget.getJSONTag()
            if isinstance(newAttrJson,list):
                for i in newAttrJson:
                    attrList.append(i)
            else:
                attrList.append(newAttrJson)
        return [self.jsonBuilder.buildClassElement(schema,name,attrList)]

    def getUiParameterJsonDict(self):
        """
        builds a dict with the following format:
        {
            'schemaComboBox': --text of selected item on schemaComboBox --
            'categoryLineEdit': --text of categoryLineEdit --
            'classNameLineEdit' : --text of classNameLineEdit --
            'geomComboBoxIdx' : --index of selected item on schemaComboBox --
            'attrWidgetList' : [--list of uiParameterJsonDict from each attributeWidget--]
        }
        """
        uiParameterJsonDict = dict()
        uiParameterJsonDict['schemaComboBox'] = self.schemaComboBox.currentText()
        uiParameterJsonDict['categoryLineEdit'] = self.categoryLineEdit.text()
        uiParameterJsonDict['classNameLineEdit'] = self.classNameLineEdit.text()
        uiParameterJsonDict['geomComboBoxIdx'] = self.geomComboBox.currentIndex()
        uiParameterJsonDict['attrWidgetList'] = []
        widgetList = self.getChildWidgetList()
        for widget in widgetList:
            uiParameterJsonDict['attrWidgetList'].append(widget.getUiParameterJsonDict())
        return uiParameterJsonDict

            
Example #12
0
class NewAttributeWidget(QtGui.QWidget, FORM_CLASS):
    def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
        """Constructor."""
        super(self.__class__, self).__init__(parent)
        self.abstractDb = abstractDb
        self.setupUi(self)
        self.addAttributeWidget.abstractDb = abstractDb
        self.jsonBuilder = CustomJSONBuilder()
        self.populateSchemaCombo()
        self.populateFromUiParameterJsonDict(uiParameterJsonDict)
    
    def populateFromUiParameterJsonDict(self, uiParameterJsonDict):
        """
        {
            'schemaComboBox': --current text of schemaComboBox --
            'tableComboBox': --current text of tableComboBox--
            'allTablesCheckBox': --state of allTablesCheckBox--
            'attrWidget' : -- uiParameterJson from addAttributeWidget--
        }
        """
        if uiParameterJsonDict:
            if uiParameterJsonDict['allTablesCheckBox']:
                self.allTablesCheckBox.setCheckState(Qt.Checked)
            else:
                schemaIdx = self.schemaComboBox.findText(uiParameterJsonDict['schemaComboBox'], flags = Qt.MatchExactly)
                self.schemaComboBox.setCurrentIndex(schemaIdx)
                tableIdx = self.tableComboBox.findText(uiParameterJsonDict['tableComboBox'], flags = Qt.MatchExactly)
                self.tableComboBox.setCurrentIndex(tableIdx)
            self.addAttributeWidget.populateFromUiParameterJsonDict(uiParameterJsonDict['attrWidget'])
    
    def getTitle(self):
        return self.title
    
    def setTitle(self, title):
        self.title = title
    
    def populateSchemaCombo(self):
        self.schemaComboBox.clear()
        self.schemaComboBox.addItem(self.tr('Select a schema'))
        schemaList = self.abstractDb.getGeometricSchemaList()
        for schema in schemaList:
            if schema not in ['views', 'validation']:
                self.schemaComboBox.addItem(schema)
    
    @pyqtSlot(int)
    def on_schemaComboBox_currentIndexChanged(self, idx):
        if idx == 0:
            self.tableComboBox.clear()
            self.tableComboBox.setEnabled(False)
        else:
            schema = self.schemaComboBox.currentText()
            self.tableComboBox.setEnabled(True)
            self.tableComboBox.clear()
            self.tableComboBox.addItem(self.tr('Select a table'))
            tableList = self.abstractDb.getGeometricTableListFromSchema(schema)
            for table in tableList:
                self.tableComboBox.addItem(table)
    
    @pyqtSlot(int)
    def on_allTablesCheckBox_stateChanged(self,idx):
        if idx == 2:
            self.tableComboBox.clear()
            self.tableComboBox.setEnabled(False)
            self.schemaComboBox.clear()
            self.schemaComboBox.setEnabled(False)
        else:
            self.schemaComboBox.setEnabled(True)
            self.populateSchemaCombo()
    
    def validate(self):
        if not self.allTablesCheckBox.isChecked():
            if self.tableComboBox.currentText() == '':
                return False
            if self.schemaComboBox.currentText() == '':
                return False
        return self.addAttributeWidget.validate()

    def validateDiagnosis(self):
        invalidatedReason = ''
        if self.tableComboBox.currentIndex() == 0:
            invalidatedReason += self.tr('A table name must be chosen.\n')
        if self.schemaComboBox.currentIndex() == 0:
            invalidatedReason += self.tr('A schema must be chosen.\n')
        invalidatedReason += self.addAttributeWidget.validateDiagnosis()
        return invalidatedReason
    
    def getJSONTag(self):
        if not self.validate():
            raise Exception(self.tr('Error in attribute ')+ self.title + ' : ' + self.validateDiagnosis())
        schema = self.schemaComboBox.currentText()
        tableName = self.tableComboBox.currentText()
        attrList = [self.addAttributeWidget.getJSONTag()]
        if not self.allTablesCheckBox.isChecked():
            bloodLine = [i for i in self.abstractDb.getInheritanceBloodLine(tableName) if i <> tableName]
            return [self.jsonBuilder.buildNewAttributeElement(schema, tableName, attrList, childrenToAlter = bloodLine)]
        else:
            attrModList = []
            classTuppleList = self.abstractDb.getParentGeomTables(getTupple = True)
            for tupple in classTuppleList:
                schema, tableName = tupple
                if schema not in ('views', 'validation'):
                    bloodLine = [i for i in self.abstractDb.getInheritanceBloodLine(tableName) if i <> tableName]
                    attrModList.append(self.jsonBuilder.buildNewAttributeElement(schema, tableName, attrList, childrenToAlter = bloodLine)) 
            return attrModList
    
    def getUiParameterJsonDict(self):
        """
        builds a dict with the following format:
        {
            'schemaComboBox': --current text of schemaComboBox --
            'tableComboBox': --current text of tableComboBox--
            'allTablesCheckBox': --state of allTablesCheckBox--
            'attrWidget' : -- uiParameterJson from addAttributeWidget--
        }
        """
        uiParameterJsonDict = dict()
        uiParameterJsonDict['schemaComboBox'] = self.schemaComboBox.currentText()
        uiParameterJsonDict['tableComboBox'] = self.tableComboBox.currentText()
        uiParameterJsonDict['allTablesCheckBox'] = self.allTablesCheckBox.isChecked()
        uiParameterJsonDict['attrWidget'] = self.addAttributeWidget.getUiParameterJsonDict()
        return uiParameterJsonDict
Example #13
0
class AddAttributeWidget(QtGui.QWidget, FORM_CLASS):
    def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
        """Constructor."""
        super(self.__class__, self).__init__(parent)
        self.abstractDb = abstractDb
        self.setupUi(self)
        regex = QtCore.QRegExp('[a-z]*')
        validator = QtGui.QRegExpValidator(regex, self.nameLineEdit)
        self.nameLineEdit.setValidator(validator)
        self.domainSetter = None
        self.jsonBuilder = CustomJSONBuilder()
        self.populateFromUiParameterJsonDict(uiParameterJsonDict)
    
    def populateFromUiParameterJsonDict(self, uiParameterJsonDict):
        """
        populates ui from  uiParameterJsonDict with the following keys:
        {
            'nameLineEdit': --text of selected item on nameLineEdit --
            'typeComboBox': --index of selected item on typeComboBox --
            'notNullcheckBox' : --True or False for notNullcheckBox isChecked --
            'defaultComboBox' : --text of selected item on typeComboBox --
            'references' : dict from domainSetter
        }
        """
        if uiParameterJsonDict:
            self.nameLineEdit.setText(uiParameterJsonDict['nameLineEdit'])
            if uiParameterJsonDict['references']:
                idx = self.typeComboBox.findText(self.tr('EDGV Domain'), flags = Qt.MatchExactly)
                self.typeComboBox.setCurrentIndex(idx)
                self.instantiateDomainSetter(uiParameterJsonDict['references'])
            else:
                self.typeComboBox.setCurrentIndex(int(uiParameterJsonDict['typeComboBox']))
            if uiParameterJsonDict['notNullcheckBox']:
                self.notNullcheckBox.setCheckState(2)
            idx = self.defaultComboBox.findText(uiParameterJsonDict['defaultComboBox'], flags = Qt.MatchExactly)
            self.defaultComboBox.setCurrentIndex(idx)

    def enableItems(self, enabled):
        self.referencesLabel.setEnabled(enabled)
        self.referencesLineEdit.setEnabled(enabled)
        self.referencesPushButton.setEnabled(enabled)
        self.defaultLabel.setEnabled(enabled)
        self.defaultComboBox.setEnabled(enabled)
    
    @pyqtSlot(int)
    def on_typeComboBox_currentIndexChanged(self, idx):
        edgvDomainIdx = self.typeComboBox.findText(self.tr('EDGV Domain'), flags = Qt.MatchExactly)
        if idx == edgvDomainIdx:
            self.enableItems(True)
        else:
            self.enableItems(False)
            self.referencesLineEdit.setText('')
            self.defaultComboBox.clear()
            self.domainSetter = None
    
    @pyqtSlot(bool)
    def on_referencesPushButton_clicked(self):
        if not self.domainSetter:
            self.instantiateDomainSetter()
        else:
            self.domainSetter.show()

    def instantiateDomainSetter(self, uiParameterJsonDict = None):
        self.domainSetter = DomainSetter(self.abstractDb, uiParameterJsonDict)
        self.domainSetter.domainChanged.connect(self.populateDefaultCombo)
        if not uiParameterJsonDict:
            self.domainSetter.exec_()
        else:
            self.domainSetter.applyChanges()

    @pyqtSlot(str, dict, list)
    def populateDefaultCombo(self, domainName, domainDict, filterClause):
        self.referencesLineEdit.setText(domainName)
        self.defaultComboBox.clear()
        addList = ['']
        for domain in domainDict.keys():
            if filterClause == dict(): 
                if domain not in addList:
                    addList.append(domain)
            elif domain in filterClause.keys():
                if domain not in addList:
                    addList.append(domain)
        for item in addList:
            self.defaultComboBox.addItem(item)
    
    def getChildWidgets(self):
        return self.domainSetter

    def validate(self):
        invalidatedList = []
        if self.nameLineEdit.text() == '':
            return False
        if self.typeComboBox.currentIndex() == 0:
            return False
        return True
    
    def validateDiagnosis(self):
        invalidatedReason = ''
        if self.nameLineEdit.text() == '':
            invalidatedReason += self.tr('Attribute must have a name.\n')
        if self.typeComboBox.currentIndex() == 0:
            invalidatedReason += self.tr('Attribute must have a type.\n')
        return invalidatedReason

    def getJSONTag(self):
        if not self.validate():
            raise Exception(self.validateDiagnosis())
        attrName = self.nameLineEdit.text()
        attrType = self.typeComboBox.currentText()
        if attrType == self.tr('EDGV Domain'):
            attrType = 'smallint'
        isPk = False
        if self.notNullcheckBox.isChecked():
            isNullable = False
        else:
            isNullable = True
        defaultComboCurrentText = self.defaultComboBox.currentText()
        if not self.domainSetter:
            return self.jsonBuilder.buildAttributeElement(attrName, attrType, isPk, isNullable)
        else:
            if defaultComboCurrentText == '':
                defaultValue = None
            else:
                defaultValue = self.domainSetter.domainDict[defaultComboCurrentText]
            references = self.domainSetter.domainName
            filter = self.domainSetter.filterClause.values()
            return [self.jsonBuilder.buildAttributeElement(attrName, attrType, isPk, isNullable, defaultValue, references, filter)]
        
    def getUiParameterJsonDict(self):
        """
        builds a dict with the following format:
        {
            'nameLineEdit': --text of selected item on nameLineEdit --
            'typeComboBox': --text of selected item on typeComboBox --
            'notNullcheckBox' : --True or False for notNullcheckBox isChecked --
            'defaultComboBox' : --text of selected item on typeComboBox --
            'references' : dict from domainSetter
        }
        """
        uiParameterJsonDict = dict()
        uiParameterJsonDict['nameLineEdit'] = self.nameLineEdit.text()
        uiParameterJsonDict['typeComboBox'] = self.typeComboBox.currentText()
        uiParameterJsonDict['notNullcheckBox'] = self.notNullcheckBox.isChecked()
        uiParameterJsonDict['defaultComboBox'] = self.defaultComboBox.currentText()
        uiParameterJsonDict['references'] = None
        if self.domainSetter:
            uiParameterJsonDict['references'] = self.domainSetter.getUiParameterJsonDict()
        return uiParameterJsonDict
Example #14
0
class ChangeFilterWidget(QtGui.QWidget, FORM_CLASS):
    populateSingleValue = pyqtSignal()
    populateListValue = pyqtSignal()

    def __init__(self, abstractDb, uiParameterJsonDict=None, parent=None):
        """Constructor."""
        super(self.__class__, self).__init__(parent)
        self.abstractDb = abstractDb
        self.setupUi(self)
        self.jsonBuilder = CustomJSONBuilder()
        self.populateSchemaCombo()
        self.hideWidgetList([
            self.singleValueLabel, self.singleValueComboBox,
            self.actionComboBox
        ])
        self.singleAttribute = True
        self.filterCustomSelectorWidget.setTitle(
            self.tr('Select filter values'))
        self.populateSingleValue.connect(self.populateWidgetWithSingleValue)
        self.populateListValue.connect(self.populateWidgetWithListValue)
        geomTypeDict = self.abstractDb.getGeomTypeDict()
        geomDict = self.abstractDb.getGeomDict(geomTypeDict)
        self.domainDict = self.abstractDb.getDbDomainDict(geomDict)
        self.inhTree = self.abstractDb.getInheritanceTreeDict()
        self.utils = Utils()
        self.actionDict = {
            self.tr('Add to Filter (Leave empty if filter is empty)'):
            'addEmpty',
            self.tr('Add to Filter (Add value to empty filter)'): 'add',
            self.tr('Remove from Filter'): 'remove'
        }
        self.populateFromUiParameterJsonDict(uiParameterJsonDict)

    def populateFromUiParameterJsonDict(self, uiParameterJsonDict):
        """
        {
            'schemaComboBox': --current text of schemaComboBox --
            'tableComboBox': ---current text of tableComboBox --
            'attributeComboBox': ---current text of attributeComboBox --
            'allAttributesCheckBox': --current state of allAttributesCheckBox--
            'allTablesCheckBox': --current state of allTablesCheckBox--
            'filterCustomSelectorWidgetToList': [--list of selected values on filterCustomSelectorWidget--]
            'singleValueComboBox': --current text of singleValueComboBox--
            'actionComboBoxIdx': --current index of actionComboBoxIdx--
        }
        """
        if uiParameterJsonDict:
            if uiParameterJsonDict['allTablesCheckBox']:
                self.allTablesCheckBox.setCheckState(Qt.Checked)
                singleValueIdx = self.singleValueComboBox.findText(
                    uiParameterJsonDict['singleValueComboBox'],
                    flags=Qt.MatchExactly)
                self.singleValueComboBox.setCurrentIndex(singleValueIdx)
                self.actionComboBox.setCurrentIndex(
                    uiParameterJsonDict['actionComboBoxIdx'])
            else:
                schemaIdx = self.schemaComboBox.findText(
                    uiParameterJsonDict['schemaComboBox'],
                    flags=Qt.MatchExactly)
                self.schemaComboBox.setCurrentIndex(schemaIdx)
                tableIdx = self.tableComboBox.findText(
                    uiParameterJsonDict['tableComboBox'],
                    flags=Qt.MatchExactly)
                self.tableComboBox.setCurrentIndex(tableIdx)
                if uiParameterJsonDict['allAttributesCheckBox']:
                    self.allAttributesCheckBox.setCheckState(Qt.Checked)
                    singleValueIdx = self.singleValueComboBox.findText(
                        uiParameterJsonDict['singleValueComboBox'],
                        flags=Qt.MatchExactly)
                    self.singleValueComboBox.setCurrentIndex(singleValueIdx)
                    self.actionComboBox.setCurrentIndex(
                        uiParameterJsonDict['actionComboBoxIdx'])
                else:
                    attributeIdx = self.attributeComboBox.findText(
                        uiParameterJsonDict['attributeComboBox'],
                        flags=Qt.MatchExactly)
                    self.attributeComboBox.setCurrentIndex(attributeIdx)
                    self.filterCustomSelectorWidget.selectItems(
                        True,
                        selectedItems=uiParameterJsonDict[
                            'filterCustomSelectorWidgetToList'])

    def populateInheritanceTree(self, nodeList):
        self.treeWidget.clear()
        rootNode = self.treeWidget.invisibleRootItem()
        for node in nodeList:
            firstNonRootNode = self.utils.find_all_paths(
                self.inhTree, 'root', node)[0][1]
            self.utils.createTreeWidgetFromDict(
                rootNode,
                {firstNonRootNode: self.inhTree['root'][firstNonRootNode]},
                self.treeWidget, 0)
        self.treeWidget.sortItems(0, Qt.AscendingOrder)
        self.treeWidget.expandAll()

    def populateSchemaCombo(self):
        self.schemaComboBox.clear()
        self.schemaComboBox.addItem(self.tr('Select a schema'))
        schemaList = self.abstractDb.getGeometricSchemaList()
        for schema in schemaList:
            if schema not in ['views', 'validation']:
                self.schemaComboBox.addItem(schema)

    def hideWidgetList(self, widgetList):
        for widget in widgetList:
            widget.hide()

    def showWidgetList(self, widgetList):
        for widget in widgetList:
            widget.show()

    @pyqtSlot(int)
    def on_schemaComboBox_currentIndexChanged(self, idx):
        if idx == 0:
            self.tableComboBox.clear()
            self.tableComboBox.setEnabled(False)
            self.attributeComboBox.clear()
            self.attributeComboBox.setEnabled(False)
        else:
            schema = self.schemaComboBox.currentText()
            self.tableComboBox.setEnabled(True)
            self.tableComboBox.clear()
            self.tableComboBox.addItem(self.tr('Select a table'))
            tableList = self.abstractDb.getGeometricTableListFromSchema(schema)
            for table in tableList:
                self.tableComboBox.addItem(table)

    @pyqtSlot(int)
    def on_tableComboBox_currentIndexChanged(self, idx):
        if idx == 0:
            self.attributeComboBox.clear()
            self.attributeComboBox.setEnabled(False)
        else:
            schema = self.schemaComboBox.currentText()
            tableName = self.tableComboBox.currentText()
            self.attributeComboBox.setEnabled(True)
            self.attributeComboBox.clear()
            self.attributeComboBox.addItem(self.tr('Select an attribute'))
            if tableName in self.domainDict.keys():
                attributeList = self.domainDict[tableName]['columns'].keys()
                for attribute in attributeList:
                    self.attributeComboBox.addItem(attribute)

    @pyqtSlot(int, name='on_schemaComboBox_currentIndexChanged')
    @pyqtSlot(int, name='on_attributeComboBox_currentIndexChanged')
    @pyqtSlot(int, name='on_tableComboBox_currentIndexChanged')
    def populateWidgetWithSingleValue(self):
        if self.allTablesCheckBox.checkState() == 2 or (
                self.allAttributesCheckBox.checkState() == 2
                and self.schemaComboBox.currentIndex() <> 0
                and self.tableComboBox.currentIndex() <> 0):
            self.attributeComboBox.clear()
            self.attributeComboBox.setEnabled(False)
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            self.singleValueComboBox.clear()
            self.singleValueComboBox.addItem(
                self.tr('Select a value to alter'))
            if self.allAttributesCheckBox.checkState() == 2:
                tableList = [self.tableComboBox.currentText()]
            else:
                tableList = self.domainDict.keys()
            allValueList = []
            idxList = []
            for tableName in tableList:
                for attrName in self.domainDict[tableName]['columns'].keys():
                    for code in self.domainDict[tableName]['columns'][
                            attrName]['values']:
                        value = self.domainDict[tableName]['columns'][
                            attrName]['values'][code]
                        if value not in allValueList:
                            allValueList.append(value)

            for value in allValueList:
                for tableName in tableList:
                    for attrName in self.domainDict[tableName]['columns'].keys(
                    ):
                        if value not in self.domainDict[tableName]['columns'][
                                attrName]['values'].values():
                            idx = allValueList.index(value)
                            if idx not in idxList:
                                idxList.append(idx)
            idxList.sort(reverse=True)
            for idx in idxList:
                allValueList.pop(idx)
            for value in allValueList:
                self.singleValueComboBox.addItem(value)
            self.populateInheritanceTree(tableList)
            QApplication.restoreOverrideCursor()

    @pyqtSlot(int, name='on_schemaComboBox_currentIndexChanged')
    @pyqtSlot(int, name='on_attributeComboBox_currentIndexChanged')
    @pyqtSlot(int, name='on_tableComboBox_currentIndexChanged')
    def populateWidgetWithListValue(self):
        self.filterCustomSelectorWidget.clearAll()
        if self.allTablesCheckBox.checkState(
        ) == 2 or self.allAttributesCheckBox.checkState() == 2:
            return
        if self.schemaComboBox.currentIndex() == 0:
            return
        if self.tableComboBox.currentIndex() == 0:
            self.treeWidget.clear()
            return
        tableName = self.tableComboBox.currentText()
        self.populateInheritanceTree([tableName])
        if self.attributeComboBox.currentIndex() == 0:
            return
        filterList = []
        attributeName = self.attributeComboBox.currentText()
        tableFilter = []
        filterToList = []
        if tableName in self.domainDict.keys():
            if attributeName in self.domainDict[tableName]['columns'].keys():
                attrDomainDict = self.domainDict[tableName]['columns'][
                    attributeName]['values']
                tableFilter = self.domainDict[tableName]['columns'][
                    attributeName]['constraintList']
                filterToList = [attrDomainDict[i] for i in tableFilter]
                filterFromList = [
                    i for i in attrDomainDict.values() if i not in filterToList
                ]
                self.filterCustomSelectorWidget.setFromList(filterFromList,
                                                            unique=True)
                self.filterCustomSelectorWidget.setToList(filterToList)

    @pyqtSlot(int)
    def on_allTablesCheckBox_stateChanged(self, state):
        self.hideOrShowWidgets()
        if state == 0:
            self.allAttributesCheckBox.setEnabled(True)
            self.schemaComboBox.setCurrentIndex(0)
            self.schemaComboBox.setEnabled(True)
        elif state == 2:
            self.allAttributesCheckBox.setEnabled(False)
            self.allAttributesCheckBox.setCheckState(0)
            self.schemaComboBox.setCurrentIndex(0)
            self.schemaComboBox.setEnabled(False)

    @pyqtSlot(int)
    def on_allAttributesCheckBox_stateChanged(self, state):
        if state == 2:
            self.allTablesCheckBox.setEnabled(False)
            self.allTablesCheckBox.setCheckState(0)
            self.attributeComboBox.setCurrentIndex(0)
            self.attributeComboBox.setEnabled(False)
        if state == 0:
            self.allTablesCheckBox.setEnabled(True)
            self.attributeComboBox.setEnabled(True)
        self.hideOrShowWidgets()

    def hideOrShowWidgets(self):
        if self.allAttributesCheckBox.checkState(
        ) == 2 or self.allTablesCheckBox.checkState() == 2:
            self.filterCustomSelectorWidget.hide()
            self.singleValueLabel.show()
            self.singleValueComboBox.show()
            self.actionComboBox.show()
            self.populateSingleValue.emit()
        else:
            self.filterCustomSelectorWidget.show()
            self.singleValueLabel.hide()
            self.singleValueComboBox.hide()
            self.actionComboBox.hide()
            self.tableComboBox.currentIndexChanged.emit(
                self.tableComboBox.currentIndex())
            self.populateListValue.emit()

    def getTitle(self):
        return self.title

    def setTitle(self, title):
        self.title = title

    def validate(self):
        if self.allTablesCheckBox.checkState() == 2:
            if self.singleValueComboBox.currentIndex() == 0:
                return False
            if self.actionComboBox.currentIndex() == 0:
                return False
        elif self.allAttributesCheckBox.checkState() == 2:
            if self.singleValueComboBox.currentIndex() == 0:
                return False
            if self.actionComboBox.currentIndex() == 0:
                return False
            if self.schemaComboBox.currentIndex() == 0:
                return False
            if self.tableComboBox.currentIndex() == 0:
                return False
        else:
            if self.schemaComboBox.currentIndex() == 0:
                return False
            if self.tableComboBox.currentIndex() == 0:
                return False
            if self.attributeComboBox.currentIndex() == 0:
                return False
        return True

    def validateDiagnosis(self):
        invalidatedReason = ''
        if self.allTablesCheckBox.checkState() == 2:
            if self.singleValueComboBox.currentIndex() == 0:
                invalidatedReason += self.tr('A value must be chosen.\n')
            if self.actionComboBox.currentIndex() == 0:
                invalidatedReason += self.tr('An action must be chosen.\n')
        elif self.allAttributesCheckBox.checkState() == 2:
            if self.singleValueComboBox.currentIndex() == 0:
                invalidatedReason += self.tr('A value must be chosen.\n')
            if self.actionComboBox.currentIndex() == 0:
                invalidatedReason += self.tr('An action must be chosen.\n')
            if self.schemaComboBox.currentIndex() == 0:
                invalidatedReason += self.tr('A schema must be chosen.\n')
            if self.tableComboBox.currentIndex() == 0:
                invalidatedReason += self.tr('A table must be chosen.\n')
        else:
            if self.schemaComboBox.currentIndex() == 0:
                invalidatedReason += self.tr('A schema must be chosen.\n')
            if self.tableComboBox.currentIndex() == 0:
                invalidatedReason += self.tr('A table must be chosen.\n')
            if self.attributeComboBox.currentIndex() == 0:
                invalidatedReason += self.tr('An attribute must be chosen.\n')
        return invalidatedReason

    def getJSONTag(self):
        if not self.validate():
            raise Exception(
                self.tr('Error in change filter customization ') + self.title +
                ' : ' + self.validateDiagnosis())
        jsonList = []
        inhConstrDict = self.abstractDb.getInheritanceConstraintDict()
        if self.allAttributesCheckBox.checkState() == 2:
            tableName = self.tableComboBox.currentText()
            schema = self.schemaComboBox.currentText()
            self.batchGetJsonTag(schema, tableName, jsonList, inhConstrDict)
        elif self.allTablesCheckBox.checkState() == 2:
            tableList = self.inhTree['root'].keys()
            for tableName in tableList:
                schema = self.abstractDb.getTableSchemaFromDb(tableName)
                self.batchGetJsonTag(schema, tableName, jsonList,
                                     inhConstrDict)
        else:
            tableName = self.tableComboBox.currentText()
            schema = self.schemaComboBox.currentText()
            attrName = self.attributeComboBox.currentText()
            if tableName in self.domainDict.keys():
                if attrName in self.domainDict[tableName]['columns'].keys():
                    attrDomainDict = self.domainDict[tableName]['columns'][
                        attrName]['values']
                    isMulti = self.domainDict[tableName]['columns'][attrName][
                        'isMulti']
            newFilter = [
                i for i in attrDomainDict.keys()
                if attrDomainDict[i] in self.filterCustomSelectorWidget.toLs
            ]
            self.getJsonTagFromOneTable(schema, tableName, attrName, jsonList,
                                        inhConstrDict, newFilter, isMulti)
        return jsonList

    def batchGetJsonTag(self, schema, tableName, jsonList, inhConstrDict):
        if tableName in self.domainDict.keys():
            for attrName in self.domainDict[tableName]['columns'].keys():
                attrDomainDict = self.domainDict[tableName]['columns'][
                    attrName]['values']
                isMulti = self.domainDict[tableName]['columns'][attrName][
                    'isMulti']
                newFilter = self.domainDict[tableName]['columns'][attrName][
                    'constraintList']
                valueText = self.singleValueComboBox.currentText()
                code = [
                    i for i in attrDomainDict.keys()
                    if attrDomainDict[i] == valueText
                ][0]
                if self.actionDict[self.actionComboBox.currentText()] == 'add':
                    if code not in newFilter: newFilter.append(code)
                elif self.actionDict[
                        self.actionComboBox.currentText()] == 'addEmpty':
                    if newFilter == []:
                        continue
                else:
                    if code in newFilter: newFilter.pop(code)
                self.getJsonTagFromOneTable(schema, tableName, attrName,
                                            jsonList, inhConstrDict, newFilter,
                                            isMulti)

    def getJsonTagFromOneTable(self, schema, tableName, attrName, jsonList,
                               inhConstrDict, newFilter, isMulti):
        originalFilterList = []
        if tableName in inhConstrDict.keys():
            if attrName in inhConstrDict[tableName].keys():
                originalFilterList = inhConstrDict[tableName][attrName]
        if originalFilterList == newFilter: return
        elif originalFilterList <> []:
            for item in originalFilterList:
                newElement = self.jsonBuilder.alterFilterElement(
                    item['schema'], item['tableName'], attrName,
                    item['constraintName'], item['filter'], newFilter, isMulti)
                if newElement not in jsonList:
                    jsonList.append(newElement)
        else:
            nodeLineage = self.utils.getNodeLineage(tableName, self.inhTree)
            firstInLineage = None
            for node in nodeLineage:
                if node in self.domainDict.keys():
                    if attrName in self.domainDict[node]['columns'].keys():
                        firstInLineage = node
                        break
                else:
                    schema = self.abstractDb.getTableSchemaFromDb(node)
                    if node in self.abstractDb.getAttributeListFromTable(
                            schema, node):
                        firstInLineage = node
                        break
            newElement = self.jsonBuilder.alterFilterElement(
                schema, firstInLineage, attrName,
                '_'.join([firstInLineage, attrName,
                          'ks']), [], newFilter, isMulti)
            if newElement not in jsonList:
                jsonList.append(newElement)

    def getUiParameterJsonDict(self):
        """
        builds a dict with the following format:
        {
            'schemaComboBox': --current text of schemaComboBox --
            'tableComboBox': ---current text of tableComboBox --
            'attributeComboBox': ---current text of attributeComboBox --
            'allAttributesCheckBox': --current state of allAttributesCheckBox--
            'allTablesCheckBox': --current state of allTablesCheckBox--
            'filterCustomSelectorWidgetToList': [--list of selected values on filterCustomSelectorWidget--]
            'singleValueComboBox': --current text of singleValueComboBox--
            'actionComboBoxIdx': --current index of actionComboBox--
        }
        """
        uiParameterJsonDict = dict()
        uiParameterJsonDict[
            'schemaComboBox'] = self.schemaComboBox.currentText()
        uiParameterJsonDict['tableComboBox'] = self.tableComboBox.currentText()
        uiParameterJsonDict[
            'attributeComboBox'] = self.attributeComboBox.currentText()
        uiParameterJsonDict[
            'allAttributesCheckBox'] = self.allAttributesCheckBox.isChecked()
        uiParameterJsonDict[
            'allTablesCheckBox'] = self.allTablesCheckBox.isChecked()
        uiParameterJsonDict[
            'filterCustomSelectorWidgetToList'] = self.filterCustomSelectorWidget.toLs
        uiParameterJsonDict[
            'singleValueComboBox'] = self.singleValueComboBox.currentText()
        uiParameterJsonDict[
            'actionComboBoxIdx'] = self.actionComboBox.currentIndex()
        return uiParameterJsonDict
class NewDomainValueWidget(QtGui.QWidget, FORM_CLASS):
    def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
        """Constructor."""
        super(self.__class__, self).__init__(parent)
        self.abstractDb = abstractDb
        self.setupUi(self)
        self.jsonBuilder = CustomJSONBuilder()
        self.populateDomainCombo()
        regex = QtCore.QRegExp('[0-9]*')
        validator = QtGui.QRegExpValidator(regex, self.codeLineEdit)
        self.codeLineEdit.setValidator(validator)
        self.populateFromUiParameterJsonDict(uiParameterJsonDict)
    
    def populateFromUiParameterJsonDict(self, uiParameterJsonDict):
        """
        builds ui from uiParameterJsonDict
        {
            'domainComboBox': --current text of domainComboBox --
            'allDomainCheckBox': --state of allDomainCheckBox--
            'codeLineEdit': --current text of codeLineEdit--
            'codeNameLineEdit': --current text of codeNameLineEdit--
        }
        """
        if uiParameterJsonDict:
            if uiParameterJsonDict['allDomainCheckBox']:
                self.allDomainCheckBox.setCheckState(Qt.Checked)
            else:
                domainIdx = self.domainComboBox.findText(uiParameterJsonDict['domainComboBox'], flags = Qt.MatchExactly)
                self.domainComboBox.setCurrentIndex(domainIdx)
            self.codeLineEdit.setText(uiParameterJsonDict['codeLineEdit'])
            self.codeNameLineEdit.setText(uiParameterJsonDict['codeNameLineEdit'])
                
    def populateDomainCombo(self):
        self.domainTableList = self.abstractDb.getDomainTables()
        self.domainComboBox.clear()
        self.domainComboBox.addItem(self.tr('Select a domain'))
        for domain in self.domainTableList:
            self.domainComboBox.addItem(domain)
    
    @pyqtSlot(int)
    def on_domainComboBox_currentIndexChanged(self, idx):
        if idx == 0:
            self.codeLineEdit.clear()
            self.codeLineEdit.setEnabled(False)
            self.codeNameLineEdit.clear()
            self.codeNameLineEdit.setEnabled(False)
        else:
            self.codeLineEdit.setEnabled(True)
            self.codeNameLineEdit.setEnabled(True)
        self.codeLineEdit.editingFinished.emit()
    
    @pyqtSlot(int)
    def on_allDomainCheckBox_stateChanged(self, state):
        if state == 2:
            self.domainComboBox.clear()
        else:
            self.populateDomainCombo()
        self.codeLineEdit.editingFinished.emit()
    
    @pyqtSlot()
    def on_codeLineEdit_editingFinished(self):
        if self.domainComboBox.currentIndex() == 0:
            self.codeLineEdit.setStyleSheet('')
            self.codeLineEdit.setToolTip('')
            return
        if self.allDomainCheckBox.checkState() == 2:
            domainValues = self.abstractDb.getAllDomainValues()
        else:
            domainValues = self.abstractDb.getAllDomainValues(domainTableList = [self.domainComboBox.currentText()])
        currentValue = self.codeLineEdit.text()
        if currentValue == '':
            self.codeLineEdit.setStyleSheet('')
            self.codeLineEdit.setToolTip('')
        elif int(currentValue) in domainValues:
            self.codeLineEdit.setStyleSheet("border: 1px solid red;")
            self.codeLineEdit.setToolTip(self.tr('Code value already exists, choose another.'))
        else:
            self.codeLineEdit.setStyleSheet('')
            self.codeLineEdit.setToolTip('')

    def getTitle(self):
        return self.title
    
    def setTitle(self, title):
        self.title = title

    def validate(self):
        if self.codeLineEdit.text() == '':
            return False
        if self.codeNameLineEdit.text() == '':
            return False
        if self.allDomainCheckBox.checkState() == 2:
            return True
        else:
            if self.domainComboBox.currentIndex() == 0:
                return False
        return True

    def validateDiagnosis(self):
        invalidatedReason = ''
        if self.codeLineEdit.text() == '':
            invalidatedReason += self.tr('A code value must be entered.\n')
        if self.codeNameLineEdit.text() == '':
            invalidatedReason += self.tr('A code name value must be entered.\n')
        if self.domainComboBox.currentIndex() == 0 and self.allDomainCheckBox.checkState() <> 2:
            invalidatedReason += self.tr('A domain table must be chosen.\n')
        return invalidatedReason
    
    def getJSONTag(self):
        if not self.validate():
            raise Exception(self.tr('Error in new domain value ')+ self.title + ' : ' + self.validateDiagnosis())
        code = self.codeLineEdit.text()
        codeName = self.codeNameLineEdit.text()
        jsonList = []
        if self.allDomainCheckBox.checkState() <> 2:
            domainName = self.domainComboBox.currentText()
            jsonList.append(self.jsonBuilder.addDomainValueElement(domainName, code, codeName))
        else:
            for domainName in self.domainTableList:
                jsonList.append(self.jsonBuilder.addDomainValueElement(domainName, code, codeName))
        return jsonList

    def getUiParameterJsonDict(self):
        """
        builds a dict with the following format:
        {
            'domainComboBox': --current text of domainComboBox --
            'allDomainCheckBox': --state of allDomainCheckBox--
            'codeLineEdit': --current text of codeLineEdit--
            'codeNameLineEdit': --current text of codeNameLineEdit--
        }
        """
        uiParameterJsonDict = dict()
        uiParameterJsonDict['domainComboBox'] = self.domainComboBox.currentText()
        uiParameterJsonDict['allDomainCheckBox'] = self.allDomainCheckBox.isChecked()
        uiParameterJsonDict['codeLineEdit'] = self.codeLineEdit.text()
        uiParameterJsonDict['codeNameLineEdit'] = self.codeNameLineEdit.text()
        return uiParameterJsonDict
        
Example #16
0
class ChangeFilterWidget(QtGui.QWidget, FORM_CLASS):
    populateSingleValue = pyqtSignal()
    populateListValue = pyqtSignal()
    def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
        """Constructor."""
        super(self.__class__, self).__init__(parent)
        self.abstractDb = abstractDb
        self.setupUi(self)
        self.jsonBuilder = CustomJSONBuilder()
        self.populateSchemaCombo()
        self.hideWidgetList([self.singleValueLabel, self.singleValueComboBox, self.actionComboBox])
        self.singleAttribute = True
        self.filterCustomSelectorWidget.setTitle(self.tr('Select filter values'))
        self.populateSingleValue.connect(self.populateWidgetWithSingleValue)
        self.populateListValue.connect(self.populateWidgetWithListValue)
        geomTypeDict = self.abstractDb.getGeomTypeDict()
        geomDict = self.abstractDb.getGeomDict(geomTypeDict)
        self.domainDict = self.abstractDb.getDbDomainDict(geomDict)
        self.inhTree = self.abstractDb.getInheritanceTreeDict()
        self.utils = Utils()
        self.actionDict = {self.tr('Add to Filter (Leave empty if filter is empty)'):'addEmpty', self.tr('Add to Filter (Add value to empty filter)'):'add',self.tr('Remove from Filter'):'remove'}
        self.populateFromUiParameterJsonDict(uiParameterJsonDict)
    
    def populateFromUiParameterJsonDict(self, uiParameterJsonDict):
        """
        {
            'schemaComboBox': --current text of schemaComboBox --
            'tableComboBox': ---current text of tableComboBox --
            'attributeComboBox': ---current text of attributeComboBox --
            'allAttributesCheckBox': --current state of allAttributesCheckBox--
            'allTablesCheckBox': --current state of allTablesCheckBox--
            'filterCustomSelectorWidgetToList': [--list of selected values on filterCustomSelectorWidget--]
            'singleValueComboBox': --current text of singleValueComboBox--
            'actionComboBoxIdx': --current index of actionComboBoxIdx--
        }
        """
        if uiParameterJsonDict:
            if uiParameterJsonDict['allTablesCheckBox']:
                self.allTablesCheckBox.setCheckState(Qt.Checked)
                singleValueIdx = self.singleValueComboBox.findText(uiParameterJsonDict['singleValueComboBox'], flags = Qt.MatchExactly)
                self.singleValueComboBox.setCurrentIndex(singleValueIdx)
                self.actionComboBox.setCurrentIndex(uiParameterJsonDict['actionComboBoxIdx'])
            else:
                schemaIdx = self.schemaComboBox.findText(uiParameterJsonDict['schemaComboBox'], flags = Qt.MatchExactly)
                self.schemaComboBox.setCurrentIndex(schemaIdx)
                tableIdx = self.tableComboBox.findText(uiParameterJsonDict['tableComboBox'], flags = Qt.MatchExactly)
                self.tableComboBox.setCurrentIndex(tableIdx)
                if uiParameterJsonDict['allAttributesCheckBox']:
                    self.allAttributesCheckBox.setCheckState(Qt.Checked)
                    singleValueIdx = self.singleValueComboBox.findText(uiParameterJsonDict['singleValueComboBox'], flags = Qt.MatchExactly)
                    self.singleValueComboBox.setCurrentIndex(singleValueIdx)
                    self.actionComboBox.setCurrentIndex(uiParameterJsonDict['actionComboBoxIdx'])
                else:
                    attributeIdx = self.attributeComboBox.findText(uiParameterJsonDict['attributeComboBox'], flags = Qt.MatchExactly)
                    self.attributeComboBox.setCurrentIndex(attributeIdx)
                    self.filterCustomSelectorWidget.selectItems(True, selectedItems=uiParameterJsonDict['filterCustomSelectorWidgetToList'])

    def populateInheritanceTree(self, nodeList):
        self.treeWidget.clear()
        rootNode = self.treeWidget.invisibleRootItem()
        for node in nodeList:
            firstNonRootNode = self.utils.find_all_paths(self.inhTree, 'root', node)[0][1]
            self.utils.createTreeWidgetFromDict(rootNode, {firstNonRootNode:self.inhTree['root'][firstNonRootNode]}, self.treeWidget, 0)
        self.treeWidget.sortItems(0, Qt.AscendingOrder)
        self.treeWidget.expandAll()

    def populateSchemaCombo(self):
        self.schemaComboBox.clear()
        self.schemaComboBox.addItem(self.tr('Select a schema'))
        schemaList = self.abstractDb.getGeometricSchemaList()
        for schema in schemaList:
            if schema not in ['views', 'validation']:
                self.schemaComboBox.addItem(schema)

    def hideWidgetList(self, widgetList):
        for widget in widgetList:
            widget.hide()

    def showWidgetList(self, widgetList):
        for widget in widgetList:
            widget.show()

    @pyqtSlot(int)
    def on_schemaComboBox_currentIndexChanged(self, idx):
        if idx == 0:
            self.tableComboBox.clear()
            self.tableComboBox.setEnabled(False)
            self.attributeComboBox.clear()
            self.attributeComboBox.setEnabled(False)
        else:
            schema = self.schemaComboBox.currentText()
            self.tableComboBox.setEnabled(True)
            self.tableComboBox.clear()
            self.tableComboBox.addItem(self.tr('Select a table'))
            tableList = self.abstractDb.getGeometricTableListFromSchema(schema)
            for table in tableList:
                self.tableComboBox.addItem(table)

    @pyqtSlot(int)
    def on_tableComboBox_currentIndexChanged(self, idx):
        if idx == 0:
            self.attributeComboBox.clear()
            self.attributeComboBox.setEnabled(False)
        else:
            schema = self.schemaComboBox.currentText()
            tableName = self.tableComboBox.currentText()
            self.attributeComboBox.setEnabled(True)
            self.attributeComboBox.clear()
            self.attributeComboBox.addItem(self.tr('Select an attribute'))
            if tableName in self.domainDict.keys():
                attributeList = self.domainDict[tableName]['columns'].keys()
                for attribute in attributeList:
                    self.attributeComboBox.addItem(attribute)

    @pyqtSlot(int, name='on_schemaComboBox_currentIndexChanged')
    @pyqtSlot(int, name='on_attributeComboBox_currentIndexChanged')
    @pyqtSlot(int, name='on_tableComboBox_currentIndexChanged')
    def populateWidgetWithSingleValue(self):
        if self.allTablesCheckBox.checkState() == 2 or (self.allAttributesCheckBox.checkState() == 2 and self.schemaComboBox.currentIndex() <> 0 and self.tableComboBox.currentIndex() <> 0):
            self.attributeComboBox.clear()
            self.attributeComboBox.setEnabled(False)
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            self.singleValueComboBox.clear()
            self.singleValueComboBox.addItem(self.tr('Select a value to alter'))
            if self.allAttributesCheckBox.checkState() == 2:
                tableList = [self.tableComboBox.currentText()]
            else:
                tableList = self.domainDict.keys()
            allValueList = []
            idxList = []
            for tableName in tableList:
                for attrName in self.domainDict[tableName]['columns'].keys():
                    for code in self.domainDict[tableName]['columns'][attrName]['values']:
                        value = self.domainDict[tableName]['columns'][attrName]['values'][code]
                        if value not in allValueList:
                            allValueList.append(value)

            for value in allValueList:
                for tableName in tableList:
                    for attrName in self.domainDict[tableName]['columns'].keys():
                        if value not in self.domainDict[tableName]['columns'][attrName]['values'].values():
                            idx = allValueList.index(value)
                            if idx not in idxList:
                                idxList.append(idx)
            idxList.sort(reverse=True)
            for idx in idxList:
                allValueList.pop(idx)
            for value in allValueList:
                self.singleValueComboBox.addItem(value)
            self.populateInheritanceTree(tableList)
            QApplication.restoreOverrideCursor()

    @pyqtSlot(int, name='on_schemaComboBox_currentIndexChanged')
    @pyqtSlot(int, name='on_attributeComboBox_currentIndexChanged')
    @pyqtSlot(int, name='on_tableComboBox_currentIndexChanged')
    def populateWidgetWithListValue(self):
        self.filterCustomSelectorWidget.clearAll()
        if self.allTablesCheckBox.checkState() == 2 or self.allAttributesCheckBox.checkState() == 2:
            return
        if self.schemaComboBox.currentIndex() == 0:
            return
        if self.tableComboBox.currentIndex() == 0:
            self.treeWidget.clear()
            return
        tableName = self.tableComboBox.currentText()
        self.populateInheritanceTree([tableName])
        if self.attributeComboBox.currentIndex() == 0:
            return
        filterList = []
        attributeName = self.attributeComboBox.currentText()
        tableFilter = []
        filterToList = []
        if tableName in self.domainDict.keys():
            if attributeName in self.domainDict[tableName]['columns'].keys():
                attrDomainDict = self.domainDict[tableName]['columns'][attributeName]['values']
                tableFilter = self.domainDict[tableName]['columns'][attributeName]['constraintList']
                filterToList = [attrDomainDict[i] for i in tableFilter]
                filterFromList = [i for i in attrDomainDict.values() if i not in filterToList]
                self.filterCustomSelectorWidget.setFromList(filterFromList, unique=True)
                self.filterCustomSelectorWidget.setToList(filterToList)

    @pyqtSlot(int)
    def on_allTablesCheckBox_stateChanged(self, state):
        self.hideOrShowWidgets()
        if state == 0:
            self.allAttributesCheckBox.setEnabled(True)
            self.schemaComboBox.setCurrentIndex(0)
            self.schemaComboBox.setEnabled(True)
        elif state == 2:
            self.allAttributesCheckBox.setEnabled(False)
            self.allAttributesCheckBox.setCheckState(0)
            self.schemaComboBox.setCurrentIndex(0)
            self.schemaComboBox.setEnabled(False)

    @pyqtSlot(int)
    def on_allAttributesCheckBox_stateChanged(self, state):
        if state == 2:
            self.allTablesCheckBox.setEnabled(False)
            self.allTablesCheckBox.setCheckState(0)
            self.attributeComboBox.setCurrentIndex(0)
            self.attributeComboBox.setEnabled(False)
        if state == 0:
            self.allTablesCheckBox.setEnabled(True)
            self.attributeComboBox.setEnabled(True)
        self.hideOrShowWidgets()

    def hideOrShowWidgets(self):
        if self.allAttributesCheckBox.checkState() == 2 or self.allTablesCheckBox.checkState() == 2:
            self.filterCustomSelectorWidget.hide()
            self.singleValueLabel.show()
            self.singleValueComboBox.show()
            self.actionComboBox.show()
            self.populateSingleValue.emit()
        else:
            self.filterCustomSelectorWidget.show()
            self.singleValueLabel.hide()
            self.singleValueComboBox.hide()
            self.actionComboBox.hide()
            self.tableComboBox.currentIndexChanged.emit(self.tableComboBox.currentIndex())
            self.populateListValue.emit()

    def getTitle(self):
        return self.title

    def setTitle(self, title):
        self.title = title

    def validate(self):
        if self.allTablesCheckBox.checkState() == 2:
             if self.singleValueComboBox.currentIndex() == 0:
                 return False
             if self.actionComboBox.currentIndex() == 0:
                 return False
        elif self.allAttributesCheckBox.checkState() == 2:
             if self.singleValueComboBox.currentIndex() == 0:
                 return False
             if self.actionComboBox.currentIndex() == 0:
                 return False
             if self.schemaComboBox.currentIndex() == 0:
                 return False
             if self.tableComboBox.currentIndex() == 0:
                 return False
        else:
             if self.schemaComboBox.currentIndex() == 0:
                 return False
             if self.tableComboBox.currentIndex() == 0:
                 return False
             if self.attributeComboBox.currentIndex() == 0:
                 return False
        return True

    def validateDiagnosis(self):
        invalidatedReason = ''
        if self.allTablesCheckBox.checkState() == 2:
             if self.singleValueComboBox.currentIndex() == 0:
                 invalidatedReason += self.tr('A value must be chosen.\n')
             if self.actionComboBox.currentIndex() == 0:
                 invalidatedReason += self.tr('An action must be chosen.\n')
        elif self.allAttributesCheckBox.checkState() == 2:
             if self.singleValueComboBox.currentIndex() == 0:
                 invalidatedReason += self.tr('A value must be chosen.\n')
             if self.actionComboBox.currentIndex() == 0:
                 invalidatedReason += self.tr('An action must be chosen.\n')
             if self.schemaComboBox.currentIndex() == 0:
                 invalidatedReason += self.tr('A schema must be chosen.\n')
             if self.tableComboBox.currentIndex() == 0:
                 invalidatedReason += self.tr('A table must be chosen.\n')
        else:
             if self.schemaComboBox.currentIndex() == 0:
                 invalidatedReason += self.tr('A schema must be chosen.\n')
             if self.tableComboBox.currentIndex() == 0:
                 invalidatedReason += self.tr('A table must be chosen.\n')
             if self.attributeComboBox.currentIndex() == 0:
                 invalidatedReason += self.tr('An attribute must be chosen.\n')
        return invalidatedReason

    def getJSONTag(self):
        if not self.validate():
            raise Exception(self.tr('Error in change filter customization ')+ self.title + ' : ' + self.validateDiagnosis())
        jsonList = []
        inhConstrDict = self.abstractDb.getInheritanceConstraintDict()
        if self.allAttributesCheckBox.checkState() == 2:
            tableName = self.tableComboBox.currentText()
            schema = self.schemaComboBox.currentText()
            self.batchGetJsonTag(schema, tableName, jsonList, inhConstrDict)
        elif self.allTablesCheckBox.checkState() == 2:
            tableList = self.inhTree['root'].keys()
            for tableName in tableList:
                schema = self.abstractDb.getTableSchemaFromDb(tableName)
                self.batchGetJsonTag(schema, tableName, jsonList, inhConstrDict)
        else:
            tableName = self.tableComboBox.currentText()
            schema = self.schemaComboBox.currentText()
            attrName = self.attributeComboBox.currentText()
            if tableName in self.domainDict.keys():
                if attrName in self.domainDict[tableName]['columns'].keys():
                    attrDomainDict = self.domainDict[tableName]['columns'][attrName]['values']
                    isMulti = self.domainDict[tableName]['columns'][attrName]['isMulti']
            newFilter = [i for i in attrDomainDict.keys() if attrDomainDict[i] in self.filterCustomSelectorWidget.toLs]
            self.getJsonTagFromOneTable(schema, tableName, attrName, jsonList, inhConstrDict, newFilter, isMulti)
        return jsonList

    def batchGetJsonTag(self, schema, tableName, jsonList, inhConstrDict):
        if tableName in self.domainDict.keys():
            for attrName in self.domainDict[tableName]['columns'].keys():
                attrDomainDict = self.domainDict[tableName]['columns'][attrName]['values']
                isMulti = self.domainDict[tableName]['columns'][attrName]['isMulti']
                newFilter = self.domainDict[tableName]['columns'][attrName]['constraintList']
                valueText = self.singleValueComboBox.currentText()
                code = [i for i in attrDomainDict.keys() if attrDomainDict[i] == valueText][0]
                if self.actionDict[self.actionComboBox.currentText()] == 'add':
                    if code not in newFilter: newFilter.append(code)
                elif self.actionDict[self.actionComboBox.currentText()] == 'addEmpty':
                    if newFilter == []:
                        continue
                else:
                    if code in newFilter: newFilter.pop(code)
                self.getJsonTagFromOneTable(schema, tableName, attrName, jsonList, inhConstrDict, newFilter, isMulti)

    def getJsonTagFromOneTable(self, schema, tableName, attrName, jsonList, inhConstrDict, newFilter, isMulti):
        originalFilterList = []
        if tableName in inhConstrDict.keys():
            if attrName in inhConstrDict[tableName].keys():
                originalFilterList = inhConstrDict[tableName][attrName]
        if originalFilterList == newFilter: return
        elif originalFilterList <> []:
            for item in originalFilterList:
                newElement = self.jsonBuilder.alterFilterElement(item['schema'], item['tableName'], attrName, item['constraintName'], item['filter'], newFilter, isMulti)
                if newElement not in jsonList:
                    jsonList.append(newElement)
        else:
            nodeLineage = self.utils.getNodeLineage(tableName, self.inhTree)
            firstInLineage = None
            for node in nodeLineage:
                if node in self.domainDict.keys():
                    if attrName in self.domainDict[node]['columns'].keys():
                        firstInLineage = node
                        break
                else:
                    schema = self.abstractDb.getTableSchemaFromDb(node)
                    if node in self.abstractDb.getAttributeListFromTable(schema, node):
                        firstInLineage = node
                        break
            newElement = self.jsonBuilder.alterFilterElement(schema, firstInLineage, attrName, '_'.join([firstInLineage,attrName,'ks']), [], newFilter, isMulti)
            if newElement not in jsonList:
                jsonList.append(newElement)

    def getUiParameterJsonDict(self):
        """
        builds a dict with the following format:
        {
            'schemaComboBox': --current text of schemaComboBox --
            'tableComboBox': ---current text of tableComboBox --
            'attributeComboBox': ---current text of attributeComboBox --
            'allAttributesCheckBox': --current state of allAttributesCheckBox--
            'allTablesCheckBox': --current state of allTablesCheckBox--
            'filterCustomSelectorWidgetToList': [--list of selected values on filterCustomSelectorWidget--]
            'singleValueComboBox': --current text of singleValueComboBox--
            'actionComboBoxIdx': --current index of actionComboBox--
        }
        """
        uiParameterJsonDict = dict()
        uiParameterJsonDict['schemaComboBox'] = self.schemaComboBox.currentText()
        uiParameterJsonDict['tableComboBox'] = self.tableComboBox.currentText()
        uiParameterJsonDict['attributeComboBox'] = self.attributeComboBox.currentText()
        uiParameterJsonDict['allAttributesCheckBox'] = self.allAttributesCheckBox.isChecked()
        uiParameterJsonDict['allTablesCheckBox'] = self.allTablesCheckBox.isChecked()
        uiParameterJsonDict['filterCustomSelectorWidgetToList'] = self.filterCustomSelectorWidget.toLs
        uiParameterJsonDict['singleValueComboBox'] = self.singleValueComboBox.currentText()
        uiParameterJsonDict['actionComboBoxIdx'] = self.actionComboBox.currentIndex()
        return uiParameterJsonDict
            
Example #17
0
class NewClassWidget(QtGui.QWidget, FORM_CLASS):
    def __init__(self, abstractDb, uiParameterJsonDict=None, parent=None):
        """Constructor."""
        super(self.__class__, self).__init__(parent)
        self.setupUi(self)
        self.geomUiDict = {
            self.tr('Point'): {
                'sufix': 'p',
                'type': 'MULTIPOINT([epsg])'
            },
            self.tr('Line'): {
                'sufix': 'l',
                'type': 'MULTILINESTRING([epsg])'
            },
            self.tr('Area'): {
                'sufix': 'a',
                'type': 'MULTIPOLYGON([epsg])'
            }
        }
        header = self.tableWidget.horizontalHeader()
        header.setStretchLastSection(True)
        regex = QtCore.QRegExp('[a-z][a-z\_]*')
        validator = QtGui.QRegExpValidator(regex, self.classNameLineEdit)
        self.classNameLineEdit.setValidator(validator)
        regex2 = QtCore.QRegExp('[a-z]*')
        validator2 = QtGui.QRegExpValidator(regex2, self.categoryLineEdit)
        self.categoryLineEdit.setValidator(validator2)
        self.abstractDb = abstractDb
        self.populateSchemaCombo()
        self.jsonBuilder = CustomJSONBuilder()
        self.populateFromUiParameterJsonDict(uiParameterJsonDict)

    def populateFromUiParameterJsonDict(self, uiParameterJsonDict):
        """
        populates ui from  uiParameterJsonDict with the following keys:
        {
            'schemaComboBox': --text of selected item on schemaComboBox --
            'categoryLineEdit': --text of categoryLineEdit --
            'classNameLineEdit' : --text of classNameLineEdit --
            'geomComboBoxIdx' : --index of selected item on schemaComboBox --
            'attrWidgetList' : [--list of uiParameterJsonDict from each attributeWidget--]
        }
        """
        if uiParameterJsonDict:
            idx = self.schemaComboBox.findText(
                uiParameterJsonDict['schemaComboBox'], flags=Qt.MatchExactly)
            self.schemaComboBox.setCurrentIndex(idx)
            self.categoryLineEdit.setText(
                uiParameterJsonDict['categoryLineEdit'])
            self.classNameLineEdit.setText(
                uiParameterJsonDict['classNameLineEdit'])
            self.geomComboBox.setCurrentIndex(
                int(uiParameterJsonDict['geomComboBoxIdx']))
            for attr in uiParameterJsonDict['attrWidgetList']:
                self.addCellWidget(uiParameterJsonDict=attr)

    def populateSchemaCombo(self):
        self.schemaComboBox.clear()
        schemaList = self.abstractDb.getGeometricSchemaList()
        for schema in schemaList:
            if schema not in ['views', 'validation']:
                self.schemaComboBox.addItem(schema)

    @pyqtSlot()
    def on_classNameLineEdit_editingFinished(self):
        text = self.classNameLineEdit.text()
        while text[-1] == '_':
            self.classNameLineEdit.setText(text[0:-1])
            text = text[0:-1]

    @pyqtSlot(str)
    def on_classNameLineEdit_textEdited(self, newText):
        if len(newText) > 1:
            if newText[-1] == '_' and newText[-2] == '_':
                self.classNameLineEdit.setText(newText[0:-1])

    @pyqtSlot(bool, name='on_addAttributePushButton_clicked')
    def addCellWidget(self, uiParameterJsonDict=None):
        index = self.tableWidget.rowCount()
        self.tableWidget.insertRow(index)
        newAttribute = AddAttributeWidget(
            self.abstractDb, uiParameterJsonDict=uiParameterJsonDict)
        self.tableWidget.setCellWidget(index, 0, newAttribute)

    @pyqtSlot(bool)
    def on_removePushButton_clicked(self):
        selected = self.tableWidget.selectedIndexes()
        rowList = [i.row() for i in selected]
        rowList.sort(reverse=True)
        for row in rowList:
            self.tableWidget.removeRow(row)

    def getTitle(self):
        return self.title

    def setTitle(self, title):
        self.title = title

    def getChildWidgetList(self):
        childWidgetList = []
        for i in range(self.tableWidget.rowCount()):
            childWidgetList.append(self.tableWidget.cellWidget(i, 0))
        return childWidgetList

    def validate(self):
        if self.categoryLineEdit.text() == '':
            return False
        if self.classNameLineEdit.text() == '':
            return False
        if self.geomComboBox.currentIndex() == 0:
            return False
        #TODO: validate attributes
        return True

    def validateDiagnosis(self):
        invalidatedReason = ''
        if self.categoryLineEdit.text() == '':
            invalidatedReason += self.tr('Class must have a category.\n')
        if self.classNameLineEdit.text() == '':
            invalidatedReason += self.tr('Class must have a name.\n')
        if self.geomComboBox.currentIndex() == 0:
            invalidatedReason += self.tr(
                'Class must have a geometric primitive.\n')
        #TODO: validate attributes
        return invalidatedReason

    def getJSONTag(self):
        if not self.validate():
            raise Exception(
                self.tr('Error in class ') + self.title + ' : ' +
                self.validateDiagnosis())
        schema = self.schemaComboBox.currentText()
        name = '_'.join([
            self.categoryLineEdit.text(),
            self.classNameLineEdit.text(),
            self.geomUiDict[self.geomComboBox.currentText()]['sufix']
        ])
        widgetList = self.getChildWidgetList()
        attrList = []
        #create pk attr
        pkItem = self.jsonBuilder.buildAttributeElement(
            'id', 'serial', True, False)
        attrList.append(pkItem)
        #create geom attr
        geomItem = self.jsonBuilder.buildAttributeElement(
            'geom', self.geomUiDict[self.geomComboBox.currentText()]['type'],
            False, False)
        attrList.append(geomItem)
        for widget in widgetList:
            newAttrJson = widget.getJSONTag()
            if isinstance(newAttrJson, list):
                for i in newAttrJson:
                    attrList.append(i)
            else:
                attrList.append(newAttrJson)
        return [self.jsonBuilder.buildClassElement(schema, name, attrList)]

    def getUiParameterJsonDict(self):
        """
        builds a dict with the following format:
        {
            'schemaComboBox': --text of selected item on schemaComboBox --
            'categoryLineEdit': --text of categoryLineEdit --
            'classNameLineEdit' : --text of classNameLineEdit --
            'geomComboBoxIdx' : --index of selected item on schemaComboBox --
            'attrWidgetList' : [--list of uiParameterJsonDict from each attributeWidget--]
        }
        """
        uiParameterJsonDict = dict()
        uiParameterJsonDict[
            'schemaComboBox'] = self.schemaComboBox.currentText()
        uiParameterJsonDict['categoryLineEdit'] = self.categoryLineEdit.text()
        uiParameterJsonDict['classNameLineEdit'] = self.classNameLineEdit.text(
        )
        uiParameterJsonDict[
            'geomComboBoxIdx'] = self.geomComboBox.currentIndex()
        uiParameterJsonDict['attrWidgetList'] = []
        widgetList = self.getChildWidgetList()
        for widget in widgetList:
            uiParameterJsonDict['attrWidgetList'].append(
                widget.getUiParameterJsonDict())
        return uiParameterJsonDict
Example #18
0
class AlterDefaultWidget(QtGui.QWidget, FORM_CLASS):
    def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
        """Constructor."""
        super(self.__class__, self).__init__(parent)
        self.abstractDb = abstractDb
        self.setupUi(self)
        self.jsonBuilder = CustomJSONBuilder()
        self.populateSchemaCombo()
        geomTypeDict = self.abstractDb.getGeomTypeDict()
        geomDict = self.abstractDb.getGeomDict(geomTypeDict)
        self.domainDict = self.abstractDb.getDbDomainDict(geomDict)
        self.utils = Utils()
        self.populateFromUiParameterJsonDict(uiParameterJsonDict)
    
    def populateFromUiParameterJsonDict(self, uiParameterJsonDict):
        """
        builds a dict with the following format:
        {
            'schemaComboBox': --current text of schemaComboBox --
            'tableComboBox': --current text of tableComboBox--
            'allAttributesCheckBox': --state of allAttributesCheckBox--
            'allTablesCheckBox': --state of allTablesCheckBox--
            'attributeComboBox': --current text of attributeComboBox--
            'singleValueComboBox': --current text of singleValueComboBox--
        }
        """
        if uiParameterJsonDict:
            if uiParameterJsonDict['allTablesCheckBox']:
                self.allTablesCheckBox.setCheckState(Qt.Checked)
            else:
                schemaIdx = self.schemaComboBox.findText(uiParameterJsonDict['schemaComboBox'], flags = Qt.MatchExactly)
                self.schemaComboBox.setCurrentIndex(schemaIdx)
                tableIdx = self.tableComboBox.findText(uiParameterJsonDict['tableComboBox'], flags = Qt.MatchExactly)
                self.tableComboBox.setCurrentIndex(tableIdx)
                if uiParameterJsonDict['allAttributesCheckBox']:
                    self.allAttributesCheckBox.setCheckState(Qt.Checked)
                else:
                    attributeIdx = self.attributeComboBox.findText(uiParameterJsonDict['attributeComboBox'], flags = Qt.MatchExactly)
                    self.attributeComboBox.setCurrentIndex(attributeIdx)
                idx = self.singleValueComboBox.findText(uiParameterJsonDict['singleValueComboBox'], flags = Qt.MatchExactly)
                self.singleValueComboBox.setCurrentIndex(idx)

    def populateSchemaCombo(self):
        self.schemaComboBox.clear()
        self.schemaComboBox.addItem(self.tr('Select a schema'))
        schemaList = self.abstractDb.getGeometricSchemaList()
        for schema in schemaList:
            if schema not in ['views', 'validation']:
                self.schemaComboBox.addItem(schema)

    @pyqtSlot(int)
    def on_schemaComboBox_currentIndexChanged(self, idx):
        if idx == 0:
            self.tableComboBox.clear()
            self.tableComboBox.setEnabled(False)
            self.attributeComboBox.clear()
            self.attributeComboBox.setEnabled(False)
            self.singleValueComboBox.clear()
        else:
            schema = self.schemaComboBox.currentText()
            self.tableComboBox.setEnabled(True)
            self.tableComboBox.clear()
            self.tableComboBox.addItem(self.tr('Select a table'))
            tableList = self.abstractDb.getGeometricTableListFromSchema(schema)
            for table in tableList:
                self.tableComboBox.addItem(table)

    @pyqtSlot(int)
    def on_tableComboBox_currentIndexChanged(self, idx):
        if idx == 0:
            self.attributeComboBox.clear()
            self.attributeComboBox.setEnabled(False)
        else:
            schema = self.schemaComboBox.currentText()
            tableName = self.tableComboBox.currentText()
            self.attributeComboBox.setEnabled(True)
            self.attributeComboBox.clear()
            self.attributeComboBox.addItem(self.tr('Select an attribute'))
            if tableName in self.domainDict.keys():
                attributeList = self.domainDict[tableName]['columns'].keys()
                for attribute in attributeList:
                    self.attributeComboBox.addItem(attribute)
            self.singleValueComboBox.clear()
    
    @pyqtSlot(int, name='on_schemaComboBox_currentIndexChanged')
    @pyqtSlot(int, name='on_tableComboBox_currentIndexChanged')
    def populateOnSelectAll(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        if self.allTablesCheckBox.checkState() == 2 or (self.allAttributesCheckBox.checkState() == 2 and self.schemaComboBox.currentIndex() <> 0 and self.tableComboBox.currentIndex() <> 0):
            self.attributeComboBox.clear()
            self.attributeComboBox.setEnabled(False)
            self.singleValueComboBox.clear()
            self.singleValueComboBox.addItem(self.tr('Select a value to alter'))
            if self.allAttributesCheckBox.checkState() == 2:
                tableList = [self.tableComboBox.currentText()]
            else:
                tableList = self.domainDict.keys()
            allValueList = []
            idxList = []
            for tableName in tableList:
                for attrName in self.domainDict[tableName]['columns'].keys():
                    for code in self.domainDict[tableName]['columns'][attrName]['values']:
                        value = self.domainDict[tableName]['columns'][attrName]['values'][code]
                        if value not in allValueList:
                            allValueList.append(value)
            for value in allValueList:
                for tableName in tableList:
                    for attrName in self.domainDict[tableName]['columns'].keys():
                        if value not in self.domainDict[tableName]['columns'][attrName]['values'].values():
                            idx = allValueList.index(value)
                            if idx not in idxList:
                                idxList.append(idx)
            idxList.sort(reverse=True)
            for idx in idxList:
                allValueList.pop(idx)
            for value in allValueList:
                self.singleValueComboBox.addItem(value)
        QApplication.restoreOverrideCursor()
    
    @pyqtSlot(int)
    def on_attributeComboBox_currentIndexChanged(self, idx):
        if idx == 0:
            QApplication.restoreOverrideCursor()
            return
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        filterList = []
        attributeName = self.attributeComboBox.currentText()
        tableFilter = []
        filterToList = []
        self.singleValueComboBox.clear()
        self.singleValueComboBox.addItem(self.tr('Select a value to alter'))
        tableName = self.tableComboBox.currentText()
        attributeName = self.attributeComboBox.currentText()
        if tableName in self.domainDict.keys():
            if attributeName in self.domainDict[tableName]['columns'].keys():
                attrDomainDict = self.domainDict[tableName]['columns'][attributeName]['values']
                for value in attrDomainDict.values():
                    self.singleValueComboBox.addItem(value)
                defaultCode = self.abstractDb.getDefaultFromDb(self.schemaComboBox.currentText(),tableName,attributeName)
                if defaultCode:
                    if 'ARRAY' in defaultCode or '@' in defaultCode:
                        #done to extract value from multi array
                        defaultCodeInt = int(defaultCode.replace('ARRAY','').replace('(','').replace(')','').replace(']','').replace('[','').replace('@','').replace('<','').split(':')[0])
                    else:
                        defaultCodeInt = int(defaultCode)
                    if defaultCodeInt in attrDomainDict.keys():
                        comboItem = self.singleValueComboBox.findText(attrDomainDict[defaultCodeInt], flags = Qt.MatchExactly)
                        self.singleValueComboBox.setCurrentIndex(comboItem)
        QApplication.restoreOverrideCursor()

    @pyqtSlot(int)
    def on_allTablesCheckBox_stateChanged(self, state):
        self.singleValueComboBox.clear()
        if state == 0:
            self.allAttributesCheckBox.setEnabled(True)
            self.schemaComboBox.setCurrentIndex(0)
            self.schemaComboBox.setEnabled(True)
        elif state == 2:
            self.allAttributesCheckBox.setEnabled(False)
            self.allAttributesCheckBox.setCheckState(0)
            self.schemaComboBox.setCurrentIndex(0)
            self.schemaComboBox.setEnabled(False)
            self.populateOnSelectAll()

    @pyqtSlot(int)
    def on_allAttributesCheckBox_stateChanged(self, state):
        self.singleValueComboBox.clear()
        if state == 2:
            self.allTablesCheckBox.setEnabled(False)
            self.allTablesCheckBox.setCheckState(0)
            self.attributeComboBox.setCurrentIndex(0)
            self.attributeComboBox.setEnabled(False)
            self.populateOnSelectAll()
        if state == 0:
            self.allTablesCheckBox.setEnabled(True)
            self.attributeComboBox.setEnabled(True)
            idx = self.tableComboBox.currentIndex()
            self.tableComboBox.currentIndexChanged.emit(idx)

    def getTitle(self):
        return self.title

    def setTitle(self, title):
        self.title = title

    def validate(self):
        if self.allTablesCheckBox.checkState() == 2:
             if self.singleValueComboBox.currentIndex() == 0:
                 return False
        elif self.allAttributesCheckBox.checkState() == 2:
             if self.singleValueComboBox.currentIndex() == 0:
                 return False
             if self.schemaComboBox.currentIndex() == 0:
                 return False
             if self.tableComboBox.currentIndex() == 0:
                 return False
        else:
            if self.singleValueComboBox.currentIndex() == 0:
                 return False
            if self.schemaComboBox.currentIndex() == 0:
                return False
            if self.tableComboBox.currentIndex() == 0:
                return False
            if self.attributeComboBox.currentIndex() == 0:
                return False
        return True

    def validateDiagnosis(self):
        invalidatedReason = ''
        if self.allTablesCheckBox.checkState() == 2:
             if self.singleValueComboBox.currentIndex() == 0:
                 invalidatedReason += self.tr('A value must be chosen.\n')
        elif self.allAttributesCheckBox.checkState() == 2:
             if self.singleValueComboBox.currentIndex() == 0:
                 invalidatedReason += self.tr('A value must be chosen.\n')
             if self.schemaComboBox.currentIndex() == 0:
                 invalidatedReason += self.tr('A schema must be chosen.\n')
             if self.tableComboBox.currentIndex() == 0:
                 invalidatedReason += self.tr('A table must be chosen.\n')
        else:             
            if self.singleValueComboBox.currentIndex() == 0:
                invalidatedReason += self.tr('A value must be chosen.\n')
            if self.schemaComboBox.currentIndex() == 0:
                invalidatedReason += self.tr('A schema must be chosen.\n')
            if self.tableComboBox.currentIndex() == 0:
                invalidatedReason += self.tr('A table must be chosen.\n')
            if self.attributeComboBox.currentIndex() == 0:
                invalidatedReason += self.tr('An attribute must be chosen.\n')
        return invalidatedReason

    def getJSONTag(self):
        if not self.validate():
            raise Exception(self.tr('Error in default customization ')+ self.title + ' : ' + self.validateDiagnosis())
        jsonList = []
        inhConstrDict = self.abstractDb.getInheritanceConstraintDict()
        if self.allAttributesCheckBox.checkState() == 2:
            tableName = self.tableComboBox.currentText()
            schema = self.schemaComboBox.currentText()
            if tableName in self.domainDict.keys():
                for attrName in self.domainDict[tableName]['columns'].keys():
                    self.getJsonTagFromOneTable(schema, tableName, attrName, jsonList)
        elif self.allTablesCheckBox.checkState() == 2:
            for tableName in self.domainDict.keys():
                schema = self.abstractDb.getTableSchemaFromDb(tableName)
                for attrName in self.domainDict[tableName]['columns'].keys():
                    self.getJsonTagFromOneTable(schema, tableName, attrName, jsonList)
        else:
            tableName = self.tableComboBox.currentText()
            schema = self.schemaComboBox.currentText()
            attrName = self.attributeComboBox.currentText()
            self.getJsonTagFromOneTable(schema, tableName, attrName, jsonList)
        return jsonList

    def getJsonTagFromOneTable(self, schema, tableName, attrName, jsonList):
        if tableName in self.domainDict.keys():
            if attrName in self.domainDict[tableName]['columns'].keys():
                attrDomainDict = self.domainDict[tableName]['columns'][attrName]['values']
                oldDefaultText = self.abstractDb.getDefaultFromDb(self.schemaComboBox.currentText(),tableName,attrName)
                if oldDefaultText:
                    if 'ARRAY' in oldDefaultText or '@' in oldDefaultText:
                        #done to build multi array
                        oldDefaultInt = int(oldDefaultText.replace('ARRAY','').replace('(','').replace(')','').replace(']','').replace('[','').replace('@','').replace('<','').split(':')[0])
                    else:
                        oldDefaultInt = int(oldDefaultText)
                newDefaultText = self.singleValueComboBox.currentText()
                newDefaultInt = [i for i in attrDomainDict.keys() if attrDomainDict[i] == newDefaultText][0]
                if oldDefaultText:
                    newDefault = oldDefaultText.replace(str(oldDefaultInt),str(newDefaultInt))
                else:
                    newDefault = str(newDefaultInt)
                newElement =  self.jsonBuilder.buildChangeDefaultElement(schema,tableName, attrName, oldDefaultText, newDefault)
                if newElement not in jsonList:
                    jsonList.append(newElement)

    def getUiParameterJsonDict(self):
        """
        builds a dict with the following format:
        {
            'schemaComboBox': --current text of schemaComboBox --
            'tableComboBox': --current text of tableComboBox--
            'allAttributesCheckBox': --state of allAttributesCheckBox--
            'allTablesCheckBox': --state of allTablesCheckBox--
            'attributeComboBox': --current text of attributeComboBox--
            'singleValueComboBox': --current text of singleValueComboBox--
        }
        """
        uiParameterJsonDict = dict()
        uiParameterJsonDict['schemaComboBox'] = self.schemaComboBox.currentText()
        uiParameterJsonDict['tableComboBox'] = self.tableComboBox.currentText()
        uiParameterJsonDict['allAttributesCheckBox'] = self.allAttributesCheckBox.isChecked()
        uiParameterJsonDict['allTablesCheckBox'] = self.allTablesCheckBox.isChecked()
        uiParameterJsonDict['attributeComboBox'] = self.attributeComboBox.currentText()
        uiParameterJsonDict['singleValueComboBox'] = self.singleValueComboBox.currentText()
        return uiParameterJsonDict
Example #19
0
class NewAttributeWidget(QtGui.QWidget, FORM_CLASS):
    def __init__(self, abstractDb, uiParameterJsonDict=None, parent=None):
        """Constructor."""
        super(self.__class__, self).__init__(parent)
        self.abstractDb = abstractDb
        self.setupUi(self)
        self.addAttributeWidget.abstractDb = abstractDb
        self.jsonBuilder = CustomJSONBuilder()
        self.populateSchemaCombo()
        self.populateFromUiParameterJsonDict(uiParameterJsonDict)

    def populateFromUiParameterJsonDict(self, uiParameterJsonDict):
        """
        {
            'schemaComboBox': --current text of schemaComboBox --
            'tableComboBox': --current text of tableComboBox--
            'allTablesCheckBox': --state of allTablesCheckBox--
            'attrWidget' : -- uiParameterJson from addAttributeWidget--
        }
        """
        if uiParameterJsonDict:
            if uiParameterJsonDict['allTablesCheckBox']:
                self.allTablesCheckBox.setCheckState(Qt.Checked)
            else:
                schemaIdx = self.schemaComboBox.findText(
                    uiParameterJsonDict['schemaComboBox'],
                    flags=Qt.MatchExactly)
                self.schemaComboBox.setCurrentIndex(schemaIdx)
                tableIdx = self.tableComboBox.findText(
                    uiParameterJsonDict['tableComboBox'],
                    flags=Qt.MatchExactly)
                self.tableComboBox.setCurrentIndex(tableIdx)
            self.addAttributeWidget.populateFromUiParameterJsonDict(
                uiParameterJsonDict['attrWidget'])

    def getTitle(self):
        return self.title

    def setTitle(self, title):
        self.title = title

    def populateSchemaCombo(self):
        self.schemaComboBox.clear()
        self.schemaComboBox.addItem(self.tr('Select a schema'))
        schemaList = self.abstractDb.getGeometricSchemaList()
        for schema in schemaList:
            if schema not in ['views', 'validation']:
                self.schemaComboBox.addItem(schema)

    @pyqtSlot(int)
    def on_schemaComboBox_currentIndexChanged(self, idx):
        if idx == 0:
            self.tableComboBox.clear()
            self.tableComboBox.setEnabled(False)
        else:
            schema = self.schemaComboBox.currentText()
            self.tableComboBox.setEnabled(True)
            self.tableComboBox.clear()
            self.tableComboBox.addItem(self.tr('Select a table'))
            tableList = self.abstractDb.getGeometricTableListFromSchema(schema)
            for table in tableList:
                self.tableComboBox.addItem(table)

    @pyqtSlot(int)
    def on_allTablesCheckBox_stateChanged(self, idx):
        if idx == 2:
            self.tableComboBox.clear()
            self.tableComboBox.setEnabled(False)
            self.schemaComboBox.clear()
            self.schemaComboBox.setEnabled(False)
        else:
            self.schemaComboBox.setEnabled(True)
            self.populateSchemaCombo()

    def validate(self):
        if not self.allTablesCheckBox.isChecked():
            if self.tableComboBox.currentText() == '':
                return False
            if self.schemaComboBox.currentText() == '':
                return False
        return self.addAttributeWidget.validate()

    def validateDiagnosis(self):
        invalidatedReason = ''
        if self.tableComboBox.currentIndex() == 0:
            invalidatedReason += self.tr('A table name must be chosen.\n')
        if self.schemaComboBox.currentIndex() == 0:
            invalidatedReason += self.tr('A schema must be chosen.\n')
        invalidatedReason += self.addAttributeWidget.validateDiagnosis()
        return invalidatedReason

    def getJSONTag(self):
        if not self.validate():
            raise Exception(
                self.tr('Error in attribute ') + self.title + ' : ' +
                self.validateDiagnosis())
        schema = self.schemaComboBox.currentText()
        tableName = self.tableComboBox.currentText()
        attrList = [self.addAttributeWidget.getJSONTag()]
        if not self.allTablesCheckBox.isChecked():
            bloodLine = [
                i for i in self.abstractDb.getInheritanceBloodLine(tableName)
                if i <> tableName
            ]
            return [
                self.jsonBuilder.buildNewAttributeElement(
                    schema, tableName, attrList, childrenToAlter=bloodLine)
            ]
        else:
            attrModList = []
            classTuppleList = self.abstractDb.getParentGeomTables(
                getTupple=True)
            for tupple in classTuppleList:
                schema, tableName = tupple
                if schema not in ('views', 'validation'):
                    bloodLine = [
                        i for i in self.abstractDb.getInheritanceBloodLine(
                            tableName) if i <> tableName
                    ]
                    attrModList.append(
                        self.jsonBuilder.buildNewAttributeElement(
                            schema,
                            tableName,
                            attrList,
                            childrenToAlter=bloodLine))
            return attrModList

    def getUiParameterJsonDict(self):
        """
        builds a dict with the following format:
        {
            'schemaComboBox': --current text of schemaComboBox --
            'tableComboBox': --current text of tableComboBox--
            'allTablesCheckBox': --state of allTablesCheckBox--
            'attrWidget' : -- uiParameterJson from addAttributeWidget--
        }
        """
        uiParameterJsonDict = dict()
        uiParameterJsonDict[
            'schemaComboBox'] = self.schemaComboBox.currentText()
        uiParameterJsonDict['tableComboBox'] = self.tableComboBox.currentText()
        uiParameterJsonDict[
            'allTablesCheckBox'] = self.allTablesCheckBox.isChecked()
        uiParameterJsonDict[
            'attrWidget'] = self.addAttributeWidget.getUiParameterJsonDict()
        return uiParameterJsonDict
Example #20
0
class CodeNameCustomizationWidget(QtGui.QWidget, FORM_CLASS):
    def __init__(self, abstractDb, uiParameterJsonDict=None, parent=None):
        """Constructor."""
        super(self.__class__, self).__init__(parent)
        self.abstractDb = abstractDb
        self.setupUi(self)
        self.jsonBuilder = CustomJSONBuilder()
        self.domainDict = dict()
        self.populateDomainCombo()
        self.populateFromUiParameterJsonDict(uiParameterJsonDict)

    def populateFromUiParameterJsonDict(self, uiParameterJsonDict):
        """
        builds ui from uiParameterJsonDict
        {
            'domainComboBox': --current text of domainComboBox --
            'oldCodeNameComboBox': ---current text of oldCodeNameComboBox --
            'newCodeNameLineEdit': --current text of newCodeNameLineEdit--
        }
        """
        if uiParameterJsonDict:
            domainIdx = self.domainComboBox.findText(
                uiParameterJsonDict['domainComboBox'], flags=Qt.MatchExactly)
            self.domainComboBox.setCurrentIndex(domainIdx)
            oldIdx = self.oldCodeNameComboBox.findText(
                uiParameterJsonDict['oldCodeNameComboBox'],
                flags=Qt.MatchExactly)
            self.oldCodeNameComboBox.setCurrentIndex(oldIdx)
            self.newCodeNameLineEdit.setText(
                uiParameterJsonDict['newCodeNameLineEdit'])

    def getTitle(self):
        return self.title

    def setTitle(self, title):
        self.title = title

    def populateDomainCombo(self):
        self.domainComboBox.clear()
        self.domainComboBox.addItem(self.tr('Choose a domain'))
        domainList = self.abstractDb.getDomainTables()
        for domain in domainList:
            self.domainComboBox.addItem(domain)

    @pyqtSlot(int)
    def on_domainComboBox_currentIndexChanged(self, idx):
        if idx <> 0:
            domainName = self.domainComboBox.currentText()
            self.oldCodeNameComboBox.setEnabled(True)
            self.oldCodeNameComboBox.clear()
            self.oldCodeNameComboBox.addItem('Choose a code name')
            self.domainDict = self.abstractDb.getDomainDictV2('dominios.' +
                                                              domainName)
            for codeName in self.domainDict.keys():
                self.oldCodeNameComboBox.addItem(codeName)
            self.newCodeNameLineEdit.setEnabled(True)
            self.newCodeNameLineEdit.clear()
        else:
            self.newCodeNameLineEdit.setEnabled(False)
            self.newCodeNameLineEdit.clear()
            self.oldCodeNameComboBox.setEnabled(False)
            self.oldCodeNameComboBox.clear()

    @pyqtSlot(int)
    def on_oldCodeNameComboBox_currentIndexChanged(self, idx):
        self.newCodeNameLineEdit.setEnabled(True)
        self.newCodeNameLineEdit.clear()

    def validate(self):
        if self.domainComboBox.currentIndex() == 0:
            return False
        if self.oldCodeNameComboBox.currentIndex() == 0:
            return False
        if self.newCodeNameLineEdit.text() == '':
            return False
        return True

    def validateDiagnosis(self):
        invalidatedReason = ''
        if self.domainComboBox.currentIndex() == 0:
            invalidatedReason += self.tr('A domain table must be chosen.\n')
        if self.oldCodeNameComboBox.currentIndex() == 0:
            invalidatedReason += self.tr(
                'An old code name value must be chosen.\n')
        if self.newCodeNameLineEdit.text() == '':
            invalidatedReason += self.tr(
                'A new code name value must be chosen.\n')
        invalidatedReason += self.addAttributeWidget.validateDiagnosis()
        return invalidatedReason

    def getJSONTag(self):
        if not self.validate():
            raise Exception(
                self.tr('Error in code name customization ') + self.title +
                ' : ' + self.validateDiagnosis())
        domainTable = self.domainComboBox.currentText()
        oldCodeName = self.oldCodeNameComboBox.currentText()
        newCodeName = self.newCodeNameLineEdit.text()
        codeValue = self.domainDict[oldCodeName]
        return [
            self.jsonBuilder.buildCodeNameToChangeElement(
                domainTable, codeValue, oldCodeName, newCodeName)
        ]

    def getUiParameterJsonDict(self):
        """
        builds a dict with the following format:
        {
            'domainComboBox': --current text of domainComboBox --
            'oldCodeNameComboBox': ---current text of oldCodeNameComboBox --
            'newCodeNameLineEdit': --current text of newCodeNameLineEdit--
        }
        """
        uiParameterJsonDict = dict()
        uiParameterJsonDict[
            'domainComboBox'] = self.domainComboBox.currentText()
        uiParameterJsonDict[
            'oldCodeNameComboBox'] = self.oldCodeNameComboBox.currentText()
        uiParameterJsonDict[
            'newCodeNameLineEdit'] = self.newCodeNameLineEdit.text()
        return uiParameterJsonDict
Example #21
0
class ChangeNullityWidget(QtGui.QWidget, FORM_CLASS):
    def __init__(self, abstractDb, uiParameterJsonDict = None, parent = None):
        """Constructor."""
        super(self.__class__, self).__init__(parent)
        self.abstractDb = abstractDb
        self.setupUi(self)
        self.jsonBuilder = CustomJSONBuilder()
        self.populateSchemaCombo()
        self.populateFromUiParameterJsonDict(uiParameterJsonDict)
    
    def populateFromUiParameterJsonDict(self, uiParameterJsonDict):
        """
        builds a dict with the following format:
        {
            'schemaComboBox': --current text of schemaComboBox --
            'tableComboBox': --current text of tableComboBox--
            'allAttributesCheckBox': --state of allAttributesCheckBox--
            'allTablesCheckBox': --state of allTablesCheckBox--
            'attributeComboBox': --current text of attributeComboBox--
            'actionComboBoxIdx': --current index of actionComboBox--
        }
        """
        if uiParameterJsonDict:
            if uiParameterJsonDict['allTablesCheckBox']:
                self.allTablesCheckBox.setCheckState(Qt.Checked)
            else:
                schemaIdx = self.schemaComboBox.findText(uiParameterJsonDict['schemaComboBox'], flags = Qt.MatchExactly)
                self.schemaComboBox.setCurrentIndex(schemaIdx)
                tableIdx = self.tableComboBox.findText(uiParameterJsonDict['tableComboBox'], flags = Qt.MatchExactly)
                self.tableComboBox.setCurrentIndex(tableIdx)
                if uiParameterJsonDict['allAttributesCheckBox']:
                    self.allAttributesCheckBox.setCheckState(Qt.Checked)
                else:
                    attributeIdx = self.attributeComboBox.findText(uiParameterJsonDict['attributeComboBox'], flags = Qt.MatchExactly)
                    self.attributeComboBox.setCurrentIndex(attributeIdx)
                self.actionComboBox.setCurrentIndex(uiParameterJsonDict['actionComboBoxIdx'])
    
    def populateSchemaCombo(self):
        self.schemaComboBox.clear()
        self.schemaComboBox.addItem(self.tr('Select a schema'))
        schemaList = self.abstractDb.getGeometricSchemaList()
        for schema in schemaList:
            if schema not in ['views', 'validation']:
                self.schemaComboBox.addItem(schema)

    @pyqtSlot(int)
    def on_schemaComboBox_currentIndexChanged(self, idx):
        if idx == 0:
            self.tableComboBox.clear()
            self.tableComboBox.setEnabled(False)
            self.attributeComboBox.clear()
            self.attributeComboBox.setEnabled(False)
        else:
            schema = self.schemaComboBox.currentText()
            self.tableComboBox.setEnabled(True)
            self.tableComboBox.clear()
            self.tableComboBox.addItem(self.tr('Select a table'))
            tableList = self.abstractDb.getGeometricTableListFromSchema(schema)
            for table in tableList:
                self.tableComboBox.addItem(table)
    
    @pyqtSlot(int)
    def on_tableComboBox_currentIndexChanged(self, idx):
        if idx == 0:
            self.attributeComboBox.clear()
            self.attributeComboBox.setEnabled(False)
        else:
            schema = self.schemaComboBox.currentText()
            tableName = self.tableComboBox.currentText()
            self.attributeComboBox.setEnabled(True)
            self.attributeComboBox.clear()
            self.attributeComboBox.addItem(self.tr('Select an attribute'))
            attributeList = self.abstractDb.getAttributeListFromTable(schema, tableName)
            for attribute in attributeList:
                self.attributeComboBox.addItem(attribute)
    
    @pyqtSlot(int)
    def on_allTablesCheckBox_stateChanged(self, state):
        if state == 0:
            self.allAttributesCheckBox.setEnabled(True)
            self.schemaComboBox.setCurrentIndex(0)
            self.schemaComboBox.setEnabled(True)
        elif state == 2:
            self.allAttributesCheckBox.setEnabled(False)
            self.allAttributesCheckBox.setCheckState(0)
            self.schemaComboBox.setCurrentIndex(0)
            self.schemaComboBox.setEnabled(False)
            
    
    @pyqtSlot(int)
    def on_allAttributesCheckBox_stateChanged(self, state):
        if state == 2:
            self.allTablesCheckBox.setEnabled(False)
            self.allTablesCheckBox.setCheckState(0)
            self.attributeComboBox.setCurrentIndex(0)
            self.attributeComboBox.setEnabled(False)
        if state == 0:
            self.allTablesCheckBox.setEnabled(True)
            self.attributeComboBox.setEnabled(True)
    
    def getTitle(self):
        return self.title
    
    def setTitle(self, title):
        self.title = title
    
    def validate(self):
        if self.actionComboBox.currentIndex() == 0:
            return False
        if self.allTablesCheckBox.checkState() == 2:
            return True
        if self.schemaComboBox.currentIndex() == 0:
            return False
        if self.tableComboBox.currentIndex() == 0:
            return False
        if self.allAttributesCheckBox.checkState() == 2:
            return True
        elif self.attributeComboBox.currentIndex() == 0:
            return False
        return True

    def validateDiagnosis(self):
        invalidatedReason = ''
        if self.schemaComboBox.currentIndex() == 0:
            invalidatedReason += self.tr('A schema must be chosen.\n')
        if self.tableComboBox.currentIndex() == 0:
            invalidatedReason += self.tr('A table must be chosen.\n')
        if self.actionComboBox.currentIndex() == 0:
            invalidatedReason += self.tr('An action be chosen.\n')
        if self.allAttributesCheckBox.checkState() <> 2 and self.attributeComboBox.currentIndex() == 0:
            invalidatedReason += self.tr('An attribute must be chosen.\n')
        return invalidatedReason
    
    def getJSONTag(self):
        if not self.validate():
            raise Exception(self.tr('Error in change nullity customization ')+ self.title + ' : ' + self.validateDiagnosis())
        if self.actionComboBox.currentIndex() == 1:
            notNull = True
        elif self.actionComboBox.currentIndex() == 2:
            notNull = False
        jsonList = []
        if self.allTablesCheckBox.checkState() == 2:
            attributeJsonList = self.abstractDb.getAttributeJsonFromDb()
            for attributeJson in attributeJsonList:
                schema = attributeJson['table_schema']
                table = attributeJson['table_name']
                for attrName in attributeJson['attributelist']:
                    jsonList.append(self.jsonBuilder.buildChangeNullityElement(schema, table, attrName, notNull))
        else:
            schema = self.schemaComboBox.currentText()
            table = self.tableComboBox.currentText()
            if self.allAttributesCheckBox.checkState() == 2:
                attrList = self.abstractDb.getAttributeListFromTable(schema, table)
                for attrName in attrList:
                    jsonList.append(self.jsonBuilder.buildChangeNullityElement(schema, table, attrName, notNull))
            else:
                attrName = self.attributeComboBox.currentText()
                jsonList.append(self.jsonBuilder.buildChangeNullityElement(schema, table, attrName, notNull))
        return jsonList

    def getUiParameterJsonDict(self):
        """
        builds a dict with the following format:
        {
            'schemaComboBox': --current text of schemaComboBox --
            'tableComboBox': --current text of tableComboBox--
            'allAttributesCheckBox': --state of allAttributesCheckBox--
            'allTablesCheckBox': --state of allTablesCheckBox--
            'attributeComboBox': --current text of attributeComboBox--
            'actionComboBoxIdx': --current index of actionComboBox--
        }
        """
        uiParameterJsonDict = dict()
        uiParameterJsonDict['schemaComboBox'] = self.schemaComboBox.currentText()
        uiParameterJsonDict['tableComboBox'] = self.tableComboBox.currentText()
        uiParameterJsonDict['allAttributesCheckBox'] = self.allAttributesCheckBox.isChecked()
        uiParameterJsonDict['allTablesCheckBox'] = self.allTablesCheckBox.isChecked()
        uiParameterJsonDict['attributeComboBox'] = self.attributeComboBox.currentText()
        uiParameterJsonDict['actionComboBoxIdx'] = self.actionComboBox.currentIndex()
        return uiParameterJsonDict