def delete(self, gid, sid, did, fid): """ This function will delete the selected foreign data wrapper node. Args: gid: Server Group ID sid: Server ID did: Database ID fid: foreign data wrapper ID """ if self.cmd == 'delete': # This is a cascade operation cascade = True else: cascade = False try: # Get name of foreign data wrapper from fid sql = render_template("/".join([self.template_path, 'delete.sql']), fid=fid, conn=self.conn ) status, name = self.conn.execute_scalar(sql) if not status: return internal_server_error(errormsg=name) if name is None: return make_json_response( status=410, success=0, errormsg=gettext( 'Error: Object not found.' ), info=gettext( 'The specified foreign data' ' wrapper could not be found.\n' ) ) # drop foreign data wrapper node sql = render_template("/".join([self.template_path, 'delete.sql']), name=name, cascade=cascade, conn=self.conn) status, res = self.conn.execute_scalar(sql) if not status: return internal_server_error(errormsg=res) return make_json_response( success=1, info=gettext("Foreign Data Wrapper dropped"), data={ 'id': fid, 'did': did, 'sid': sid, 'gid': gid, } ) except Exception as e: return internal_server_error(errormsg=str(e))
def sql(self, gid, sid, did, scid, tid): """ This function will reverse generate sql for sql panel :param gid: group id :param sid: server id :param did: database id :param scid: schema id :param tid: fts tempate id """ sql = render_template( "/".join([self.template_path, 'sql.sql']), tid=tid, scid=scid, conn=self.conn ) status, res = self.conn.execute_scalar(sql) if not status: return internal_server_error( gettext( "Could not generate reversed engineered query for the " "FTS Template.\n{0}").format(res) ) if res is None: return gone( gettext( "Could not generate reversed engineered query for " "FTS Template node.") ) return ajax_response(response=res)
def download(self, path=None, name=None, req=None): """ Functionality to download file """ if not self.validate_request('download'): return { 'Error': gettext('Not allowed'), 'Code': 0 } dir = self.dir if self.dir is not None else '' if hasattr(str, 'decode'): path = path.encode('utf-8') orig_path = u"{0}{1}".format(dir, path.decode('utf-8')) else: orig_path = u"{0}{1}".format(dir, path) try: Filemanager.check_access_permission( dir, u"{}{}".format(path, path) ) except Exception as e: resp = Response(gettext(u"Error: {0}".format(e))) resp.headers['Content-Disposition'] = \ 'attachment; filename=' + name return resp name = path.split('/')[-1] content = open(orig_path, 'rb') resp = Response(content) resp.headers['Content-Disposition'] = 'attachment; filename=' + name return resp
def get(*args): """To fetch the current sorted columns""" status, error_msg, conn, trans_obj, session_obj = args if error_msg == gettext('Transaction ID not found in the session.'): return make_json_response( success=0, errormsg=error_msg, info='DATAGRID_TRANSACTION_REQUIRED', status=404 ) column_list = [] if status and conn is not None and \ trans_obj is not None and session_obj is not None: msg = gettext('Success') columns, column_list = trans_obj.get_all_columns_with_order(conn) sql = trans_obj.get_filter() else: status = False msg = error_msg columns = None sql = None return make_json_response( data={ 'status': status, 'msg': msg, 'result': { 'data_sorting': columns, 'column_list': column_list, 'sql': sql } } )
def put(self, sales_order_id): try: args = parser.parse_args() status_id = args['status_id'] session = Info.get_db().session sales_order = session.query(SalesOrder).get(sales_order_id) status = session.query(EnumValues).get(status_id) if status is not None and status.type.code == SO_STATUS_KEY: if sales_order.status.code == SO_CREATED_STATUS_KEY: if status.code == SO_SHIPPED_STATUS_KEY or status.code == SO_DELIVERED_STATUS_KEY: sales_order.status_id = status_id shipping = SalesOrderService.create_or_update_shipping(sales_order) session.add(sales_order) session.add(shipping) SalesOrderService.update_related_po_status(sales_order, PO_SHIPPED_STATUS_KEY) elif status.code == SO_INVALID_STATUS_KEY: sales_order.status_id = status_id session.add(sales_order) po = SalesOrderService.update_related_po_status(sales_order, PO_REJECTED_STATUS_KEY) recvs = po.po_receivings for recv in recvs: session.delete(recv) session.commit() return dict(message=gettext('Status update successfully'), status='success'), 200 else: return dict(message=gettext('Status update not allowed'), status='error'), 201 else: return dict(message=gettext('Invalid sales order status parameter'), status='error'), 201 except Exception as e: return dict(message=gettext('Failed to change sales order status<br>{0}').format(e.message), status='error'), 201
def delete(self, gid, sid, did, cid): """ This function will drop the cast object :param cid: cast id :param did: database id :param sid: server id :param gid: group id :return: """ # Below will decide if it's simple drop or drop with cascade call if self.cmd == 'delete': # This is a cascade operation cascade = True else: cascade = False try: # Get name for cast from cid sql = render_template("/".join([self.template_path, 'delete.sql']), cid=cid) status, res = self.conn.execute_dict(sql) if not status: return internal_server_error(errormsg=res) if not res['rows']: return make_json_response( status=410, success=0, errormsg=gettext( 'Error: Object not found.' ), info=gettext( 'The specified cast object could not be found.\n' ) ) # drop cast result = res['rows'][0] sql = render_template("/".join([self.template_path, 'delete.sql']), castsource=result['castsource'], casttarget=result['casttarget'], cascade=cascade ) status, res = self.conn.execute_scalar(sql) if not status: return internal_server_error(errormsg=res) return make_json_response( success=1, info=gettext("Cast dropped"), data={ 'id': cid, 'sid': sid, 'gid': gid, 'did': did } ) except Exception as e: return internal_server_error(errormsg=str(e))
def sales_amount_report(r_type, r_period): limit = get_limit(r_period) sql = sqls.SALES_AMOUNT_REPORT_SQL.format('WEEK', 'WW', limit) \ if r_period == 'week' \ else sqls.SALES_AMOUNT_REPORT_SQL.format('MONTH', 'Mon', limit) results = Info.get_db().engine.execute(sql).fetchall() labels, totals = [], [] for r in results: labels.append("{0}, {1}".format(int(r[0]), gettext(r[2]))) totals.append(float(r[3])) avg = str(format_util.format_decimal(sum(totals) / float(len(totals)))) if len(totals) > 0 else 0 labels.reverse() totals.reverse() ct = gettext(r_type.capitalize()) cp = gettext(r_period.capitalize()) label_tot = gettext('Total Sales {0} Per {1}').format(ct, cp) label_avg = gettext('Average Sales {0}(Past {1} {2}(s)): {3}').format(ct, 24, cp, avg) return dict( data={ "labels": labels, "details": { "average_amount": { "label": label_avg, "data": [avg] * len(totals), "style": "average" }, "total": { "label": label_tot, "data": totals, "style": "major" } } }, status='success' )
def delete(self, gid, sid, did, scid): """ This function will delete an existing schema object Args: gid: Server Group ID sid: Server ID did: Database ID scid: Schema ID """ try: # Get name for schema from did SQL = render_template( "/".join([self.template_path, 'sql/get_name.sql']), _=gettext, scid=scid ) status, name = self.conn.execute_scalar(SQL) if not status: return internal_server_error(errormsg=name) if name is None: return make_json_response( status=410, success=0, errormsg=gettext( 'Error: Object not found.' ), info=gettext( 'The specified schema could not be found.\n' ) ) # drop schema SQL = render_template( "/".join([self.template_path, 'sql/delete.sql']), _=gettext, name=name, conn=self.conn, cascade=True if self.cmd == 'delete' else False ) status, res = self.conn.execute_scalar(SQL) if not status: return internal_server_error(errormsg=res) return make_json_response( success=1, info=gettext("Schema dropped"), data={ 'id': scid, 'sid': sid, 'gid': gid, 'did': did } ) except Exception as e: current_app.logger.exception(e) return internal_server_error(errormsg=str(e))
def save(cls, mid, cid, pid, value): """ save Update the value for the preference in the configuration database. :param mid: Module ID :param cid: Category ID :param pid: Preference ID :param value: Value for the options """ # Find the entry for this module in the configuration database. module = ModulePrefTable.query.filter_by(id=mid).first() # Can't find the reference for it in the configuration database, # create on for it. if module is None: return False, gettext("Could not find the specified module.") m = cls.modules[module.name] if m is None: return False, gettext( "Module '{0}' is no longer in use." ).format(module.name) category = None for c in m.categories: cat = m.categories[c] if cid == cat['id']: category = cat break if category is None: return False, gettext( "Module '{0}' does not have category with id '{1}'" ).format(module.name, cid) preference = None for p in category['preferences']: pref = (category['preferences'])[p] if pref.pid == pid: preference = pref break if preference is None: return False, gettext( "Could not find the specified preference." ) try: pref.set(value) except Exception as e: current_app.logger.exeception(e) return False, str(e) return True, None
def change_password(): """View function which handles a change password request.""" has_error = False form_class = _security.change_password_form if request.json: form = form_class(MultiDict(request.json)) else: form = form_class() if form.validate_on_submit(): try: change_user_password(current_user, form.new_password.data) except SOCKETErrorException as e: # Handle socket errors which are not covered by SMTPExceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP Socket error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except (SMTPConnectError, SMTPResponseException, SMTPServerDisconnected, SMTPDataError, SMTPHeloError, SMTPException, SMTPAuthenticationError, SMTPSenderRefused, SMTPRecipientsRefused) as e: # Handle smtp specific exceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except Exception as e: # Handle other exceptions. logging.exception(str(e), exc_info=True) flash( gettext( u'Error: {}\n' u'Your password has not been changed.' ).format(e), 'danger' ) has_error = True if request.json is None and not has_error: after_this_request(_commit) do_flash(*get_message('PASSWORD_CHANGE')) return redirect(get_url(_security.post_change_view) or get_url(_security.post_login_view)) if request.json and not has_error: form.user = current_user return _render_json(form) return _security.render_template( config_value('CHANGE_PASSWORD_TEMPLATE'), change_password_form=form, **_ctx('change_password'))
def reset_password(token): """View function that handles a reset password request.""" expired, invalid, user = reset_password_token_status(token) if invalid: do_flash(*get_message('INVALID_RESET_PASSWORD_TOKEN')) if expired: do_flash(*get_message('PASSWORD_RESET_EXPIRED', email=user.email, within=_security.reset_password_within)) if invalid or expired: return redirect(url_for('browser.forgot_password')) has_error = False form = _security.reset_password_form() if form.validate_on_submit(): try: update_password(user, form.password.data) except SOCKETErrorException as e: # Handle socket errors which are not covered by SMTPExceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP Socket error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except (SMTPConnectError, SMTPResponseException, SMTPServerDisconnected, SMTPDataError, SMTPHeloError, SMTPException, SMTPAuthenticationError, SMTPSenderRefused, SMTPRecipientsRefused) as e: # Handle smtp specific exceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except Exception as e: # Handle other exceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'Error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True if not has_error: after_this_request(_commit) do_flash(*get_message('PASSWORD_RESET')) login_user(user) return redirect(get_url(_security.post_reset_view) or get_url(_security.post_login_view)) return _security.render_template( config_value('RESET_PASSWORD_TEMPLATE'), reset_password_form=form, reset_password_token=token, **_ctx('reset_password'))
def delete(self, gid, sid, did, scid, coid): """ This function will delete existing the collation object Args: gid: Server Group ID sid: Server ID did: Database ID scid: Schema ID coid: Collation ID """ # Below will decide if it's simple drop or drop with cascade call if self.cmd == 'delete': # This is a cascade operation cascade = True else: cascade = False try: SQL = render_template("/".join([self.template_path, 'get_name.sql']), scid=scid, coid=coid) status, name = self.conn.execute_scalar(SQL) if not status: return internal_server_error(errormsg=name) if name is None: return make_json_response( success=0, errormsg=gettext( 'Error: Object not found.' ), info=gettext( 'The specified collation could not be found.\n' ) ) SQL = render_template("/".join([self.template_path, 'delete.sql']), name=name, cascade=cascade, conn=self.conn) status, res = self.conn.execute_scalar(SQL) if not status: return internal_server_error(errormsg=res) return make_json_response( success=1, info=gettext("Collation dropped"), data={ 'id': coid, 'scid': scid, 'did': did } ) except Exception as e: return internal_server_error(errormsg=str(e))
def delete(self, gid, sid, did, scid, doid): """ Drops the Domain object. Args: gid: Server Group Id sid: Server Id did: Database Id scid: Schema Id doid: Domain Id """ if self.cmd == 'delete': # This is a cascade operation cascade = True else: cascade = False SQL = render_template("/".join([self.template_path, 'delete.sql']), scid=scid, doid=doid) status, res = self.conn.execute_2darray(SQL) if not status: return internal_server_error(errormsg=res) if not res['rows']: return make_json_response( status=410, success=0, errormsg=gettext( 'Error: Object not found.' ), info=gettext( 'The specified domain could not be found.\n' ) ) name = res['rows'][0]['name'] basensp = res['rows'][0]['basensp'] SQL = render_template("/".join([self.template_path, 'delete.sql']), name=name, basensp=basensp, cascade=cascade) status, res = self.conn.execute_scalar(SQL) if not status: return internal_server_error(errormsg=res) return make_json_response( success=1, info=gettext("Domain dropped"), data={ 'id': doid, 'scid': scid, 'sid': sid, 'gid': gid, 'did': did } )
def test_as_default(self): app = flask.Flask(__name__) b = babel.Babel(app, default_locale='de_DE') domain = babel.Domain(domain='test') with app.test_request_context(): assert babel.gettext('first') == 'first' domain.as_default() assert babel.gettext('first') == 'erste'
def delete(self, gid, sid, did, scid, tid): """ This function will drop the fts_template object :param gid: group id :param sid: server id :param did: database id :param scid: schema id :param tid: fts tempate id """ # Below will decide if it's simple drop or drop with cascade call if self.cmd == 'delete': # This is a cascade operation cascade = True else: cascade = False # Get name for template from tid sql = render_template("/".join([self.template_path, 'delete.sql']), tid=tid) status, res = self.conn.execute_dict(sql) if not status: return internal_server_error(errormsg=res) if not res['rows']: return make_json_response( success=0, errormsg=gettext( 'Error: Object not found.' ), info=gettext( 'The specified FTS template could not be found.\n' ) ) # Drop fts template result = res['rows'][0] sql = render_template("/".join([self.template_path, 'delete.sql']), name=result['name'], schema=result['schema'], cascade=cascade ) status, res = self.conn.execute_scalar(sql) if not status: return internal_server_error(errormsg=res) return make_json_response( success=1, info=gettext("FTS Template dropped"), data={ 'id': tid, 'sid': sid, 'gid': gid, 'did': did, 'scid': scid } )
def get_sql(self, did, scid, tid, idx, data, mode=None): """ This function will genrate sql from model data """ if idx is not None: SQL = render_template( "/".join([self.template_path, 'properties.sql']), did=did, tid=tid, idx=idx, datlastsysoid=self.datlastsysoid ) status, res = self.conn.execute_dict(SQL) if not status: return internal_server_error(errormsg=res) if len(res['rows']) == 0: return gone( gettext("""Could not find the index in the table.""") ) old_data = dict(res['rows'][0]) # If name is not present in data then # we will fetch it from old data, we also need schema & table name if 'name' not in data: data['name'] = old_data['name'] SQL = render_template( "/".join([self.template_path, 'update.sql']), data=data, o_data=old_data, conn=self.conn ) else: required_args = { 'name': 'Name', 'columns': 'Columns' } for arg in required_args: err = False if arg == 'columns' and len(data['columns']) < 1: err = True if arg not in data: err = True # Check if we have at least one column if err: return gettext('-- definition incomplete') # If the request for new object which do not have did SQL = render_template( "/".join([self.template_path, 'create.sql']), data=data, conn=self.conn, mode=mode ) SQL += "\n" SQL += render_template( "/".join([self.template_path, 'alter.sql']), data=data, conn=self.conn ) return SQL, data['name'] if 'name' in data else old_data['name']
def delete(self, gid, sid, did, scid, doid, coid): """ Drops the Domain Constraint object. Args: gid: Server Group Id sid: Server Id did: Database Id scid: Schema Id doid: Domain Id coid: Domain Constraint Id """ try: SQL = render_template("/".join([self.template_path, 'properties.sql']), doid=doid, coid=coid) status, res = self.conn.execute_dict(SQL) if not status: return internal_server_error(errormsg=res) if not res['rows']: return make_json_response( success=0, errormsg=gettext( 'Error: Object not found.' ), info=gettext( 'The specified domain constraint could not be found.\n' ) ) data = res['rows'][0] SQL = render_template("/".join([self.template_path, 'delete.sql']), data=data) status, res = self.conn.execute_scalar(SQL) if not status: return internal_server_error(errormsg=res) return make_json_response( success=1, info=gettext("Domain Constraint dropped"), data={ 'id': doid, 'scid': scid, 'sid': sid, 'gid': gid, 'did': did } ) except Exception as e: return internal_server_error(errormsg=str(e))
def action_print(self, ids): try: for pk in ids: doc = Document.objects.get(id=pk) printdoc(doc) flash(gettext("Impression demandée pour les document sélectionnés.")) except Exception as ex: msg = gettext( "Erreur lors de la demande d'impression des documents (%s)" ) flash(msg.format(str(ex)), 'error')
def print_doc(self, id): return_url = get_redirect_target() or url_for('.index_view') try: doc = Document.objects.get(id=id) printdoc(doc) job = doc.print_jobs[-1] msg = gettext("Impression OK ( id du job : %s )") flash(msg.format(job.cups_job_id)) except Exception as ex: flash(gettext("Erreur lors de l'impression du document (%s)").format(str(ex)), 'error') return redirect(return_url)
def check_transaction_status(trans_id): """ This function is used to check the transaction id is available in the session object and connection status. Args: trans_id: Returns: status and connection object """ if 'gridData' not in session: return False, gettext( 'Transaction ID not found in the session.' ), None, None, None grid_data = session['gridData'] # Return from the function if transaction id not found if str(trans_id) not in grid_data: return False, gettext( 'Transaction ID not found in the session.' ), None, None, None # Fetch the object for the specified transaction id. # Use pickle.loads function to get the command object session_obj = grid_data[str(trans_id)] trans_obj = pickle.loads(session_obj['command_obj']) try: manager = get_driver( PG_DEFAULT_DRIVER).connection_manager(trans_obj.sid) conn = manager.connection( did=trans_obj.did, conn_id=trans_obj.conn_id, auto_reconnect=False, use_binary_placeholder=True, array_to_string=True ) except (ConnectionLost, SSHTunnelConnectionLost) as e: raise except Exception as e: current_app.logger.error(e) return False, internal_server_error(errormsg=str(e)), None, None, None connect = True if 'connect' in request.args and \ request.args['connect'] == '1' else False if connect: conn.connect() return True, None, conn, trans_obj, session_obj
def reset_doc(self, id): return_url = get_redirect_target() or url_for('.index_view') doc_id = integrate.delay(doc_id=id).get() doc = Document.objects(id=doc_id).get() if doc.log: msg = gettext(doc.log).lower() prefix = gettext("Problème avec le document : ") flash("%s %s" % (prefix, msg), 'error') else: flash(gettext('Document repassé : %s').format(doc)) return redirect(return_url)
def add(self, req=None): """ File upload functionality """ if not self.validate_request('upload'): return { 'Error': gettext('Not allowed'), 'Code': 0 } dir = self.dir if self.dir is not None else '' err_msg = '' code = 1 try: path = req.form.get('currentpath') file_obj = req.files['newfile'] file_name = file_obj.filename if hasattr(str, 'decode'): path = req.form.get('currentpath').encode( 'utf-8').decode('utf-8') file_name = file_obj.filename.encode('utf-8').decode('utf-8') orig_path = u"{0}{1}".format(dir, path) newName = u"{0}{1}".format(orig_path, file_name) with open(newName, 'wb') as f: while True: # 4MB chunk (4 * 1024 * 1024 Bytes) data = file_obj.read(4194304) if not data: break f.write(data) except Exception as e: code = 0 err_msg = u"Error: {0}".format( e.strerror if hasattr(e, 'strerror') else u'Unknown') try: Filemanager.check_access_permission(dir, path) except Exception as e: res = { 'Error': gettext(u"Error: {0}".format(e)), 'Code': 0 } return res result = { 'Path': path, 'Name': newName, 'Error': err_msg, 'Code': code } return result
def on_model_delete(self, model): super(BasePurchaseOrderAdmin, self).on_model_delete(model) DeleteValidator.validate_status_for_change( model, const.PO_RECEIVED_STATUS_KEY, gettext( 'Purchase order can not be update nor delete on received status' )) DeleteValidator.validate_status_for_change( model, const.PO_ISSUED_STATUS_KEY, gettext( 'Purchase order can not be update nor delete on issued status') )
def forgot_password(): """View function that handles a forgotten password request.""" has_error = False form_class = _security.forgot_password_form if request.json: form = form_class(MultiDict(request.json)) else: form = form_class() if form.validate_on_submit(): try: send_reset_password_instructions(form.user) except SOCKETErrorException as e: # Handle socket errors which are not covered by SMTPExceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP Socket error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except (SMTPConnectError, SMTPResponseException, SMTPServerDisconnected, SMTPDataError, SMTPHeloError, SMTPException, SMTPAuthenticationError, SMTPSenderRefused, SMTPRecipientsRefused) as e: # Handle smtp specific exceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'SMTP error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True except Exception as e: # Handle other exceptions. logging.exception(str(e), exc_info=True) flash(gettext(u'Error: {}\n' u'Your password has not been changed.' ).format(e), 'danger') has_error = True if request.json is None and not has_error: do_flash(*get_message('PASSWORD_RESET_REQUEST', email=form.user.email)) if request.json and not has_error: return _render_json(form, include_user=False) return _security.render_template( config_value('FORGOT_PASSWORD_TEMPLATE'), forgot_password_form=form, **_ctx('forgot_password'))
def addfolder(self, path, name): """ Functionality to create new folder """ if not self.validate_request('create'): return { 'Error': gettext('Not allowed'), 'Code': 0 } dir = self.dir if self.dir is not None else '' try: Filemanager.check_access_permission(dir, u"{}{}".format( path, name)) except Exception as e: res = { 'Error': gettext(u"Error: {0}".format(e)), 'Code': 0 } return res if dir != "": newPath = u"{}/{}{}/".format(dir, path, name) else: newPath = u"{}{}/".format(path, name) err_msg = '' code = 1 newName = name if not path_exists(newPath): try: os.mkdir(newPath) except Exception as e: code = 0 err_msg = u"Error: {0}".format(e.strerror) else: newPath, newName = self.getNewName(dir, path, name) try: os.mkdir(newPath) except Exception as e: code = 0 err_msg = u"Error: {0}".format(e.strerror) result = { 'Parent': path, 'Name': newName, 'Error': err_msg, 'Code': code } return result
def test_locale_selector(app): """Test locale selector.""" app.config["I18N_LANGUAGES"] = [("da", "Danish")] InvenioI18N(app) with app.test_request_context(headers=[("Accept-Language", "da")]): assert str(get_locale()) == "da" assert format_number(10.1) == "10,1" assert gettext("Translate") == u"Oversætte" with app.test_request_context(headers=[("Accept-Language", "en")]): assert str(get_locale()) == "en" assert format_number(10.1) == "10.1" assert gettext("Translate") == "Translate"
def test_locale_selector(app): """Test locale selector.""" app.config['I18N_LANGUAGES'] = ['da'] InvenioI18N(app) with app.test_request_context(headers=[('Accept-Language', 'da')]): assert str(get_locale()) == 'da' assert format_number(10.1) == '10,1' assert gettext('Translate') == u'Oversætte' with app.test_request_context(headers=[('Accept-Language', 'en')]): assert str(get_locale()) == 'en' assert format_number(10.1) == '10.1' assert gettext('Translate') == 'Translate'
def enable_disable_triggers(self, gid, sid, did, scid, tid): """ This function will enable/disable trigger(s) on the table object Args: gid: Server Group ID sid: Server ID did: Database ID scid: Schema ID tid: Table ID """ # Below will decide if it's simple drop or drop with cascade call data = request.form if request.form else json.loads( request.data, encoding='utf-8' ) # Convert str 'true' to boolean type is_enable = json.loads(data['enable']) try: SQL = render_template( "/".join([self.table_template_path, 'properties.sql']), did=did, scid=scid, tid=tid, datlastsysoid=self.datlastsysoid ) status, res = self.conn.execute_dict(SQL) if not status: return internal_server_error(errormsg=res) data = res['rows'][0] SQL = render_template( "/".join([ self.table_template_path, 'enable_disable_trigger.sql' ]), data=data, is_enable_trigger=is_enable ) status, res = self.conn.execute_scalar(SQL) if not status: return internal_server_error(errormsg=res) return make_json_response( success=1, info=gettext("Trigger(s) have been enabled") if is_enable else gettext("Trigger(s) have been disabled"), data={ 'id': tid, 'scid': scid } ) except Exception as e: return internal_server_error(errormsg=str(e))
def delete(self, gid, sid, did, scid, syid): """ This function will delete existing the synonym object Args: gid: Server Group ID sid: Server ID did: Database ID scid: Schema ID syid: Synonym ID """ # Below will decide if it's simple drop or drop with cascade call try: SQL = render_template("/".join([self.template_path, 'properties.sql']), scid=scid, syid=syid) status, res = self.conn.execute_dict(SQL) if not status: return internal_server_error(errormsg=res) if len(res['rows']) > 0: data = res['rows'][0] else: return gone( gettext('The specified synonym could not be found.') ) SQL = render_template("/".join([self.template_path, 'delete.sql']), data=data, conn=self.conn) status, res = self.conn.execute_scalar(SQL) if not status: return internal_server_error(errormsg=res) return make_json_response( success=1, info=gettext("Synonym dropped"), data={ 'id': syid, 'scid': scid, 'did': did } ) except Exception as e: return internal_server_error(errormsg=str(e))
def delete(self, gid, sid, tsid): """ This function will drop the tablespace object """ try: # Get name for tablespace from tsid status, rset = self.conn.execute_dict( render_template( "/".join([self.template_path, 'nodes.sql']), tsid=tsid, conn=self.conn ) ) if not status: return internal_server_error(errormsg=rset) if not rset['rows']: return make_json_response( success=0, errormsg=gettext( 'Error: Object not found.' ), info=gettext( 'The specified tablespace could not be found.\n' ) ) # drop tablespace SQL = render_template( "/".join([self.template_path, 'delete.sql']), tsname=(rset['rows'][0])['name'], conn=self.conn ) status, res = self.conn.execute_scalar(SQL) if not status: return internal_server_error(errormsg=res) return make_json_response( success=1, info=gettext("Tablespace dropped"), data={ 'id': tsid, 'sid': sid, 'gid': gid, } ) except Exception as e: current_app.logger.exception(e) return internal_server_error(errormsg=str(e))
def payments_account_id_validator(form, field): if field.data and not re.match('^[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}$', field.data): raise ValidationError(gettext('ID must be in the format of 1234-1234-1234-1234'))
def compare(trans_id, source_sid, source_did, target_sid, target_did): """ This function will compare the two schemas. """ # Check the transaction and connection status status, error_msg, diff_model_obj, session_obj = \ check_transaction_status(trans_id) if error_msg == gettext('Transaction ID not found in the session.'): return make_json_response(success=0, errormsg=error_msg, status=404) # Server version compatibility check status, msg = check_version_compatibility(source_sid, target_sid) if not status: return make_json_response(success=0, errormsg=msg, status=428) comparison_result = [] diff_model_obj.set_comparison_info(gettext("Comparing objects..."), 0) update_session_diff_transaction(trans_id, session_obj, diff_model_obj) try: pref = Preferences.module('schema_diff') ignore_whitespaces = pref.preference('ignore_whitespaces').get() # Fetch all the schemas of source and target database # Compare them and get the status. schema_result = fetch_compare_schemas(source_sid, source_did, target_sid, target_did) total_schema = len(schema_result['source_only']) + len( schema_result['target_only']) + len( schema_result['in_both_database']) node_percent = round( 100 / (total_schema * len(SchemaDiffRegistry.get_registered_nodes()))) total_percent = 0 # Compare Database objects comparison_schema_result, total_percent = \ compare_database_objects( trans_id=trans_id, session_obj=session_obj, source_sid=source_sid, source_did=source_did, target_sid=target_sid, target_did=target_did, diff_model_obj=diff_model_obj, total_percent=total_percent, node_percent=node_percent, ignore_whitespaces=ignore_whitespaces) comparison_result = \ comparison_result + comparison_schema_result # Compare Schema objects if 'source_only' in schema_result and \ len(schema_result['source_only']) > 0: for item in schema_result['source_only']: comparison_schema_result, total_percent = \ compare_schema_objects( trans_id=trans_id, session_obj=session_obj, source_sid=source_sid, source_did=source_did, source_scid=item['scid'], target_sid=target_sid, target_did=target_did, target_scid=None, schema_name=item['schema_name'], diff_model_obj=diff_model_obj, total_percent=total_percent, node_percent=node_percent, ignore_whitespaces=ignore_whitespaces) comparison_result = \ comparison_result + comparison_schema_result if 'target_only' in schema_result and \ len(schema_result['target_only']) > 0: for item in schema_result['target_only']: comparison_schema_result, total_percent = \ compare_schema_objects( trans_id=trans_id, session_obj=session_obj, source_sid=source_sid, source_did=source_did, source_scid=None, target_sid=target_sid, target_did=target_did, target_scid=item['scid'], schema_name=item['schema_name'], diff_model_obj=diff_model_obj, total_percent=total_percent, node_percent=node_percent, ignore_whitespaces=ignore_whitespaces) comparison_result = \ comparison_result + comparison_schema_result # Compare the two schema present in both the databases if 'in_both_database' in schema_result and \ len(schema_result['in_both_database']) > 0: for item in schema_result['in_both_database']: comparison_schema_result, total_percent = \ compare_schema_objects( trans_id=trans_id, session_obj=session_obj, source_sid=source_sid, source_did=source_did, source_scid=item['src_scid'], target_sid=target_sid, target_did=target_did, target_scid=item['tar_scid'], schema_name=item['schema_name'], diff_model_obj=diff_model_obj, total_percent=total_percent, node_percent=node_percent, ignore_whitespaces=ignore_whitespaces) comparison_result = \ comparison_result + comparison_schema_result msg = gettext("Successfully compare the specified databases.") total_percent = 100 diff_model_obj.set_comparison_info(msg, total_percent) # Update the message and total percentage done in session object update_session_diff_transaction(trans_id, session_obj, diff_model_obj) except Exception as e: app.logger.exception(e) return make_json_response(data=comparison_result)
def label(p): return gettext(p['label'])