def run(self): ''' Fetch property IDs from the database ''' pty=Table('spatial_unit',Base.metadata,autoload=True,autoload_with=STDMDb.instance().engine) session=STDMDb.instance().session properties =session.query(pty.c.spatial_unit_id).all() #pty = Property() #properties = pty.queryObject([Property.spatial_unit_id]).all() self.emit(SIGNAL("retrieved(PyQt_PyObject)"), properties)
def close_event(self): try: self.reset_session_mapping() self.submit() self.accept() except Exception as ex: self._notifBar.insertWarningNotification(unicode(ex.message)) finally: STDMDb.instance().session.rollback()
def onCreateSTR(self): ''' Slot raised when the user clicks on Finish button in order to create a new STR entry. ''' isValid = True #Create a progress dialog progDialog = QProgressDialog(self) progDialog.setWindowTitle(QApplication.translate("newSTRWiz", "Creating New STR")) progDialog.setRange(0,7) progDialog.show() socialTenureRel=self.mapping.tableMapping('social_tenure_relationship') try: progDialog.setValue(1) socialTenure = socialTenureRel() socialTenure.party = self.selPerson.id progDialog.setValue(2) socialTenure.spatial_unit = self.selProperty.id progDialog.setValue(3) socialTenure.social_tenure_type=str(self.cboSTRType.currentText()) progDialog.setValue(6) socialTenure.save() progDialog.setValue(7) #strPerson = "%s %s"%(str(self.selPerson.family_name),str(self.selPerson.other_names)) strMsg = str(QApplication.translate("newSTRWiz", "The social tenure relationship for has been successfully created!")) QMessageBox.information(self, QApplication.translate("newSTRWiz", "STR Creation"),strMsg) except sqlalchemy.exc.OperationalError as oe: errMsg = oe.message QMessageBox.critical(self, QApplication.translate("newSTRWiz", "Unexpected Error"),errMsg) progDialog.hide() isValid = False except Exception as e: errMsg = str(e) QMessageBox.critical(self, QApplication.translate("newSTRWiz", "Unexpected Error"),errMsg) isValid = False finally: STDMDb.instance().session.rollback() progDialog.hide() return isValid
def __init__(self, parent=None, iface=None): QTabWidget.__init__(self, parent) self.setupUi(self) self._notif_bar = None self._ol_loaded = False self._overlay_layer = None self._db_session = STDMDb.instance().session self.set_iface(iface) #Web config self._web_spatial_loader = WebSpatialLoader(self.spatial_web_view, self) #Connect signals self._web_spatial_loader.loadError.connect(self.on_spatial_browser_error) self._web_spatial_loader.loadProgress.connect(self.on_spatial_browser_loading) self._web_spatial_loader.loadFinished.connect(self.on_spatial_browser_finished) self._web_spatial_loader.zoomChanged.connect(self.on_map_zoom_level_changed) self.rbGMaps.toggled.connect(self.on_load_GMaps) self.rbOSM.toggled.connect(self.on_load_OSM) self.zoomSlider.sliderReleased.connect(self.on_zoom_changed) self.btnResetMap.clicked.connect(self.on_reset_web_map) self.btnSync.clicked.connect(self.on_sync_extents) QgsMapLayerRegistry.instance().layersWillBeRemoved.connect(self._on_overlay_to_be_removed)
def __init__(self,parent,layer,feature,mode = SAVE,session=None, row=None, row_id=None): BoundDialog.__init__(self, parent) QgsFeatureMapperMixin.__init__(self, layer, feature, mode) self.session=STDMDb.instance().session self.columns=tableCols('spatial_unit') mapping=DeclareMapping.instance() SpatialModel=mapping.tableMapping('spatial_unit') self.setWindowTitle("Spatial unit editor") self.setDataReader(self.session,SpatialModel,'id') vbox=QVBoxLayout() self.setLayout(vbox) grid=LayoutLayout(vbox,QFormLayout()) self.mm=self.mapClass(SpatialModel) self.mm.addBoundForm(vbox,self.columns) buttons = LayoutWidget(vbox,QDialogButtonBox()) self.close_button = ButtonBoxButton(buttons,QDialogButtonBox.Ok) self.close_button1 = ButtonBoxButton(buttons,QDialogButtonBox.Cancel) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) self.geo=WindowGeometry(self, position=False, tabs=None)
def raw_table(self,table): """ Method to return a table reflection from postgres to sqlalchemy object: not a mapper :param table: :return: """ return Table(table, Base.metadata, autoload=True, autoload_with=STDMDb.instance().engine)
def setTableMapping(self,list): for table in list: className=table.capitalize() classObject=self.classFromTable(className) pgtable=Table(table,Base.metadata,autoload=True,autoload_with=STDMDb.instance().engine) self.mappedTableProperties(pgtable) mapper(classObject,pgtable) self.mapping[table]=classObject
def _execute(sql,**kwargs): """ Execute the passed in sql statement """ conn = STDMDb.instance().engine.connect() result = conn.execute(sql,**kwargs) conn.close() return result
def _mapTable(self,dataSourceName): """ Reflect the data source. """ meta = MetaData(bind = STDMDb.instance().engine) dsTable = Table(dataSourceName,meta,autoload=True) return dsTable
def _table(self, name): """ Get an SQLAlchemy table object based on the name. :param name: Table Name :type name: str """ meta = MetaData(bind=STDMDb.instance().engine) return Table(name, meta, autoload=True)
def __init__(self, dbname, template=None): """ use the provided dbname to create a database using existing connection :param dbname: :return: """ self.dbName = dbname self.template = template self._engine = STDMDb.instance().engine
def _execute(sql, **kwargs): ''' Execute the passed in sql statement ''' conn = STDMDb.instance().engine.connect() result = conn.execute(sql, **kwargs) conn.close() return result
def __init__(self, iface, parent=None): QObject.__init__(self, parent) self._iface = iface self._mapRenderer = self._iface.mapCanvas().mapRenderer() self._dbSession = STDMDb.instance().session self._attrValueFormatters = {} #For cleanup after document compositions have been created self._memoryLayers = []
def __init__(self,iface,parent = None): QObject.__init__(self,parent) self._iface = iface self._mapRenderer = self._iface.mapCanvas().mapRenderer() self._dbSession = STDMDb.instance().session self._attrValueFormatters = {} #For cleanup after document compositions have been created self._memoryLayers = []
def setTableMapping(self, tablist): """ Method to convert a list of table to mapped table object :return Mapper calass """ for table in tablist: try: self.mapper_for_table(table) except: pass Base.metadata.reflect(STDMDb.instance().engine)
def _updatePropertySummary(self,propid): ''' Update the summary information for the selected property ''' propty=Table('spatial_unit',Base.metadata,autoload=True,autoload_with=STDMDb.instance().engine) session=STDMDb.instance().session prop =session.query(propty).filter(propty.c.spatial_unit_id == str(propid)).first() if prop: propMapping = self._mapPropertyAttributes(prop) #Load information in the tree view propertyTreeLoader = TreeSummaryLoader(self.tvPropInfo) propertyTreeLoader.addCollection(propMapping, QApplication.translate("newSTRWiz","Property Information"), ":/plugins/stdm/images/icons/property.png") propertyTreeLoader.display() self.selProperty = prop #Show property in OpenLayers if self.gpOpenLayers.isChecked(): if self.olLoaded: self.overlayProperty()
def _execQuery(self,dataSourceName,queryField,queryValue): """ Reflects the data source then execute the query using the specified query parameters. Returns a tuple containing the reflected table and results of the query. """ meta = MetaData(bind = STDMDb.instance().engine) dsTable = Table(dataSourceName,meta,autoload = True) sql = "{0} = :qvalue".format(queryField) results = self._dbSession.query(dsTable).filter(sql).params(qvalue = queryValue).all() return (dsTable,results)
def mapper_for_table(self, table): """ Create a slqalchamey table mapping from the table name :param table: string :return: table: slqalchemy table model """ try: class_object = self.pythonize_tablename(table) mapper_table = Table(table, Base.metadata, autoload=True, autoload_with=STDMDb.instance().engine) mapper(class_object, mapper_table) self._mapping[table] = class_object self.table_property(mapper_table) except: return None
def _execQuery(self, dataSourceName, queryField, queryValue): """ Reflects the data source then execute the query using the specified query parameters. Returns a tuple containing the reflected table and results of the query. """ meta = MetaData(bind=STDMDb.instance().engine) dsTable = Table(dataSourceName, meta, autoload=True) sql = "{0} = :qvalue".format(queryField) results = self._dbSession.query(dsTable).filter(sql).params( qvalue=queryValue).all() return (dsTable, results)
def __init__(self, webview, parent=None, style=OLStyle()): QObject.__init__(self, parent) self._base_html = "spatial_unit_overlay.html" self.webview = webview self.dbSession = STDMDb.instance().session self.olPage = ProxyWebPage(self) #Property Style self._style = style #Connect slots self.olPage.loadFinished.connect(self.onFinishLoading) self.olPage.loadProgress.connect(self.onLoadingProgress) self.olPage.loadStarted.connect(self.onStartLoading)
def __init__(self, iface, parent = None): QObject.__init__(self,parent) self._iface = iface self._map_renderer = self._iface.mapCanvas().mapRenderer() self._dbSession = STDMDb.instance().session self._attr_value_formatters = {} #For cleanup after document compositions have been created self._map_memory_layers = [] self._table_mem_layers = [] self._link_field = "" self._base_photo_table = "supporting_document"
def initSTRType(self): ''' Initialize 'Social Tenure Relationship' GUI controls ''' pty=Table('check_social_tenure_type',Base.metadata,autoload=True,autoload_with=STDMDb.instance().engine) session=STDMDb.instance().session strTypeFormatter =session.query(pty.c.value).all() strType=[str(ids[0]) for ids in strTypeFormatter] self.cboSTRType.insertItems(0,strType) strType.insert(0, " ") self.cboSTRType.setCurrentIndex(-1) #loadComboSelections(self.cboSTRType, CheckSocialTenureRelationship) self.notifSTR = NotificationBar(self.vlSTRTypeNotif) #Register STR selection field self.frmWizSTRType.registerField("STR_Type",self.cboSTRType)
def __init__(self,webview,parent = None,style = OLStyle()): ''' Initialize ''' QObject.__init__(self,parent) self.baseHTML = "property_overlay.html" self.webview = webview self.dbSession = STDMDb.instance().session self.olPage = OLWebPage(self) #Property Style self._style = style #Connect slots QObject.connect(self.olPage, SIGNAL("loadFinished(bool)"),self.onFinishLoading) QObject.connect(self.olPage, SIGNAL("loadProgress(int)"),self.onLoadingProgress) QObject.connect(self.olPage, SIGNAL("loadStarted()"),self.onStartLoading)
def qgsgeometry_from_wkbelement(wkb_element): """ Convert a geoalchemy object in str or WKBElement format to the a QgsGeometry object. :return: QGIS Geometry object. """ if isinstance(wkb_element, WKBElement): db_session = STDMDb.instance().session geom_wkt = db_session.scalar(wkb_element.ST_AsText()) elif isinstance(wkb_element, str): split_geom = wkb_element.split(";") if len(split_geom) < 2: return None geom_wkt = split_geom[1] return QgsGeometry.fromWkt(geom_wkt)
def _exec_query(self, dataSourceName, queryField, queryValue): """ Reflects the data source then execute the query using the specified query parameters. Returns a tuple containing the reflected table and results of the query. """ meta = MetaData(bind=STDMDb.instance().engine) dsTable = Table(dataSourceName, meta, autoload=True) if not queryField and not queryValue: #Return all the rows; this is currently limited to 100 rows results = self._dbSession.query(dsTable).limit(100).all() else: if isinstance(queryValue, str) or isinstance(queryValue, unicode): queryValue = u"'{0}'".format(queryValue) sql = "{0} = :qvalue".format(queryField) results = self._dbSession.query(dsTable).filter(sql).params(qvalue=queryValue).all() return dsTable, results
def __init__(self, webview, parent=None, style=OLStyle()): ''' Initialize ''' QObject.__init__(self, parent) self.baseHTML = "property_overlay.html" self.webview = webview self.dbSession = STDMDb.instance().session self.olPage = OLWebPage(self) #Property Style self._style = style #Connect slots QObject.connect(self.olPage, SIGNAL("loadFinished(bool)"), self.onFinishLoading) QObject.connect(self.olPage, SIGNAL("loadProgress(int)"), self.onLoadingProgress) QObject.connect(self.olPage, SIGNAL("loadStarted()"), self.onStartLoading)
def __init__(self, parent=None): self._parent = None self._db_session = STDMDb.instance().session self.clear()
def onCreateSTR(self): ''' Slot raised when the user clicks on Finish button in order to create a new STR entry. ''' isValid = True #Create a progress dialog progDialog = QProgressDialog(self) progDialog.setWindowTitle(QApplication.translate("newSTRWiz", "Creating New STR")) progDialog.setRange(0,7) progDialog.show() socialTenureRel=self.mapping.tableMapping('social_tenure_relationship') str_relation_table =self.mapping.tableMapping('str_relations') STR_relation = str_relation_table() try: progDialog.setValue(1) socialTenure = socialTenureRel() socialTenure.party = self.selPerson.id progDialog.setValue(2) socialTenure.spatial_unit = self.selProperty.id progDialog.setValue(3) socialTenure.social_tenure_type=str(self.cboSTRType.currentText()) progDialog.setValue(6) """ Save new STR relations and supporting documentation """ socialTenure.save() model_objs = self.sourceDocManager.model_objects() if model_objs is not None: if len(model_objs)>0: for model_obj in model_objs: model_obj.save() STR_relation.social_tenure_id = socialTenure.id STR_relation.source_doc_id = model_obj.id STR_relation.save() progDialog.setValue(7) #source_doc_model = self.sourceDocManager.sourceDocuments(dtype ="TITLE DEED") #strPerson = "%s %s"%(str(self.selPerson.family_name),str(self.selPerson.other_names)) strMsg = str(QApplication.translate("newSTRWiz", "The social tenure relationship for has been successfully created!")) QMessageBox.information(self, QApplication.translate("newSTRWiz", "STR Creation"),strMsg) except sqlalchemy.exc.OperationalError as oe: errMsg = oe.message QMessageBox.critical(self, QApplication.translate("newSTRWiz", "Unexpected Error"),errMsg) progDialog.hide() isValid = False except sqlalchemy.exc.IntegrityError as ie: errMsg = ie.message QMessageBox.critical(self, QApplication.translate("newSTRWiz", "Dublicate Relationship Error"),errMsg) progDialog.hide() isValid = False except Exception as e: errMsg = str(e) QMessageBox.critical(self, QApplication.translate("newSTRWiz", "Unexpected Error"),errMsg) isValid = False finally: STDMDb.instance().session.rollback() progDialog.hide() return isValid
def __init__(self): #Create internal reference to database engine self._engine = STDMDb.instance().engine
def __init__(self): self._engine = STDMDb.instance().engine #Define membership settings. In future, there will be a better way of defining these settings self._minUserLength = 6 self._minPassLength = 6
def clearMapping(self): STDMDb.instance().session.rollback()
def __init__(self, source_file): self._ds = ogr.Open(source_file) self._targetGeomColSRID = -1 self._geomType = "" self._dbSession = STDMDb.instance().session self._mapped_class = None
def flush_session_activity(): STDMDb.instance().session._autoflush()