def assignCols(self): #Load source and target columns respectively srcCols = self._source_columns() for c in srcCols: srcItem = QListWidgetItem(c,self.lstSrcFields) srcItem.setCheckState(Qt.Unchecked) srcItem.setIcon(QIcon(":/plugins/stdm/images/icons/column.png")) self.lstSrcFields.addItem(srcItem) #Destination Columns tabIndex = int(self.field("tabIndex")) self.targetTab = self.destCheckedItem.text() targetCols = table_column_names(self.targetTab, False, True) #Remove geometry columns in the target columns list for gc in self.geomcols: colIndex = getIndex(targetCols,gc) if colIndex != -1: targetCols.remove(gc) #Remove 'id' column if there id_idx = getIndex(targetCols, 'id') if id_idx != -1: targetCols.remove('id') self._add_target_table_columns(targetCols)
def _map_column_values(self, feature, feature_defn, source_cols): """ Retrieves values for specific columns from the specified feature. :param feature: Input feature. :type feature: ogr.Feature :param feature_defn: Feature definition for the layer. :type feature_defn: ogr.FeatureDefn :param source_cols: List of columns whose respective values will be retrieved. :type source_cols: list :return: Collection containing pairs of column names and corresponding values. :rtype: dict """ col_values = {} if len(source_cols) == 0: return col_values for f in range(feature_defn.GetFieldCount()): field_defn = feature_defn.GetFieldDefn(f) field_name = field_defn.GetNameRef() match_idx = getIndex(source_cols, field_name) if match_idx != -1: field_value = feature.GetField(f) col_values[field_name] = field_value return col_values
def __init__(self, parent, source_cols, dest_table, dest_col, src_col): QDialog.__init__(self, parent) self.setupUi(self) TranslatorDialogBase.__init__(self, source_cols, dest_table, dest_col, src_col) self._notif_bar = NotificationBar(self.vl_notification) #Container of column names for an enumeration table self._enum_col_names = [] self._load_separators() #Init user selection to the corresponding UI controls self.txt_source_col.setText(self._src_col) #Remove selected column name from the 'other column' list sel_col_idx = getIndex(self._source_cols, self._src_col) if sel_col_idx != -1: self._source_cols.remove(self._src_col) #Load source columns self.cbo_src_other_col.addItem("") self.cbo_src_other_col.addItems(self._source_cols) #Load database tables self.cbo_enum_table.addItem("") self.cbo_enum_table.addItems(self.db_tables()) #Connect signals self.cbo_enum_table.currentIndexChanged.connect( self._on_enum_table_changed) self.cbo_primary_col.currentIndexChanged.connect( self._on_primary_col_changed)
def loadColumns(self,table): #Load textual and spatial (if available) columns #Get spatial columns first spColumns = table_column_names(table,True, creation_order=True) self.cboSpatialCols_2.clear() self.cboSpatialCols_2.addItems(spColumns) #Textual Columns self.lstSrcCols_2.clear() self.allCols = table_column_names(table, creation_order=True) for sc in spColumns: colIndex = getIndex(self.allCols,sc) if colIndex != -1: self.allCols.remove(sc) for col in self.allCols: if ' ' in col: col = u'"{}"'.format(col) tabItem = QListWidgetItem(col, self.lstSrcCols_2) tabItem.setCheckState(Qt.Unchecked) tabItem.setIcon(QIcon(":/plugins/stdm/images/icons/column.png")) self.lstSrcCols_2.addItem(tabItem) if len(spColumns) > 0: self.cboSpatialCols_2.setEnabled(True)
def referencing_column_value(self, field_values): """ Searches a corresponding record from the linked table using one or more pairs of field names and their corresponding values. :param field_values: Pair of field names and corresponding values i.e. {field1:value1, field2:value2, field3:value3...} :type field_values: dict :return: Value of the referenced column in the linked table. :rtype: object """ link_table_columns = self._table_columns(self._referenced_table) query_attrs = {} for source_col, val in field_values.iteritems(): ref_table_col = self._input_referenced_columns.get(source_col, None) if not ref_table_col is None: col_idx = getIndex(link_table_columns, ref_table_col) #If column is found, add it to the query fields collection if col_idx != -1: query_attrs[ref_table_col] = val #Create link table object link_table = self._table(self._referenced_table) #Use AND operator link_table_rec = self._db_session.query(link_table).filter_by(**query_attrs).first() if link_table_rec is None: return IgnoreType() else: return getattr(link_table_rec, self._output_referenced_column, IgnoreType())
def insertDocFromModel(self, sourcedoc, containerid): """ Renders the source document info from a subclass of 'SupportingDocumentMixin'. """ #Check if the document has already been inserted in the manager. docIndex = getIndex(self._docRefs, sourcedoc.document_identifier) if docIndex != -1: return if len(self.containers) > 0: if containerid in self.containers: container = self.containers[containerid] network_location = source_document_location('') if not network_location: self._doc_repository_error() return networkManager = NetworkFileManager(network_document_path()) #Add document widget docWidg = DocumentWidget( self.document_model, networkManager, mode=DOWNLOAD_MODE, canRemove=self._canEdit, view_manager=self._doc_view_manager ) self._linkWidgetRemovedSignal(docWidg) docWidg.setModel(sourcedoc) container.addWidget(docWidg) self._docRefs.append(sourcedoc.document_identifier)
def __init__(self, parent, source_cols, dest_table, dest_col, src_col): QDialog.__init__(self, parent) self.setupUi(self) TranslatorDialogBase.__init__(self, source_cols, dest_table, dest_col, src_col) self._notif_bar = NotificationBar(self.vl_notification) #Container of column names for an enumeration table self._enum_col_names = [] self._load_separators() #Init user selection to the corresponding UI controls self.txt_source_col.setText(self._src_col) #Remove selected column name from the 'other column' list sel_col_idx = getIndex(self._source_cols, self._src_col) if sel_col_idx != -1: self._source_cols.remove(self._src_col) #Load source columns self.cbo_src_other_col.addItem("") self.cbo_src_other_col.addItems(self._source_cols) #Load database tables self.cbo_enum_table.addItem("") self.cbo_enum_table.addItems(self.db_tables()) #Connect signals self.cbo_enum_table.currentIndexChanged.connect(self._on_enum_table_changed) self.cbo_primary_col.currentIndexChanged.connect(self._on_primary_col_changed)
def unique_column_values(tableName, columnName, quoteDataTypes=["character varying"]): """ Select unique row values in the specified column. Specify the data types of row values which need to be quoted. Default is varchar. """ dataType = columnType(tableName, columnName) quoteRequired = getIndex(quoteDataTypes, dataType) sql = "SELECT DISTINCT {0} FROM {1}".format(columnName, tableName) t = text(sql) result = _execute(t) uniqueVals = [] for r in result: if r[columnName] == None: if quoteRequired == -1: uniqueVals.append("NULL") else: uniqueVals.append("''") else: if quoteRequired == -1: uniqueVals.append(str(r[columnName])) else: uniqueVals.append("'{0}'".format(str(r[columnName]))) return uniqueVals
def pg_tables(schema="public", exclude_lookups=False): """ Returns a list of all the tables in the given schema minus the default PostGIS tables. Views are also excluded. See separate function for retrieving views. :rtype: list """ t = text("SELECT table_name FROM information_schema.tables WHERE table_schema = :tschema and table_type = :tbtype " \ "ORDER BY table_name ASC") result = _execute(t, tschema=schema, tbtype="BASE TABLE") pgTables = [] for r in result: tableName = r["table_name"] #Remove default PostGIS tables tableIndex = getIndex(_postGISTables, tableName) if tableIndex == -1: if exclude_lookups: #Validate if table is a lookup table and if it is, then omit rx = QRegExp("check_*") rx.setPatternSyntax(QRegExp.Wildcard) if not rx.exactMatch(tableName): pgTables.append(tableName) else: pgTables.append(tableName) return pgTables
def loadRoles(self,contentname = ""): ''' Loads the roles in the database cluster ''' self.roleProvider = RoleProvider() sysRoles = self.roleProvider.GetAllRoles() roles = [] #Load the corresponding roles for the specified content item cnt=Content() if contentname != "": self.currentContent = self.content.queryObject().filter(Content.name == contentname).first() if self.currentContent: roles = [rl.name for rl in self.currentContent.roles] #Initialize model self.roleMappingsModel = QStandardItemModel(self) self.roleMappingsModel.setColumnCount(1) #Add role items into the standard item model for r in range(len(sysRoles)): role = sysRoles[r] if role.name != "postgres": roleItem = self._createNewRoleItem(role.name) #Check if the db role is in the approved for the current content item roleIndex = getIndex(roles,role.name) if roleIndex != -1: roleItem.setCheckState(Qt.Checked) self.roleMappingsModel.appendRow(roleItem) self.lstRoles.setModel(self.roleMappingsModel)
def unique_column_values(tableName, columnName, quoteDataTypes=["character varying"]): """ Select unique row values in the specified column. Specify the data types of row values which need to be quoted. Default is varchar. """ # tableName = unicode(tableName) # columnName = unicode(columnName) dataType = columnType(tableName, columnName) quoteRequired = getIndex(quoteDataTypes, dataType) if "'" in columnName and '"' not in columnName: sql = u'SELECT DISTINCT "{0}" FROM {1}'.format(unicode(columnName), tableName) else: sql = u"SELECT DISTINCT {0} FROM {1}".format(unicode(columnName), tableName) t = text(sql) result = _execute(t) uniqueVals = [] for r in result: if r[unicode(columnName)] == None: if quoteRequired == -1: uniqueVals.append(u"NULL") else: uniqueVals.append(u"''") else: if quoteRequired == -1: uniqueVals.append(unicode(r[columnName])) else: uniqueVals.append(u"'{0}'".format(r[columnName])) return uniqueVals
def run_checks(self): """ Assert translator configuration prior to commencing the translation process. This includes checking whether the defined tables and respective columns exist. :return: Whether the translator settings are correct. :rtype: bool """ res = False #Check destination table if self._table(self._referencing_table) is None: msg = QApplication.translate("SourceValueTranslator", "Target table '%s' does not exist." % (self._referencing_table)) raise TranslatorException(msg) #Check destination column dest_columns = self._table_columns(self._referencing_table) referencing_col_idx = getIndex(dest_columns, self._referencing_column) if referencing_col_idx == -1: msg = QApplication.translate("SourceValueTranslator", "Target column '%s' does not exist." % (self._referencing_column)) raise TranslatorException(msg) #Check link table if self._table(self._referenced_table) is None: msg = QApplication.translate("SourceValueTranslator", "Linked table '%s' does not exist." % (self._referenced_table)) raise TranslatorException(msg) return res
def run_checks(self): """ Assert translator configuration prior to commencing the translation process. This includes checking whether the defined tables and respective columns exist. :return: Whether the translator settings are correct. :rtype: bool """ res = False # Check destination table if self._table(self._referencing_table) is None: msg = QApplication.translate( "SourceValueTranslator", "Target table '%s' does not exist." % (self._referencing_table)) raise TranslatorException(msg) # Check destination column dest_columns = self._table_columns(self._referencing_table) referencing_col_idx = getIndex(dest_columns, self._referencing_column) if referencing_col_idx == -1: msg = QApplication.translate( "SourceValueTranslator", "Target column '%s' does not exist." % (self._referencing_column)) raise TranslatorException(msg) # Check link table if self._table(self._referenced_table) is None: msg = QApplication.translate( "SourceValueTranslator", "Linked table '%s' does not exist." % (self._referenced_table)) raise TranslatorException(msg) return res
def pg_table_exists(table_name, include_views=True, schema="public"): """ Checks whether the given table name exists in the current database connection. :param table_name: Name of the table or view. If include_views is False the result will always be False since views have been excluded from the search. :type table_name: str :param include_views: True if view names will be also be included in the search. :type include_views: bool :param schema: Schema to search against. Default is "public" schema. :type schema: str :return: True if the table or view (if include_views is True) exists in currently connected database. :rtype: bool """ tables = pg_tables(schema=schema) if include_views: tables.extend(pg_views(schema=schema)) if getIndex(tables, table_name) == -1: return False else: return True
def loadColumns(self, table): #Load textual and spatial (if available) columns #Get spatial columns first spColumns = table_column_names(table, True, creation_order=True) self.cboSpatialCols_2.clear() self.cboSpatialCols_2.addItems(spColumns) #Textual Columns self.lstSrcCols_2.clear() self.allCols = table_column_names(table, creation_order=True) for sc in spColumns: colIndex = getIndex(self.allCols, sc) if colIndex != -1: self.allCols.remove(sc) for col in self.allCols: if ' ' in col: col = u'"{}"'.format(col) tabItem = QListWidgetItem(col, self.lstSrcCols_2) tabItem.setCheckState(Qt.Unchecked) tabItem.setIcon(QIcon(":/plugins/stdm/images/icons/column.png")) self.lstSrcCols_2.addItem(tabItem) if len(spColumns) > 0: self.cboSpatialCols_2.setEnabled(True)
def CheckAccess(self, contentCode): """ Assert whether the given user has permissions to access a content item with the gien code. """ hasPermission = False # Get roles with permission try: cnt = Content() qo = cnt.queryObject() """ cntRef = qo.filter(Content.code == contentCode).first() """ cntRef = qo.filter(Content.code == contentCode).first() if cntRef is not None: cntRoles = cntRef.roles for rl in cntRoles: if getIndex(self.userRoles, rl.name) != -1: hasPermission = True break except DummyException: """ Current user does not have permission to access the content tables. Catches all errors """ # pass raise return hasPermission
def loadUserMappings(self,rolename = ""): ''' Loads checked/unchecked users in the user mappings list based on whether they are non/members of the specified group. If rolename is empty, then just load all users with the check state set to 'Unchecked' ''' roleUsers = [] if rolename != "": roleUsers = self.roleProvider.GetUsersInRole(rolename) sysUsers = self.usersModel._users #Initialize model self.UserMappingsModel = QStandardItemModel(len(sysUsers),1,self) #Create standard user items (checkable and with an icon) then add them to the list view for u in range(len(sysUsers)): user = sysUsers[u] userItem = self._createNewUserMapping(user) #If the user is in the given role then set checkstate to 'checked' sysIndex = getIndex(roleUsers,user) if sysIndex != -1: userItem.setCheckState(Qt.Checked) self.UserMappingsModel.setItem(u, userItem) self.lstMappingUsers.setModel(self.UserMappingsModel)
def loadUserMappings(self, rolename=""): """ Loads checked/unchecked users in the user mappings list based on whether they are non/members of the specified group. If rolename is empty, then just load all users with the check state set to 'Unchecked' """ roleUsers = [] if rolename != "": roleUsers = self.roleProvider.GetUsersInRole(rolename) sysUsers = self.usersModel._users # Initialize model self.UserMappingsModel = QStandardItemModel(len(sysUsers), 1, self) # Create standard user items (checkable and with an icon) then add them to the list view for u in range(len(sysUsers)): user = sysUsers[u] userItem = self._createNewUserMapping(user) # If the user is in the given role then set checkstate to 'checked' sysIndex = getIndex(roleUsers, user) if sysIndex != -1: userItem.setCheckState(Qt.Checked) self.UserMappingsModel.setItem(u, userItem) self.lstMappingUsers.setModel(self.UserMappingsModel)
def loadRoles(self, contentname=""): ''' Loads the roles in the database cluster ''' self.roleProvider = RoleProvider() sysRoles = self.roleProvider.GetAllRoles() roles = [] #Load the corresponding roles for the specified content item cnt = Content() if contentname != "": self.currentContent = self.content.queryObject().filter( Content.name == contentname).first() if self.currentContent: roles = [rl.name for rl in self.currentContent.roles] #Initialize model self.roleMappingsModel = QStandardItemModel(self) self.roleMappingsModel.setColumnCount(1) #Add role items into the standard item model for r in range(len(sysRoles)): role = sysRoles[r] if role.name != "postgres": roleItem = self._createNewRoleItem(role.name) #Check if the db role is in the approved for the current content item roleIndex = getIndex(roles, role.name) if roleIndex != -1: roleItem.setCheckState(Qt.Checked) self.roleMappingsModel.appendRow(roleItem) self.lstRoles.setModel(self.roleMappingsModel)
def IsUserInRole(self, userName, roleName): ''' Does the specified username belong to the given role ''' #Get the roles that the user belongs to uRoles = self.GetRolesForUser(userName) roleIndex = getIndex(uRoles, roleName) exist = False if roleIndex == -1 else True return exist
def IsUserInRole(self,userName,roleName): ''' Does the specified username belong to the given role ''' #Get the roles that the user belongs to uRoles = self.GetRolesForUser(userName) roleIndex = getIndex(uRoles,roleName) exist = False if roleIndex == -1 else True return exist
def _addDocumentReference(self,docid): """ Add a document reference to the list that the document manager contains """ docIndex = getIndex(self._docRefs,docid) if docIndex == -1: self._docRefs.append(docid)
def addUniqueColumnName(self, colName, replace=True): ''' Set the name of the column whose values are to be unique. If 'replace' is True then the existing row will be replaced with one with the new value; else, the new row will not be added to the list. ''' headers = list(self._dbmodel.displayMapping().values()) colIndex = getIndex(headers, colName) if colIndex != -1: self.addUniqueColumnIndex(colIndex, replace)
def addUniqueColumnName(self,colName,replace = True): ''' Set the name of the column whose values are to be unique. If 'replace' is True then the existing row will be replaced with one with the new value; else, the new row will not be added to the list. ''' headers = self._dbmodel.displayMapping().values() colIndex = getIndex(headers,colName) if colIndex != -1: self.addUniqueColumnIndex(colIndex, replace)
def RoleExists(self, roleName): ''' Assert whether the given role exists ''' #Get role objects rolesObj = self.GetAllRoles() roles = [] for roleObj in rolesObj: roles.append(roleObj.name) roleIndex = getIndex(roles, roleName) return False if roleIndex == -1 else True
def RoleExists(self,roleName): ''' Assert whether the given role exists ''' #Get role objects rolesObj = self.GetAllRoles() roles = [] for roleObj in rolesObj: roles.append(roleObj.name) roleIndex = getIndex(roles,roleName) return False if roleIndex == -1 else True
def syncSysRoles(self): ''' Ensure system roles are upto-date with STDM roles (latter as the reference). Reverse of 'syncSTDMRoles'. ''' sysRoles = self.GetSysRoles() stdmRoles = [role.name for role in self.GetAllRoles()] #Add missing STDMRoles to sysRoles for stdmRole in stdmRoles: roleIndex = getIndex(sysRoles, stdmRole) if roleIndex == -1: self.CreateRole(stdmRole) #Remove obsolete system roles for sysRole in sysRoles: roleIndex = getIndex(stdmRoles, sysRole) if roleIndex == -1: self.DeleteRole(sysRole)
def syncSysRoles(self): ''' Ensure system roles are upto-date with STDM roles (latter as the reference). Reverse of 'syncSTDMRoles'. ''' sysRoles = self.GetSysRoles() stdmRoles = [role.name for role in self.GetAllRoles()] #Add missing STDMRoles to sysRoles for stdmRole in stdmRoles: roleIndex = getIndex(sysRoles,stdmRole) if roleIndex == -1: self.CreateRole(stdmRole) #Remove obsolete system roles for sysRole in sysRoles: roleIndex = getIndex(stdmRoles,sysRole) if roleIndex == -1: self.DeleteRole(sysRole)
def syncSTDMRoles(self): ''' Synchronizes STDM roles with the database cluster roles. By default, this method is executed when an instance of this class is created. ''' sysRoles = self.GetSysRoles() stdmRoles = [role.name for role in self.GetAllRoles()] #Add missing sysroles to STDM roles for sysRole in sysRoles: roleIndex = getIndex(stdmRoles, sysRole) if roleIndex == -1: self.AddSTDMRole(sysRole) #Remove obsolete roles from the STDM roles table for stdmRole in stdmRoles: roleIndex = getIndex(sysRoles, stdmRole) if roleIndex == -1: self.DeleteSTDMRole(stdmRole)
def syncSTDMRoles(self): ''' Synchronizes STDM roles with the database cluster roles. By default, this method is executed when an instance of this class is created. ''' sysRoles = self.GetSysRoles() stdmRoles = [role.name for role in self.GetAllRoles()] #Add missing sysroles to STDM roles for sysRole in sysRoles: roleIndex = getIndex(stdmRoles,sysRole) if roleIndex == -1: self.AddSTDMRole(sysRole) #Remove obsolete roles from the STDM roles table for stdmRole in stdmRoles: roleIndex = getIndex(sysRoles,stdmRole) if roleIndex == -1: self.DeleteSTDMRole(stdmRole)
def _is_spatial_data_source(self, ds): """ Searches the data source name against the list of spatial tables. :param ds: Data source name :type ds: str :return: True if 'ds' is a spatial table, otherwise False. :rtype: bool """ sp_idx = getIndex(self._spatial_data_sources, ds) if sp_idx == -1: return False return True
def __init__(self, config, treeview=None, parentwidget=None): self._config = config self.curr_profile = current_profile() headers = self._config.displayColumns.values() idx = getIndex(headers, "Id") if idx != -1: id_ref = headers.pop(idx) self._headers = headers self._data = [] self.rootNode = BaseSTRNode(self._headers, view=treeview, parentWidget=parentwidget)
def delete_table_data(tableName, cascade=True): """ Delete all the rows in the target table. """ tables = pg_tables() tableIndex = getIndex(tables, tableName) if tableIndex != -1: sql = "DELETE FROM {0}".format(tableName) if cascade: sql += " CASCADE" t = text(sql) _execute(t)
def _insertWidgettoContainer(self, widget): """ This method inserts the parent widget to the container for those actions that have parents defined. But it ensures that only one instance of the parent widget is inserted. """ objName = widget.objectName() # Determine if the widget is already in the container if getIndex(self._widgets, objName) == -1: if isinstance(self._container, QToolBar): self._container.insertWidget(self._actionReference, widget) elif isinstance(self._container, QMenu): self._container.insertMenu(self._actionReference, widget) self._widgets.append(objName)
def matchingFontName(self, fontName): # Try to match the exact font based on the general name matchingFont = None try: fontList = self.reg.matchName(fontName) if len(fontList) > 0: fontIndex = getIndex(fontList, fontName) if fontIndex != -1: matchingFont = fontName else: matchingFont = fontList[0] except KeyError: pass return matchingFont
def __init__(self, config, treeview=None, parentwidget=None): self._config = config self.curr_profile = current_profile() headers = list(self._config.displayColumns.values()) idx = getIndex(headers, "Id") if idx != -1: id_ref = headers.pop(idx) self._headers = headers self._data = [] self.rootNode = BaseSTRNode(self._headers, view=treeview, parentWidget=parentwidget)
def numeric_varchar_columns(table, exclude_fk_columns=True): #Combines numeric and text column types mostly used for display columns num_char_types = _pg_numeric_col_types + _text_col_types num_char_cols = columns_by_type(table, num_char_types) if exclude_fk_columns: fk_refs = foreign_key_parent_tables(table) for fk in fk_refs: local_col = fk[0] col_idx = getIndex(num_char_cols, local_col) if col_idx != -1: num_char_cols.remove(local_col) return num_char_cols else: return num_char_cols
def _onRecordSelectedEntityBrowser(self, rec, row_number=-1): ''' Slot raised when the user has clicked the select button in the 'EntityBrowser' dialog to add the selected record to the table's list. Add the record to the foreign key table using the mappings. ''' # Check if the record exists using the primary key so as to ensure # only one instance is added to the table if isinstance(rec, int): recIndex = getIndex(self._recordIds(), rec) if recIndex != -1: return dbHandler = self._dbmodel() modelObj = dbHandler.queryObject().filter( self._dbmodel.id == rec).first() elif isinstance(rec, object): modelObj = rec else: return if modelObj is not None: # Raise before entity added signal self.beforeEntityAdded.emit(modelObj) # Validate for unique value configurations ''' if not self._validate_unique_columns(modelObj, row_number): return ''' if not self._supportsLists and self._tableModel.rowCount() > 0: self._removeRow(0) insert_position = self._insertModelToView(modelObj, row_number) if isinstance(rec, object): self._deferred_objects[insert_position] = modelObj
def spatial_tables(exclude_views=False): """ Returns a list of spatial table names in the STDM database. """ t = text("select DISTINCT f_table_name from geometry_columns") result = _execute(t) spTables = [] views = pg_views() for r in result: spTable = r["f_table_name"] if exclude_views: tableIndex = getIndex(views, spTable) if tableIndex == -1: spTables.append(spTable) else: spTables.append(spTable) return spTables
def pg_views(schema="public"): """ Returns the views in the given schema minus the default PostGIS views. """ t = text("SELECT table_name FROM information_schema.tables WHERE table_schema = :tschema and table_type = :tbtype " \ "ORDER BY table_name ASC") result = _execute(t, tschema=schema, tbtype="VIEW") pgViews = [] for r in result: viewName = r["table_name"] #Remove default PostGIS tables viewIndex = getIndex(_postGISViews, viewName) if viewIndex == -1: pgViews.append(viewName) return pgViews
def _onRecordSelectedEntityBrowser(self, rec, row_number=-1): ''' Slot raised when the user has clicked the select button in the 'EntityBrowser' dialog to add the selected record to the table's list. Add the record to the foreign key table using the mappings. ''' #Check if the record exists using the primary key so as to ensure #only one instance is added to the table if isinstance(rec, int): recIndex = getIndex(self._recordIds(), rec) if recIndex != -1: return dbHandler = self._dbmodel() modelObj = dbHandler.queryObject().filter(self._dbmodel.id == rec).first() elif isinstance(rec, object): modelObj = rec else: return if not modelObj is None: #Raise before entity added signal self.beforeEntityAdded.emit(modelObj) #Validate for unique value configurations ''' if not self._validate_unique_columns(modelObj, row_number): return ''' if not self._supportsLists and self._tableModel.rowCount() > 0: self._removeRow(0) insert_position = self._insertModelToView(modelObj, row_number) if isinstance(rec, object): self._deferred_objects[insert_position] = modelObj
def isControlTypeSupported(ctl): ''' Returns whether or not the control type of the given control is supported by this class. If the control type is supported then the corresponding value handler is returned. This is based on whether there exists a registered value handler class for the specified control. ''' #Define default list of supported control names supportedControls = ControlValueHandler.handlers.keys() ctlName = str(ctl.metaObject().className()) handler = None typeIndex = getIndex(supportedControls, ctlName) if typeIndex == -1: return False, handler else: handler = ControlValueHandler.handlers[ctlName] return True, handler
def isControlTypeSupported(ctl): ''' Returns whether or not the control type of the given control is supported by this class. If the control type is supported then the corresponding value handler is returned. This is based on whether there exists a registered value handler class for the specified control. ''' #Define default list of supported control names supportedControls = ControlValueHandler.handlers.keys() ctlName = str(ctl.metaObject().className()) handler = None typeIndex = getIndex(supportedControls, ctlName) if typeIndex == -1: return False,handler else: handler = ControlValueHandler.handlers[ctlName] return True,handler
def referencing_column_value(self, field_values): """ Searches a corresponding record from the linked table using one or more pairs of field names and their corresponding values. :param field_values: Pair of field names and corresponding values i.e. {field1:value1, field2:value2, field3:value3...} :type field_values: dict :return: Value of the referenced column in the linked table. :rtype: object """ link_table_columns = self._table_columns(self._referenced_table) query_attrs = {} for source_col, val in field_values.iteritems(): ref_table_col = self._input_referenced_columns.get(source_col, None) if not ref_table_col is None: col_idx = getIndex(link_table_columns, ref_table_col) #If column is found, add it to the query fields collection if col_idx != -1: # TODO use the column object to cast based on column data type query_attrs[ref_table_col] = cast(val, String) #Create link table object link_table = self._table(self._referenced_table) #Use AND operator link_table_rec = self._db_session.query(link_table).filter_by(**query_attrs).first() if link_table_rec is None: return IgnoreType() else: return getattr(link_table_rec, self._output_referenced_column, IgnoreType())
def _on_enum_table_changed(self, index): """ Slot raised when an enumeration table is selected. :param index: Index of currently selected item. :type index: int """ enum_table = self.cbo_enum_table.currentText() self.cbo_primary_col.clear() self.cbo_other_col.clear() self._enum_col_names = [] if enum_table: self._enum_col_names = table_column_names(enum_table) #Remove id column name id_col = "id" id_idx = getIndex(self._enum_col_names, id_col) if id_idx != -1: self._enum_col_names.remove(id_col) self.cbo_primary_col.addItem("") self.cbo_primary_col.addItems(self._enum_col_names)