def _persistModel(self, save_and_new): """ Saves the model to the database and shows a success message. :param save_and_new: A Boolean indicating it is triggered by save and new button. :type save_and_new: Boolean """ try: # Persist the model to its corresponding store. if self._mode == SAVE: self._model.save() if not save_and_new: QMessageBox.information( self, QApplication.translate("MappedDialog", "Record Saved"), QApplication.translate( "MappedDialog", "New record has been successfully saved.")) else: self._model.update() QMessageBox.information( self, QApplication.translate("MappedDialog", "Record Updated"), QApplication.translate( "MappedDialog", "Record has been successfully updated.")) STDMDb.instance().session.flush() for attrMapper in self._attrMappers: control = attrMapper.valueHandler().control if isinstance(control, ExpressionLineEdit): value = control.on_expression_triggered() print attrMapper._attrName, value setattr(self.model(), attrMapper._attrName, value) self._model.update() # STDMDb.instance().session.flush() except Exception as ex: QMessageBox.critical( self, QApplication.translate("MappedDialog", "Data Operation Error"), QApplication.translate( "MappedDialog", u'The data could not be saved due to ' u'the error: \n{}'.format(ex.args[0]))) self.is_valid = False # Close the dialog if isinstance(self, QDialog) and self.is_valid: self.postSaveUpdate(self._model) if not save_and_new: self.accept()
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) try: 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 except SQLAlchemyError as ex: self._dbSession.rollback() raise ex
def __init__(self, parent=None): self._parent = None self._db_session = STDMDb.instance().session self.clear() #Primary entity self.entity = None
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.sel_highlight = None self.memory_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 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 __init__(self, parent=None): self._parent = None self._db_session = STDMDb.instance().session self.clear() # Primary entity self.entity = 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 __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.sel_highlight = None self.memory_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, 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 = {} self._current_profile = current_profile() if self._current_profile is None: raise Exception('Current data profile has not been set.') #For cleanup after document compositions have been created self._map_memory_layers = [] self.map_registry = QgsMapLayerRegistry.instance() self._table_mem_layers = [] self._feature_ids = [] self._link_field = "" self._base_photo_table = "supporting_document" #Value formatter for output files self._file_name_value_formatter = None
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, source_file): self._ds = ogr.Open(source_file) self._targetGeomColSRID = -1 self._geomType = '' self._dbSession = STDMDb.instance().session self._mapped_cls = None self._mapped_doc_cls = None self._current_profile = current_profile() self._source_doc_manager = None
def on_digitizing_saved(self): """ A slot raised when the save button is clicked on Digitizing Toolbar of QGIS. It saves feature models created by the digitizer and STDM form to the Database. :return: None :rtype: NoneType """ ent_model = entity_model(self.entity) entity_obj = ent_model() entity_obj.saveMany( list(self.feature_models.values()) ) for model in self.feature_models.values(): STDMDb.instance().session.flush() for attrMapper in self.editor._attrMappers: control = attrMapper.valueHandler().control if isinstance(control, ExpressionLineEdit): value = control.on_expression_triggered(model) print(attrMapper._attrName, value) setattr(model, attrMapper._attrName, value) model.update() # Save child models if self.editor is not None: self.editor.save_children() # undo each feature created so that qgis # don't try to save the same feature again. # It will also clear all the models from # self.feature_models as on_feature_deleted # is raised when a feature is removed. feature_ids_to_delete = list(self.feature_models.keys()) for f_id in feature_ids_to_delete: iface.mainWindow().blockSignals(True) self.layer.deleteFeature(f_id) self.on_feature_deleted(f_id) iface.mainWindow().blockSignals(True) for i in range(len(self.feature_models)): self.layer.undoStack().undo()
def on_digitizing_saved(self): """ A slot raised when the save button is clicked on Digitizing Toolbar of QGIS. It saves feature models created by the digitizer and STDM form to the Database. :return: None :rtype: NoneType """ ent_model = entity_model(self.entity) entity_obj = ent_model() entity_obj.saveMany( self.feature_models.values() ) for model in self.feature_models.values(): STDMDb.instance().session.flush() for attrMapper in self.editor._attrMappers: control = attrMapper.valueHandler().control if isinstance(control, ExpressionLineEdit): value = control.on_expression_triggered(model) print attrMapper._attrName, value setattr(model, attrMapper._attrName, value) model.update() # Save child models if self.editor is not None: self.editor.save_children() # undo each feature created so that qgis # don't try to save the same feature again. # It will also clear all the models from # self.feature_models as on_feature_deleted # is raised when a feature is removed. for f_id in self.feature_models.keys(): iface.mainWindow().blockSignals(True) self.layer.deleteFeature(f_id) self.on_feature_deleted(f_id) iface.mainWindow().blockSignals(True) for i in range(len(self.feature_models)): self.layer.undoStack().undo()
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 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 DummyException: pass Base.metadata.reflect(STDMDb.instance().engine)
def _execute(sql, **kwargs): """ Execute the passed in sql statement """ conn = STDMDb.instance().engine.connect() trans = conn.begin() result = conn.execute(sql, **kwargs) try: trans.commit() conn.close() return result except SQLAlchemyError: trans.rollback()
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 __init__(self, engine=None, parent=None): QObject.__init__(self, parent) self.config = StdmConfiguration.instance() self.engine = engine self.metadata = metadata #Use the default engine if None is specified. if self.engine is None: self.engine = STDMDb.instance().engine #Ensure there is a connectable set in the metadata if self.metadata.bind is None: self.metadata.bind = self.engine
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, 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 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 _create_layer(self, wkb_element, attributes): """ Creates a vector layer :param wkb_element: Geoalchemy WKB data type class wrap :type wkb_element: WKBElement :param attributes: Layer attributes :type attributes: List """ db_session = STDMDb.instance().session wkt = db_session.scalar(wkb_element.ST_AsText()) if not self._plot_layer: crs_id = "EPSG:{0}".format(wkb_element.srid) geom_type = self._wkt_type(wkt) uri = "{0}?crs={1}&index=yes".format(geom_type, crs_id) fields = [(field, type_) for field, type_, value in attributes] name = self._generate_layer_name() self._plot_layer = PlotLayer(uri, name, fields=fields) self._plot_layer.create_layer() self.layer.setReadOnly() value = {field: value for field, type_, value in attributes} self._plot_layer.wkt_geometry(wkt, value)
def import_data(table_name, columns_names, data, **kwargs): sql = "INSERT INTO {0} ({1}) VALUES {2}".format(table_name, columns_names, str(data)) t = text(sql) conn = STDMDb.instance().engine.connect() trans = conn.begin() try: result = conn.execute(t, **kwargs) trans.commit() conn.close() return result except IntegrityError: trans.rollback() return False except SQLAlchemyError: trans.rollback() return False
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) try: 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 except SQLAlchemyError as ex: self._dbSession.rollback() raise ex
def __init__(self, iface, parent = None): QObject.__init__(self,parent) self._iface = iface self._map_renderer = self._iface.mapCanvas().mapRenderer() self._map_settings = self._iface.mapCanvas().mapSettings() self._dbSession = STDMDb.instance().session self._attr_value_formatters = {} self._current_profile = current_profile() if self._current_profile is None: raise Exception('Current data profile has not been set.') #For cleanup after document compositions have been created self._map_memory_layers = [] self.map_registry = QgsMapLayerRegistry.instance() self._table_mem_layers = [] self._feature_ids = [] self._link_field = "" self._base_photo_table = "supporting_document" #Value formatter for output files self._file_name_value_formatter = None
def commit_str(self): """ Slot raised when the user clicks on Finish button in order to create a new STR entry. """ isValid = True # Create a progress dialog try: self.progress.show() if not self.str_edit_node: QApplication.processEvents() self.progress.setRange(0, len(self.data_store)) self.progress.overall_progress( 'Creating a STR...', ) for i, str_store in enumerate(self.data_store.values()): self.progress.progress_message( 'Saving STR {}'.format(i+1), '' ) self.progress.setValue(i + 1) self.on_add_str(str_store) self.progress.hide() strMsg = QApplication.translate( "STRDBHandler", "The social tenure relationship has " "been successfully created!" ) QMessageBox.information( iface.mainWindow(), QApplication.translate( "STRDBHandler", "Social Tenure Relationship" ), strMsg ) else: QApplication.processEvents() self.progress.setRange(0, 1) self.progress.setValue(0) self.progress.overall_progress( 'Editing a STR...', ) self.progress.progress_message('Updating STR', '') updated_str_obj = self.on_edit_str( self.data_store[1] ) self.progress.setValue(1) self.progress.hide() strMsg = QApplication.translate( "STRDBHandler", "The social tenure relationship has " "been successfully updated!" ) QMessageBox.information( iface.mainWindow(), QApplication.translate( "STRDBHandler", "Social Tenure Relationship" ), strMsg ) return updated_str_obj except exc.OperationalError as oe: errMsg = oe.message QMessageBox.critical( iface.mainWindow(), QApplication.translate( "STRDBHandler", "Unexpected Error" ), errMsg ) self.progress.hide() isValid = False STDMDb.instance().session.rollback() LOGGER.debug(str(oe)) except exc.IntegrityError as ie: errMsg = ie.message QMessageBox.critical( iface.mainWindow(), QApplication.translate( "STRDBHandler", "Duplicate Relationship Error" ), errMsg ) self.progress.hide() isValid = False STDMDb.instance().session.rollback() LOGGER.debug(str(ie)) except exc.InternalError as ie: QMessageBox.critical( iface.mainWindow(), QApplication.translate( 'STRDBHandler', 'InternalError Error' ), QApplication.translate( 'STRDBHandler', 'Sorry, there is an internal error. \n' 'Restart QGIS to fix the issue.' ) ) LOGGER.debug(str(ie)) self.progress.hide() isValid = False STDMDb.instance().session.rollback() except Exception as e: errMsg = unicode(e) QMessageBox.critical( iface.mainWindow(), QApplication.translate( 'STRDBHandler', 'Unexpected Error' ), errMsg ) LOGGER.debug(str(e)) isValid = False STDMDb.instance().session.rollback() self.progress.hide() finally: STDMDb.instance().session.rollback() self.progress.hide() return isValid
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 = 4 self._minPassLength = 6
def flush_session_activity(): STDMDb.instance().session._autoflush()
def _bind_metadata(metadata): # Ensures there is a connectable set in the metadata if metadata.bind is None: metadata.bind = 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 = 4 self._minPassLength = 6
def __init__(self): #Create internal reference to database engine self._engine = STDMDb.instance().engine self._current_profile = current_profile()
def _bind_metadata(metadata): #Ensures there is a connectable set in the metadata if metadata.bind is None: metadata.bind = STDMDb.instance().engine