class MiscModule(PgAdminModule): def get_own_javascripts(self): return [ { 'name': 'pgadmin.misc.explain', 'path': url_for('misc.index') + 'explain/explain', 'preloaded': False }, { 'name': 'snap.svg', 'path': url_for( 'misc.static', filename='explain/vendor/snap.svg/' + ( 'snap.svg' if config.DEBUG else 'snap.svg-min' )), 'preloaded': False } ] def get_own_stylesheets(self): stylesheets = [] stylesheets.append( url_for('misc.static', filename='explain/css/explain.css') ) return stylesheets def register_preferences(self): """ Register preferences for this module. """ self.misc_preference = Preferences( 'miscellaneous', gettext('Miscellaneous') ) lang_options = [] for lang in config.LANGUAGES: lang_options.append( { 'label': config.LANGUAGES[lang], 'value': lang } ) # Register options for the User language settings self.misc_preference.register( 'miscellaneous', 'user_language', gettext("User language"), 'options', 'en', category_label=gettext('User language'), options=lang_options ) def get_exposed_url_endpoints(self): """ Returns: list: a list of url endpoints exposed to the client. """ return ['misc.ping', 'misc.index']
def register_preferences(cls): paths = Preferences('paths', _('Paths')) for key in cls.registry: st = cls.registry[key] default_path = config.DEFAULT_BINARY_PATHS.get(st.stype, "") st.utility_path = paths.register( 'bin_paths', st.stype + '_bin_dir', st.UTILITY_PATH_LABEL, 'text', default_path, category_label=_('Binary paths'), help_str=st.UTILITY_PATH_HELP )
def statistics(self, gid, sid, jid): """ statistics Returns the statistics for a particular database if jid is specified, otherwise it will return statistics for all the databases in that server. """ pref = Preferences.module('browser') rows_threshold = pref.preference( 'pgagent_row_threshold' ) status, res = self.conn.execute_dict( render_template( "/".join([self.template_path, 'stats.sql']), jid=jid, conn=self.conn, rows_threshold=rows_threshold.get() ) ) if not status: return internal_server_error(errormsg=res) return make_json_response( data=res, status=200 )
def register_preferences(self): """ Get show_system_objects preference """ self.browser_preference = Preferences.module('browser') self.pref_show_system_objects = self.browser_preference.preference( 'show_system_objects')
def get_long_running_query_status(activities): """ This function is used to check the long running query and set the row type to highlight the row color accordingly """ dash_preference = Preferences.module('dashboards') long_running_query_threshold = \ dash_preference.preference('long_running_query_threshold').get() if long_running_query_threshold is not None: long_running_query_threshold = long_running_query_threshold.split('|') warning_value = float(long_running_query_threshold[0]) \ if long_running_query_threshold[0] != '' else math.inf alert_value = float(long_running_query_threshold[1]) \ if long_running_query_threshold[1] != '' else math.inf for row in activities: row['row_type'] = None # We care for only those queries which are in active state and # have active_since parameter and not None if row['state'] == 'active' and 'active_since' in row and \ row['active_since'] is not None: active_since = float(row['active_since']) if active_since > warning_value: row['row_type'] = 'warning' if active_since > alert_value: row['row_type'] = 'alert'
def get_locale(): """Get the language for the user.""" language = 'en' if config.SERVER_MODE is False: # Get the user language preference from the miscellaneous module if current_user.is_authenticated: user_id = current_user.id else: user = user_datastore.get_user(config.DESKTOP_USER) if user is not None: user_id = user.id user_language = Preferences.raw_value('misc', 'user_language', 'user_language', user_id) if user_language is not None: language = user_language else: # If language is available in get request then return the same # otherwise check the session or cookie data = request.form if 'language' in data: language = data['language'] or language setattr(session, 'PGADMIN_LANGUAGE', language) elif hasattr(session, 'PGADMIN_LANGUAGE'): language = getattr(session, 'PGADMIN_LANGUAGE', language) elif hasattr(request.cookies, 'PGADMIN_LANGUAGE'): language = getattr(request.cookies, 'PGADMIN_LANGUAGE', language) return language
def get_locale(): """Get the language for the user.""" language = 'en' if config.SERVER_MODE is False: # Get the user language preference from the miscellaneous module if current_user.is_authenticated: user_id = current_user.id else: user = user_datastore.get_user(config.DESKTOP_USER) if user is not None: user_id = user.id user_language = Preferences.raw_value( 'miscellaneous', 'user_language', None, user_id ) if user_language is not None: language = user_language else: # If language is available in get request then return the same # otherwise check the session or cookie data = request.form if 'language' in data: language = data['language'] or language setattr(session, 'PGADMIN_LANGUAGE', language) elif hasattr(session, 'PGADMIN_LANGUAGE'): language = getattr(session, 'PGADMIN_LANGUAGE', language) elif hasattr(request.cookies, 'PGADMIN_LANGUAGE'): language = getattr( request.cookies, 'PGADMIN_LANGUAGE', language ) return language
def register_preferences(self): """ register_preferences Register preferences for this module. """ # Register options for the PG and PPAS help paths self.help_preference = Preferences('paths', gettext('Paths')) self.pg_help_path = self.help_preference.register( 'help', 'pg_help_path', gettext("PostgreSQL Help Path"), 'text', 'https://www.postgresql.org/docs/$VERSION$/static/', category_label=gettext('Help'), help_str=gettext( 'Path to the PostgreSQL documentation. $VERSION$ will be ' 'replaced with the major.minor version number.' ) ) self.edbas_help_path = self.help_preference.register( 'help', 'edbas_help_path', gettext("EDB Advanced Server Help Path"), 'text', 'https://www.enterprisedb.com/docs/en/$VERSION$/pg/', category_label=gettext('Help'), help_str=gettext( 'Path to the EDB Advanced Server documentation. $VERSION$ ' 'will be replaced with the major.minor version number.' ) )
def index(sid=None, did=None): """ Renders the welcome, server or database dashboard Args: sid: Server ID did: Database ID Returns: Welcome/Server/database dashboard """ rates = {} prefs = Preferences.module('dashboards') session_stats_refresh_pref = prefs.preference('session_stats_refresh') rates['session_stats_refresh'] = session_stats_refresh_pref.get() tps_stats_refresh_pref = prefs.preference('tps_stats_refresh') rates['tps_stats_refresh'] = tps_stats_refresh_pref.get() ti_stats_refresh_pref = prefs.preference('ti_stats_refresh') rates['ti_stats_refresh'] = ti_stats_refresh_pref.get() to_stats_refresh_pref = prefs.preference('to_stats_refresh') rates['to_stats_refresh'] = to_stats_refresh_pref.get() bio_stats_refresh_pref = prefs.preference('bio_stats_refresh') rates['bio_stats_refresh'] = bio_stats_refresh_pref.get() # Show the appropriate dashboard based on the identifiers passed to us if sid is None and did is None: return render_template('/dashboard/welcome_dashboard.html') if did is None: return render_template('/dashboard/server_dashboard.html', sid=sid, rates=rates) else: return render_template('/dashboard/database_dashboard.html', sid=sid, did=did, rates=rates)
def set_preference(default_binary_path): conn = sqlite3.connect(config.TEST_SQLITE_PATH) cur = conn.cursor() perf = Preferences.module('paths') server_types = default_binary_path.keys() for server in server_types: path_pref = perf.preference('{0}_bin_dir'.format(server)) user_pref = cur.execute( 'SELECT pid, uid FROM user_preferences ' 'where pid=%s' % path_pref.pid ) user_pref_data = user_pref.fetchone() if user_pref_data: cur.execute( 'UPDATE user_preferences SET value = ? WHERE pid = ?', (default_binary_path[server], path_pref.pid) ) else: params = (path_pref.pid, 1, default_binary_path[server]) cur.execute( 'INSERT INTO user_preferences(pid, uid, value)' ' VALUES (?,?,?)', params ) conn.commit()
def register_preferences(cls): paths = Preferences('paths', _('Paths')) for key in cls.registry: st = cls.registry[key] st.utility_path = paths.register( 'bin_paths', st.stype + '_bin_dir', _("{0} Binary Path").format(st.desc), 'text', "", category_label=_('Binary paths'), help_str=_( "Path to the {0} binary utilities.".format( st.desc ) ) )
def set_preference(default_binary_path): conn = sqlite3.connect(config.TEST_SQLITE_PATH) cur = conn.cursor() perf = Preferences.module('paths') server_types = default_binary_path.keys() for server in server_types: path_pref = perf.preference('{0}_bin_dir'.format(server)) user_pref = cur.execute( 'SELECT pid, uid FROM user_preferences ' 'where pid=%s' % path_pref.pid ) user_pref_data = user_pref.fetchone() if user_pref_data: cur.execute( 'UPDATE user_preferences SET value = ? WHERE pid = ?', (default_binary_path[server], path_pref.pid) ) else: params = (path_pref.pid, 1, default_binary_path[server]) cur.execute( 'INSERT INTO user_preferences(pid, uid, value)' ' VALUES (?,?,?)', params ) conn.commit() conn.close()
def utils(): layout = get_setting('Browser/Layout', default='') snippets = [] prefs = Preferences.module('paths') pg_help_path_pref = prefs.preference('pg_help_path') pg_help_path = pg_help_path_pref.get() edbas_help_path_pref = prefs.preference('edbas_help_path') edbas_help_path = edbas_help_path_pref.get() # Get sqleditor options prefs = Preferences.module('sqleditor') editor_tab_size_pref = prefs.preference('tab_size') editor_tab_size = editor_tab_size_pref.get() editor_use_spaces_pref = prefs.preference('use_spaces') editor_use_spaces = editor_use_spaces_pref.get() editor_wrap_code_pref = prefs.preference('wrap_code') editor_wrap_code = editor_wrap_code_pref.get() brace_matching_pref = prefs.preference('brace_matching') brace_matching = brace_matching_pref.get() insert_pair_brackets_perf = prefs.preference('insert_pair_brackets') insert_pair_brackets = insert_pair_brackets_perf.get() for submodule in current_blueprint.submodules: snippets.extend(submodule.jssnippets) return make_response( render_template( 'browser/js/utils.js', layout=layout, jssnippets=snippets, pg_help_path=pg_help_path, edbas_help_path=edbas_help_path, editor_tab_size=editor_tab_size, editor_use_spaces=editor_use_spaces, editor_wrap_code=editor_wrap_code, editor_brace_matching=brace_matching, editor_insert_pair_brackets=insert_pair_brackets, app_name=config.APP_NAME ), 200, {'Content-Type': 'application/x-javascript'})
def save(pid): """ Save a specific preference. """ data = request.form if request.form else json.loads(request.data.decode()) if data['name'] in ['vw_edt_tab_title_placeholder', 'qt_tab_title_placeholder', 'debugger_tab_title_placeholder'] \ and data['value'].isspace(): data['value'] = '' res, msg = Preferences.save(data['mid'], data['category_id'], data['id'], data['value']) sgm.get_nodes(sgm) if not res: return internal_server_error(errormsg=msg) response = success_return() # Set cookie & session for language settings. # This will execute every time as could not find the better way to know # that which preference is getting updated. misc_preference = Preferences.module('misc') user_languages = misc_preference.preference('user_language') language = 'en' if user_languages: language = user_languages.get() or language domain = dict() if config.COOKIE_DEFAULT_DOMAIN and\ config.COOKIE_DEFAULT_DOMAIN != 'localhost': domain['domain'] = config.COOKIE_DEFAULT_DOMAIN setattr(session, 'PGADMIN_LANGUAGE', language) response.set_cookie("PGADMIN_LANGUAGE", value=language, path=config.COOKIE_DEFAULT_PATH, secure=config.SESSION_COOKIE_SECURE, httponly=config.SESSION_COOKIE_HTTPONLY, samesite=config.SESSION_COOKIE_SAMESITE, **domain) return response
def register_preferences(self): """ Get show_system_objects preference """ self.browser_preference = Preferences.module('browser') self.pref_show_system_objects = self.browser_preference.preference( 'show_system_objects' )
def register_preferences(cls): paths = Preferences('paths', _('Paths')) for key in cls.registry: st = cls.registry[key] default_path = config.DEFAULT_BINARY_PATHS[st.stype] or "" st.utility_path = paths.register( 'bin_paths', st.stype + '_bin_dir', _("{0} Binary Path").format(st.desc), 'text', default_path, category_label=_('Binary paths'), help_str=_( "Path to the directory containing the {0} utility programs (pg_dump, pg_restore etc).".format( st.desc ) ) )
def list(): processes = Process.query.filter_by(user_id=current_user.id) changed = False browser_preference = Preferences.module('browser') expiry_add = timedelta( browser_preference.preference('process_retain_days').get() or 1) res = [] for p in [*processes]: if p.start_time is not None: # remove expired jobs process_expiration_time = \ parser.parse(p.start_time) + expiry_add if datetime.now(process_expiration_time.tzinfo) >= \ process_expiration_time: shutil.rmtree(p.logdir, True) db.session.delete(p) changed = True status, updated = BatchProcess.update_process_info(p) if not status: continue elif not changed: changed = updated if p.start_time is None or (p.acknowledge is not None and p.end_time is None): continue stime = parser.parse(p.start_time) etime = parser.parse(p.end_time or get_current_time()) execution_time = BatchProcess.total_seconds(etime - stime) desc, details, type_desc, current_storage_dir = BatchProcess.\ _check_process_desc(p) res.append({ 'id': p.pid, 'desc': desc, 'type_desc': type_desc, 'details': details, 'stime': stime, 'etime': p.end_time, 'exit_code': p.exit_code, 'acknowledge': p.acknowledge, 'execution_time': execution_time, 'process_state': p.process_state, 'utility_pid': p.utility_pid, 'server_id': p.server_id, 'current_storage_dir': current_storage_dir, }) if changed: db.session.commit() return res
def panel(trans_id, is_query_tool, editor_title): """ This method calls index.html to render the data grid. Args: trans_id: unique transaction id is_query_tool: True if panel calls when query tool menu is clicked. editor_title: Title of the editor """ # Let's fetch Script type URL from request if request.args and request.args['query_url'] != '': sURL = request.args['query_url'] else: sURL = None # Fetch server type from request if request.args and request.args['server_type'] != '': server_type = request.args['server_type'] else: server_type = None # We need client OS information to render correct Keyboard shortcuts user_agent = UserAgent(request.headers.get('User-Agent')) """ Animations and transitions are not automatically GPU accelerated and by default use browser's slow rendering engine. We need to set 'translate3d' value of '-webkit-transform' property in order to use GPU. After applying this property under linux, Webkit calculates wrong position of the elements so panel contents are not visible. To make it work, we need to explicitly set '-webkit-transform' property to 'none' for .ajs-notifier, .ajs-message, .ajs-modal classes. This issue is only with linux runtime application and observed in Query tool and debugger. When we open 'Open File' dialog then whole Query-tool panel content is not visible though it contains HTML element in back end. The port number should have already been set by the runtime if we're running in desktop mode. """ is_linux_platform = False from sys import platform as _platform if "linux" in _platform: is_linux_platform = True pref = Preferences.module('sqleditor') if pref.preference('new_browser_tab').get(): new_browser_tab = 'true' else: new_browser_tab = 'false' return render_template("datagrid/index.html", _=gettext, uniqueId=trans_id, is_query_tool=is_query_tool, editor_title=editor_title, script_type_url=sURL, is_desktop_mode=app.PGADMIN_RUNTIME, is_linux=is_linux_platform, is_new_browser_tab=new_browser_tab, server_type=server_type, client_platform=user_agent.platform)
def register_preferences(self): """ Register preferences for this module. """ # Add the node informaton for browser, not in respective # node preferences self.browser_preference = Preferences.module('browser') self.pref_show_system_objects = self.browser_preference.preference( 'show_system_objects')
def register_preferences(self): """ register_preferences Register preferences for this module. """ # Register options for the PG and PPAS help paths self.help_preference = Preferences('paths', gettext('Paths')) self.pg_help_path = self.help_preference.register( 'help', 'pg_help_path', gettext("PostgreSQL Help Path"), 'text', 'https://www.postgresql.org/docs/$VERSION$/', category_label=gettext('Help'), help_str=gettext( 'Path to the PostgreSQL documentation. $VERSION$ will be ' 'replaced with the major.minor version number.'))
def register_preferences(self): """ Register preferences for this module. """ self.misc_preference = Preferences('miscellaneous', _('Miscellaneous')) lang_options = [] for lang in config.LANGUAGES: lang_options.append({'label': config.LANGUAGES[lang], 'value': lang}) # Register options for the User language settings language = self.misc_preference.register( 'miscellaneous', 'user_language', _("User language"), 'options', 'en', category_label=_('User language'), options=lang_options )
def index(sid=None, did=None): """ Renders the welcome, server or database dashboard Args: sid: Server ID did: Database ID Returns: Welcome/Server/database dashboard """ rates = {} settings = {} prefs = Preferences.module('dashboards') # Get the server version if sid is not None: g.manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid) g.conn = g.manager.connection() g.version = g.manager.version if not g.conn.connected(): g.version = 0 session_stats_refresh_pref = prefs.preference('session_stats_refresh') rates['session_stats_refresh'] = session_stats_refresh_pref.get() tps_stats_refresh_pref = prefs.preference('tps_stats_refresh') rates['tps_stats_refresh'] = tps_stats_refresh_pref.get() ti_stats_refresh_pref = prefs.preference('ti_stats_refresh') rates['ti_stats_refresh'] = ti_stats_refresh_pref.get() to_stats_refresh_pref = prefs.preference('to_stats_refresh') rates['to_stats_refresh'] = to_stats_refresh_pref.get() bio_stats_refresh_pref = prefs.preference('bio_stats_refresh') rates['bio_stats_refresh'] = bio_stats_refresh_pref.get() # Whether to display graphs and server activity preferences show_graphs_pref = prefs.preference('show_graphs') settings['show_graphs'] = show_graphs_pref.get() show_activity_pref = prefs.preference('show_activity') settings['show_activity'] = show_activity_pref.get() # Show the appropriate dashboard based on the identifiers passed to us if sid is None and did is None: return render_template('/dashboard/welcome_dashboard.html') if did is None: return render_template('/dashboard/server_dashboard.html', sid=sid, rates=rates, version=g.version, settings=settings) else: return render_template('/dashboard/database_dashboard.html', sid=sid, did=did, rates=rates, version=g.version, settings=settings)
def set_preference(default_binary_path): conn = sqlite3.connect(config.TEST_SQLITE_PATH) cur = conn.cursor() perf = Preferences.module('paths') pg_path_pref = perf.preference('pg_bin_dir') user_pref = cur.execute( 'SELECT pid, uid FROM user_preferences where pid=%s' % pg_path_pref.pid) user_pref = user_pref.fetchone() if user_pref: cur.execute('UPDATE user_preferences SET value = ? WHERE pid = ?', (default_binary_path['pg'], pg_path_pref.pid)) else: pg_pref_details = (pg_path_pref.pid, 1, default_binary_path['pg']) cur.execute( 'INSERT INTO user_preferences(pid, uid, value)' ' VALUES (?,?,?)', pg_pref_details) ppas_path_pref = perf.preference('ppas_bin_dir') user_pref = cur.execute( 'SELECT pid, uid FROM user_preferences where pid=%s' % ppas_path_pref.pid) user_pref = user_pref.fetchone() if user_pref: cur.execute('UPDATE user_preferences SET value = ? WHERE pid = ? ', (default_binary_path['ppas'], ppas_path_pref.pid)) else: ppas_pref_details = (ppas_path_pref.pid, 1, default_binary_path['ppas']) cur.execute( 'INSERT INTO user_preferences(pid, uid, value)' ' VALUES (?,?,?)', ppas_pref_details) gpdb_path_pref = perf.preference('gpdb_bin_dir') user_pref = cur.execute( 'SELECT pid, uid FROM user_preferences where pid=%s' % gpdb_path_pref.pid) user_pref = user_pref.fetchone() if user_pref: cur.execute('UPDATE user_preferences SET value = ? WHERE pid = ? ', (default_binary_path['gpdb'], gpdb_path_pref.pid)) else: gpdb_pref_details = (gpdb_path_pref.pid, 1, default_binary_path['gpdb']) cur.execute( 'INSERT INTO user_preferences(pid, uid, value)' ' VALUES (?,?,?)', gpdb_pref_details) conn.commit()
def register_preferences(self): """ Register preferences for this module. """ # Add the node informaton for browser, not in respective # node preferences self.browser_preference = Preferences.module('browser') self.pref_show_system_objects = self.browser_preference.preference( 'show_system_objects' )
def initialize_query_tool(sid, did=None): """ This method is responsible for instantiating and initializing the query tool object. It will also create a unique transaction id and store the information into session variable. Args: sid: Server Id did: Database Id """ if did is None: # Use Maintenance database OID from pgadmin.utils.driver import get_driver driver = get_driver(PG_DEFAULT_DRIVER) manager = driver.connection_manager(sid) conn = manager.connection() if conn.connected(): did = manager.did else: internal_server_error(errormsg=gettext( 'Server disconnected. Please connect and try again.')) try: command_obj = ObjectRegistry.get_object('query_tool', sid=sid, did=did) except Exception as e: return internal_server_error(errormsg=str(e)) # Create a unique id for the transaction trans_id = str(random.randint(1, 9999999)) if 'gridData' not in session: sql_grid_data = dict() else: sql_grid_data = session['gridData'] # Use pickle to store the command object which will be used # later by the sql grid module. sql_grid_data[trans_id] = { 'command_obj': pickle.dumps(command_obj, -1) # -1 specify the highest protocol version available } # Store the grid dictionary into the session variable session['gridData'] = sql_grid_data pref = Preferences.module('sqleditor') new_browser_tab = pref.preference('new_browser_tab').get() return make_json_response(data={ 'gridTransId': trans_id, 'newBrowserTab': new_browser_tab })
def __init__(self, **kwargs): """ This method is used to initialize the class. Args: **kwargs : N number of parameters """ self.sid = kwargs['sid'] if 'sid' in kwargs else None self.did = kwargs['did'] if 'did' in kwargs else None self.conn = kwargs['conn'] if 'conn' in kwargs else None self.keywords = [] manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(self.sid) # we will set template path for sql scripts self.sql_path = 'sqlautocomplete/sql/#{0}#'.format(manager.version) self.search_path = [] # Fetch the search path if self.conn.connected(): query = render_template("/".join([self.sql_path, 'schema.sql']), search_path=True) status, res = self.conn.execute_dict(query) if status: for record in res['rows']: self.search_path.append(record['schema']) pref = Preferences.module('sqleditor') keywords_in_uppercase = \ pref.preference('keywords_in_uppercase').get() # Fetch the keywords query = render_template("/".join([self.sql_path, 'keywords.sql'])) # If setting 'Keywords in uppercase' is set to True in # Preferences then fetch the keywords in upper case. if keywords_in_uppercase: query = render_template("/".join( [self.sql_path, 'keywords.sql']), upper_case=True) status, res = self.conn.execute_dict(query) if status: for record in res['rows']: self.keywords.append(record['word']) self.text_before_cursor = None self.prioritizer = PrevalenceCounter(self.keywords) self.reserved_words = set() for x in self.keywords: self.reserved_words.update(x.split()) self.name_pattern = re.compile("^[_a-z][_a-z0-9\$]*$")
def register_language(sender, user): # After logged in, set the language in the preferences if we get from # the login page data = request.form if 'language' in data: language = data['language'] # Set the user language preference misc_preference = Preferences.module('miscellaneous') user_languages = misc_preference.preference('user_language') if user_languages and language: language = user_languages.set(language)
def browser_js(): layout = get_setting('Browser/Layout', default='') snippets = [] prefs = Preferences.module('paths') pg_help_path_pref = prefs.preference('pg_help_path') pg_help_path = pg_help_path_pref.get() edbas_help_path_pref = prefs.preference('edbas_help_path') edbas_help_path = edbas_help_path_pref.get() # Get sqleditor options prefs = Preferences.module('sqleditor') editor_tab_size_pref = prefs.preference('tab_size') editor_tab_size = editor_tab_size_pref.get() editor_use_spaces_pref = prefs.preference('use_spaces') editor_use_spaces = editor_use_spaces_pref.get() editor_wrap_code_pref = prefs.preference('wrap_code') editor_wrap_code = editor_wrap_code_pref.get() for submodule in current_blueprint.submodules: snippets.extend(submodule.jssnippets) return make_response( render_template( 'browser/js/browser.js', layout=layout, jssnippets=snippets, pg_help_path=pg_help_path, edbas_help_path=edbas_help_path, editor_tab_size=editor_tab_size, editor_use_spaces=editor_use_spaces, editor_wrap_code=editor_wrap_code, _=gettext ), 200, {'Content-Type': 'application/x-javascript'})
def save(pid): """ Save a specific preference. """ data = request.form if request.form else json.loads(request.data.decode()) res, msg = Preferences.save(data['mid'], data['cid'], data['id'], data['value']) if not res: return internal_server_error(errormsg=msg) return success_return()
def get_theme_css(): all_themes = get_all_themes() theme_css = all_themes['standard']['cssfile'] + '.css' try: misc_preference = Preferences.module('misc') theme = misc_preference.preference('theme').get() if theme in all_themes: theme_css = all_themes[theme]['cssfile'] + '.css' except Exception: # Let the default theme go if exception occurs pass return theme_css
class HelpModule(PgAdminModule): def get_own_menuitems(self): """Return a (set) of dicts of help menu items, with name, priority, URL, target and onclick code.""" return { 'help_items': [ MenuItem(name='mnu_online_help', label=gettext('Online Help'), priority=100, target='pgadmin_help', icon='fa fa-question', url=url_for('help.static', filename='index.html')), MenuItem(name='mnu_pgadmin_website', label=gettext('pgAdmin Website'), priority=200, target='pgadmin_website', icon='fa fa-external-link-alt', url='https://www.pgadmin.org/'), MenuItem(name='mnu_postgresql_website', label=gettext('PostgreSQL Website'), priority=300, target='postgres_website', icon='fa fa-external-link-alt', url='https://www.postgresql.org/') ] } def register_preferences(self): """ register_preferences Register preferences for this module. """ # Register options for the PG and PPAS help paths self.help_preference = Preferences('paths', gettext('Paths')) self.pg_help_path = self.help_preference.register( 'help', 'pg_help_path', gettext("PostgreSQL Help Path"), 'text', 'https://www.postgresql.org/docs/$VERSION$/', category_label=gettext('Help'), help_str=gettext( 'Path to the PostgreSQL documentation. $VERSION$ will be ' 'replaced with the major.minor version number.')) def get_exposed_url_endpoints(self): """ Returns the list of URLs exposed to the client. """ return ['help.static']
def save(pid): """ Save a specific preference. """ data = request.form if request.form else json.loads(request.data.decode()) res, msg = Preferences.save( data['mid'], data['category_id'], data['id'], data['value']) if not res: return internal_server_error(errormsg=msg) response = success_return() # Set cookie & session for language settings. # This will execute every time as could not find the better way to know # that which preference is getting updated. misc_preference = Preferences.module('miscellaneous') user_languages = misc_preference.preference( 'user_language' ) language = 'en' if user_languages: language = user_languages.get() or language domain = dict() if config.COOKIE_DEFAULT_DOMAIN and\ config.COOKIE_DEFAULT_DOMAIN != 'localhost': domain['domain'] = config.COOKIE_DEFAULT_DOMAIN setattr(session, 'PGADMIN_LANGUAGE', language) response.set_cookie("PGADMIN_LANGUAGE", value=language, path=config.COOKIE_DEFAULT_PATH, **domain) return response
def file_manager_config(trans_id): """render the required json""" # trans_id = Filemanager.create_new_transaction() data = Filemanager.get_trasaction_selection(trans_id) pref = Preferences.module('file_manager') file_dialog_view = pref.preference('file_dialog_view').get() return Response(response=render_template( "file_manager/js/file_manager_config.json", _=gettext, data=data, file_dialog_view=file_dialog_view), status=200, mimetype="application/json")
def preferences_s(): """Fetch all preferences for caching.""" # Load Preferences pref = Preferences.preferences() res = [] for m in pref: if len(m['categories']): for c in m['categories']: for p in c['preferences']: p['module'] = m['name'] res.append(p) return ajax_response(response=res, status=200)
def register_preferences(self): """ Register preferences for this module. """ # Add the node informaton for browser, not in respective # node preferences self.browser_preference = Preferences.module('browser') self.pref_show_system_objects = self.browser_preference.preference( 'show_system_objects' ) self.pref_show_node = self.browser_preference.register( 'node', 'show_node_' + self.node_type, gettext('Package {0}').format(self.label), 'node', self.SHOW_ON_BROWSER, category_label=gettext('Nodes') )
def node_js(): prefs = Preferences.module('paths') pg_help_path_pref = prefs.preference('pg_help_path') pg_help_path = pg_help_path_pref.get() edbas_help_path_pref = prefs.preference('edbas_help_path') edbas_help_path = edbas_help_path_pref.get() return make_response( render_template('browser/js/node.js', pg_help_path=pg_help_path, edbas_help_path=edbas_help_path, _=gettext), 200, {'Content-Type': 'application/x-javascript'})
def register_language(sender, user): # After logged in, set the language in the preferences if we get from # the login page data = request.form if 'language' in data: language = data['language'] # Set the user language preference misc_preference = Preferences.module('miscellaneous') user_languages = misc_preference.preference( 'user_language' ) if user_languages and language: language = user_languages.set(language)
def node_js(): prefs = Preferences.module('paths') pg_help_path_pref = prefs.preference('pg_help_path') pg_help_path = pg_help_path_pref.get() edbas_help_path_pref = prefs.preference('edbas_help_path') edbas_help_path = edbas_help_path_pref.get() return make_response( render_template('browser/js/node.js', pg_help_path=pg_help_path, edbas_help_path=edbas_help_path, _=gettext ), 200, {'Content-Type': 'application/x-javascript'})
def __init__(self, **kwargs): """ This method calls the __init__ method of the base class to get the proper object name. Args: **kwargs : N number of parameters """ # call base class init to fetch the table name super(TableCommand, self).__init__(**kwargs) # Set the default sorting on table data by primary key if user # preference value is set self.data_sorting_by_pk = Preferences.module('sqleditor').preference( 'table_view_data_by_pk').get()
def register_preferences(self): """ register_preferences Register preferences for this module. """ # Register options for the PG and PPAS help paths self.dashboard_preference = Preferences('dashboards', gettext('Dashboards')) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'session_stats_refresh', gettext("Session statistics refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'tps_stats_refresh', gettext("Transaction throughput refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'ti_stats_refresh', gettext("Tuples in refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'to_stats_refresh', gettext("Tuples out refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'bio_stats_refresh', gettext("Block I/O statistics refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') )
def init_filemanager(): if len(req.data) != 0: configs = json.loads(req.data) trans_id = Filemanager.create_new_transaction(configs) data = Filemanager.get_trasaction_selection(trans_id) pref = Preferences.module('file_manager') file_dialog_view = pref.preference('file_dialog_view').get() if type(file_dialog_view) == list: file_dialog_view = file_dialog_view[0] last_selected_format = get_file_type_setting(data['supported_types']) # in some cases, the setting may not match with available types if last_selected_format not in data['supported_types']: last_selected_format = data['supported_types'][0] res_data = { 'transId': trans_id, "options": { "culture": "en", "lang": "py", "defaultViewMode": file_dialog_view, "autoload": True, "showFullPath": False, "dialog_type": data['dialog_type'], "show_hidden_files": pref.preference('show_hidden_files').get(), "fileRoot": data['fileroot'], "capabilities": data['capabilities'], "allowed_file_types": data['supported_types'], "platform_type": data['platform_type'], "show_volumes": data['show_volumes'], "homedir": data['homedir'], "last_selected_format": last_selected_format }, "security": { "uploadPolicy": data['security']['uploadPolicy'], "uploadRestrictions": data['security']['uploadRestrictions'], }, "upload": { "multiple": data['upload']['multiple'], "number": 20, "fileSizeLimit": data['upload']['fileSizeLimit'], "imagesOnly": False } } return make_json_response(data=res_data)
def preferences_s(): """Fetch all preferences for caching.""" # Load Preferences pref = Preferences.preferences() res = [] for m in pref: if len(m['categories']): for c in m['categories']: for p in c['preferences']: p['module'] = m['name'] res.append(p) return ajax_response( response=res, status=200 )
def file_manager_config(trans_id): """render the required json""" # trans_id = Filemanager.create_new_transaction() data = Filemanager.get_trasaction_selection(trans_id) pref = Preferences.module('file_manager') file_dialog_view = pref.preference('file_dialog_view').get() show_hidden_files = pref.preference('show_hidden_files').get() return Response(response=render_template( "file_manager/js/file_manager_config.json", _=gettext, data=data, file_dialog_view=file_dialog_view, show_hidden_files=show_hidden_files ), status=200, mimetype="application/json" )
def register_preferences(self): """ register_preferences Register preferences for this module. Keep the browser preference object to be used by overriden submodule, along with that get two browser level preferences show_system_objects, and show_node will be registered to used by the submodules. """ # Add the node informaton for browser, not in respective node preferences self.browser_preference = Preferences.module('browser') self.pref_show_system_objects = self.browser_preference.preference( 'show_system_objects' ) self.pref_show_node = self.browser_preference.register( 'node', 'show_node_' + self.node_type, self.collection_label, 'node', self.SHOW_ON_BROWSER, category_label=gettext('Nodes') )
def browser_css(): """Render and return CSS snippets from the nodes and modules.""" snippets = [] # Get configurable options prefs = Preferences.module('sqleditor') sql_font_size_pref = prefs.preference('sql_font_size') sql_font_size = round(float(sql_font_size_pref.get()), 2) if sql_font_size != 0: snippets.append( '.CodeMirror { font-size: %sem; }' % str(sql_font_size) ) for submodule in blueprint.submodules: snippets.extend(submodule.csssnippets) return make_response( render_template( 'browser/css/browser.css', snippets=snippets, _=gettext ), 200, {'Content-Type': 'text/css'})
def browser_js(): layout = get_setting('Browser/Layout', default='') snippets = [] prefs = Preferences.module('paths') pg_help_path_pref = prefs.preference('pg_help_path') pg_help_path = pg_help_path_pref.get() edbas_help_path_pref = prefs.preference('edbas_help_path') edbas_help_path = edbas_help_path_pref.get() for submodule in current_blueprint.submodules: snippets.extend(submodule.jssnippets) return make_response( render_template( 'browser/js/browser.js', layout=layout, jssnippets=snippets, pg_help_path=pg_help_path, edbas_help_path=edbas_help_path, _=gettext ), 200, {'Content-Type': 'application/x-javascript'})
def register_preferences(self): """ Register preferences for this module. """ self.misc_preference = Preferences( 'miscellaneous', gettext('Miscellaneous') ) lang_options = [] for lang in config.LANGUAGES: lang_options.append( { 'label': config.LANGUAGES[lang], 'value': lang } ) # Register options for the User language settings self.misc_preference.register( 'miscellaneous', 'user_language', gettext("User language"), 'options', 'en', category_label=gettext('User language'), options=lang_options )
class DashboardModule(PgAdminModule): def __init__(self, *args, **kwargs): super(DashboardModule, self).__init__(*args, **kwargs) def get_own_menuitems(self): return {} def get_own_javascripts(self): return [{ 'name': 'pgadmin.dashboard', 'path': url_for('dashboard.index') + 'dashboard', 'when': None }] def get_own_stylesheets(self): """ Returns: list: the stylesheets used by this module. """ stylesheets = [ url_for('dashboard.static', filename='css/dashboard.css') ] return stylesheets def get_panels(self): return [ Panel( name='dashboard', priority=1, title=gettext('Dashboard'), icon='fa fa-tachometer', content='', isCloseable=True, isPrivate=False, limit=1, isIframe=False, canHide=True ).__dict__ ] def register_preferences(self): """ register_preferences Register preferences for this module. """ # Register options for the PG and PPAS help paths self.dashboard_preference = Preferences( 'dashboards', gettext('Dashboards') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'session_stats_refresh', gettext("Session statistics refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'tps_stats_refresh', gettext("Transaction throughput refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'ti_stats_refresh', gettext("Tuples in refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'to_stats_refresh', gettext("Tuples out refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'bio_stats_refresh', gettext("Block I/O statistics refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.display_graphs = self.dashboard_preference.register( 'display', 'show_graphs', gettext("Show graphs?"), 'boolean', True, category_label=gettext('Display'), help_str=gettext('If set to True, graphs ' 'will be displayed on dashboards.') ) self.display_server_activity = self.dashboard_preference.register( 'display', 'show_activity', gettext("Show activity?"), 'boolean', True, category_label=gettext('Display'), help_str=gettext('If set to True, activity tables ' 'will be displayed on dashboards.') ) def get_exposed_url_endpoints(self): """ Returns: list: a list of url endpoints exposed to the client. """ return [ 'dashboard.index', 'dashboard.get_by_sever_id', 'dashboard.get_by_database_id', 'dashboard.session_stats', 'dashboard.get_session_stats_by_sever_id', 'dashboard.get_session_stats_by_database_id', 'dashboard.tps_stats', 'dashboard.tps_stats_by_server_id', 'dashboard.tps_stats_by_database_id', 'dashboard.ti_stats', 'dashboard.ti_stats_by_server_id', 'dashboard.ti_stats_by_database_id', 'dashboard.to_stats', 'dashboard.to_stats_by_server_id', 'dashboard.to_stats_by_database_id', 'dashboard.bio_stats', 'dashboard.bio_stats_by_server_id', 'dashboard.bio_stats_by_database_id', 'dashboard.activity', 'dashboard.get_activity_by_server_id', 'dashboard.get_activity_by_database_id', 'dashboard.locks', 'dashboard.get_locks_by_server_id', 'dashboard.get_locks_by_database_id', 'dashboard.prepared', 'dashboard.get_prepared_by_server_id', 'dashboard.get_prepared_by_database_id', 'dashboard.config', 'dashboard.get_config_by_server_id', ]
def index(): """Render and process the main browser window.""" # Register Gravatar module with the app only if required if config.SHOW_GRAVATAR_IMAGE: Gravatar( current_app, size=100, rating='g', default='retro', force_default=False, use_ssl=True, base_url=None ) # Get the current version info from the website, and flash a message if # the user is out of date, and the check is enabled. if config.UPGRADE_CHECK_ENABLED: data = None url = '%s?version=%s' % (config.UPGRADE_CHECK_URL, config.APP_VERSION) current_app.logger.debug('Checking version data at: %s' % url) try: # Do not wait for more than 5 seconds. # It stuck on rendering the browser.html, while working in the # broken network. if os.path.exists(config.CA_FILE): response = urlreq.urlopen(url, data, 5, cafile=config.CA_FILE) else: response = urlreq.urlopen(url, data, 5) current_app.logger.debug( 'Version check HTTP response code: %d' % response.getcode() ) if response.getcode() == 200: data = json.loads(response.read().decode('utf-8')) current_app.logger.debug('Response data: %s' % data) except Exception: current_app.logger.exception('Exception when checking for update') if data is not None: if data['pgadmin4']['version_int'] > config.APP_VERSION_INT: msg = render_template( MODULE_NAME + "/upgrade.html", current_version=config.APP_VERSION, upgrade_version=data['pgadmin4']['version'], product_name=config.APP_NAME, download_url=data['pgadmin4']['download_url'] ) flash(msg, 'warning') response = Response(render_template( MODULE_NAME + "/index.html", username=current_user.email, is_admin=current_user.has_role("Administrator"), _=gettext )) # Set the language cookie after login, so next time the user will have that # same option at the login time. misc_preference = Preferences.module('miscellaneous') user_languages = misc_preference.preference( 'user_language' ) language = 'en' if user_languages: language = user_languages.get() or 'en' domain = dict() if config.COOKIE_DEFAULT_DOMAIN and\ config.COOKIE_DEFAULT_DOMAIN != 'localhost': domain['domain'] = config.COOKIE_DEFAULT_DOMAIN response.set_cookie("PGADMIN_LANGUAGE", value=language, path=config.COOKIE_DEFAULT_PATH, **domain) return response
def utils(): layout = get_setting('Browser/Layout', default='') snippets = [] prefs = Preferences.module('paths') pg_help_path_pref = prefs.preference('pg_help_path') pg_help_path = pg_help_path_pref.get() edbas_help_path_pref = prefs.preference('edbas_help_path') edbas_help_path = edbas_help_path_pref.get() # Get sqleditor options prefs = Preferences.module('sqleditor') editor_tab_size_pref = prefs.preference('tab_size') editor_tab_size = editor_tab_size_pref.get() editor_use_spaces_pref = prefs.preference('use_spaces') editor_use_spaces = editor_use_spaces_pref.get() editor_wrap_code_pref = prefs.preference('wrap_code') editor_wrap_code = editor_wrap_code_pref.get() brace_matching_pref = prefs.preference('brace_matching') brace_matching = brace_matching_pref.get() insert_pair_brackets_perf = prefs.preference('insert_pair_brackets') insert_pair_brackets = insert_pair_brackets_perf.get() # This will be opposite of use_space option editor_indent_with_tabs = False if editor_use_spaces else True # Try to fetch current libpq version from the driver try: from config import PG_DEFAULT_DRIVER from pgadmin.utils.driver import get_driver driver = get_driver(PG_DEFAULT_DRIVER) pg_libpq_version = driver.libpq_version() except Exception as e: pg_libpq_version = 0 for submodule in current_blueprint.submodules: snippets.extend(submodule.jssnippets) return make_response( render_template( 'browser/js/utils.js', layout=layout, jssnippets=snippets, pg_help_path=pg_help_path, edbas_help_path=edbas_help_path, editor_tab_size=editor_tab_size, editor_use_spaces=editor_use_spaces, editor_wrap_code=editor_wrap_code, editor_brace_matching=brace_matching, editor_insert_pair_brackets=insert_pair_brackets, editor_indent_with_tabs=editor_indent_with_tabs, app_name=config.APP_NAME, pg_libpq_version=pg_libpq_version, support_ssh_tunnel=config.SUPPORT_SSH_TUNNEL ), 200, {'Content-Type': 'application/x-javascript'})
def preferences(module=None, preference=None): """Fetch all/or requested preferences of pgAdmin IV.""" if module is not None and preference is not None: try: m = Preferences.module(module, create=False) if m is None: return Response(status=404) p = m.preference(preference) if p is None: return Response(status=404) return ajax_response( response=p.to_json(), status=200 ) except Exception as e: return internal_server_error(errormsg=str(e)) # Load Preferences pref = Preferences.preferences() res = [] def label(p): return gettext(p['label']) for m in pref: if len(m['categories']): om = { "id": m['id'], "label": gettext(m['label']), "inode": True, "open": True, "branch": [] } for c in m['categories']: for p in c['preferences']: if 'label' in p and p['label'] is not None: p['label'] = gettext(p['label']) if 'help_str' in p and p['help_str'] is not None: p['help_str'] = gettext(p['help_str']) oc = { "id": c['id'], "mid": m['id'], "label": gettext(c['label']), "inode": False, "open": False, "preferences": sorted(c['preferences'], key=label) } (om['branch']).append(oc) om['branch'] = sorted(om['branch'], key=label) res.append(om) return ajax_response( response=sorted(res, key=label), status=200 )
def index(sid=None, did=None): """ Renders the welcome, server or database dashboard Args: sid: Server ID did: Database ID Returns: Welcome/Server/database dashboard """ rates = {} settings = {} prefs = Preferences.module('dashboards') # Get the server version if sid is not None: g.manager = get_driver( PG_DEFAULT_DRIVER).connection_manager(sid) g.conn = g.manager.connection() g.version = g.manager.version if not g.conn.connected(): g.version = 0 session_stats_refresh_pref = prefs.preference('session_stats_refresh') rates['session_stats_refresh'] = session_stats_refresh_pref.get() tps_stats_refresh_pref = prefs.preference('tps_stats_refresh') rates['tps_stats_refresh'] = tps_stats_refresh_pref.get() ti_stats_refresh_pref = prefs.preference('ti_stats_refresh') rates['ti_stats_refresh'] = ti_stats_refresh_pref.get() to_stats_refresh_pref = prefs.preference('to_stats_refresh') rates['to_stats_refresh'] = to_stats_refresh_pref.get() bio_stats_refresh_pref = prefs.preference('bio_stats_refresh') rates['bio_stats_refresh'] = bio_stats_refresh_pref.get() # Whether to display graphs and server activity preferences show_graphs_pref = prefs.preference('show_graphs') settings['show_graphs'] = show_graphs_pref.get() show_activity_pref = prefs.preference('show_activity') settings['show_activity'] = show_activity_pref.get() # Show the appropriate dashboard based on the identifiers passed to us if sid is None and did is None: return render_template('/dashboard/welcome_dashboard.html') if did is None: return render_template( '/dashboard/server_dashboard.html', sid=sid, rates=rates, version=g.version, settings=settings ) else: return render_template( '/dashboard/database_dashboard.html', sid=sid, did=did, rates=rates, version=g.version, settings=settings )
def properties(self, gid, sid, did, scid, tid): """ This function will show the properties of the selected table node. Args: gid: Server Group ID sid: Server ID did: Database ID scid: Schema ID scid: Schema ID tid: Table ID Returns: JSON of selected table node """ 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) if len(res['rows']) == 0: return gone(gettext("The specified table could not be found.")) # We will check the threshold set by user before executing # the query because that can cause performance issues # with large result set pref = Preferences.module('browser') table_row_count_pref = pref.preference('table_row_count_threshold') table_row_count_threshold = table_row_count_pref.get() estimated_row_count = int(res['rows'][0].get('reltuples', 0)) # If estimated rows are greater than threshold then if estimated_row_count and \ estimated_row_count > table_row_count_threshold: res['rows'][0]['rows_cnt'] = str(table_row_count_threshold) + '+' # If estimated rows is lower than threshold then calculate the count elif estimated_row_count and \ table_row_count_threshold >= estimated_row_count: SQL = render_template( "/".join( [self.table_template_path, 'get_table_row_count.sql'] ), data=res['rows'][0] ) status, count = self.conn.execute_scalar(SQL) if not status: return internal_server_error(errormsg=count) res['rows'][0]['rows_cnt'] = count # If estimated_row_count is zero then set the row count with same elif not estimated_row_count: res['rows'][0]['rows_cnt'] = estimated_row_count return super(TableView, self).properties( gid, sid, did, scid, tid, res )
def __init__(self, **kwargs): """ This method is used to initialize the class. Args: **kwargs : N number of parameters """ self.sid = kwargs['sid'] if 'sid' in kwargs else None self.conn = kwargs['conn'] if 'conn' in kwargs else None self.keywords = [] self.databases = [] self.functions = [] self.datatypes = [] self.dbmetadata = {'tables': {}, 'views': {}, 'functions': {}, 'datatypes': {}} self.text_before_cursor = None self.name_pattern = re.compile("^[_a-z][_a-z0-9\$]*$") manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(self.sid) # we will set template path for sql scripts self.sql_path = 'sqlautocomplete/sql/#{0}#'.format(manager.version) self.search_path = [] schema_names = [] if self.conn.connected(): # Fetch the search path query = render_template( "/".join([self.sql_path, 'schema.sql']), search_path=True) status, res = self.conn.execute_dict(query) if status: for record in res['rows']: self.search_path.append(record['schema']) # Fetch the schema names query = render_template("/".join([self.sql_path, 'schema.sql'])) status, res = self.conn.execute_dict(query) if status: for record in res['rows']: schema_names.append(record['schema']) pref = Preferences.module('sqleditor') keywords_in_uppercase = \ pref.preference('keywords_in_uppercase').get() # Fetch the keywords query = render_template("/".join([self.sql_path, 'keywords.sql'])) # If setting 'Keywords in uppercase' is set to True in # Preferences then fetch the keywords in upper case. if keywords_in_uppercase: query = render_template( "/".join([self.sql_path, 'keywords.sql']), upper_case=True) status, res = self.conn.execute_dict(query) if status: for record in res['rows']: # 'public' is a keyword in EPAS database server. Don't add # this into the list of keywords. # This is a hack to fix the issue in autocomplete. if record['word'].lower() == 'public': continue self.keywords.append(record['word']) self.prioritizer = PrevalenceCounter(self.keywords) self.reserved_words = set() for x in self.keywords: self.reserved_words.update(x.split()) self.all_completions = set(self.keywords) self.extend_schemata(schema_names) # Below are the configurable options in pgcli which we don't have # in pgAdmin4 at the moment. Setting the default value from the pgcli's # config file. self.signature_arg_style = '{arg_name} {arg_type}' self.call_arg_style = '{arg_name: <{max_arg_len}} := {arg_default}' self.call_arg_display_style = '{arg_name}' self.call_arg_oneliner_max = 2 self.search_path_filter = True self.generate_aliases = False self.insert_col_skip_patterns = [ re.compile(r'^now\(\)$'), re.compile(r'^nextval\(')] self.qualify_columns = 'if_more_than_one_table' self.asterisk_column_order = 'table_order'
def register_preferences(self): """ register_preferences Register preferences for this module. """ # Register options for the PG and PPAS help paths self.dashboard_preference = Preferences( 'dashboards', gettext('Dashboards') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'session_stats_refresh', gettext("Session statistics refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'tps_stats_refresh', gettext("Transaction throughput refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'ti_stats_refresh', gettext("Tuples in refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'to_stats_refresh', gettext("Tuples out refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'bio_stats_refresh', gettext("Block I/O statistics refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.display_graphs = self.dashboard_preference.register( 'display', 'show_graphs', gettext("Show graphs?"), 'boolean', True, category_label=gettext('Display'), help_str=gettext('If set to True, graphs ' 'will be displayed on dashboards.') ) self.display_server_activity = self.dashboard_preference.register( 'display', 'show_activity', gettext("Show activity?"), 'boolean', True, category_label=gettext('Display'), help_str=gettext('If set to True, activity tables ' 'will be displayed on dashboards.') )
class DashboardModule(PgAdminModule): def __init__(self, *args, **kwargs): super(DashboardModule, self).__init__(*args, **kwargs) def get_own_menuitems(self): return {} def get_own_javascripts(self): return [{ 'name': 'pgadmin.dashboard', 'path': url_for('dashboard.index') + 'dashboard', 'when': None }] def get_own_stylesheets(self): """ Returns: list: the stylesheets used by this module. """ stylesheets = [ url_for('dashboard.static', filename='css/dashboard.css') ] return stylesheets def get_panels(self): return [ Panel( name='dashboard', priority=1, title=gettext('Dashboard'), icon='fa fa-tachometer', content='', isCloseable=False, isPrivate=True, isIframe=False) ] def register_preferences(self): """ register_preferences Register preferences for this module. """ # Register options for the PG and PPAS help paths self.dashboard_preference = Preferences('dashboards', gettext('Dashboards')) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'session_stats_refresh', gettext("Session statistics refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'tps_stats_refresh', gettext("Transaction throughput refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'ti_stats_refresh', gettext("Tuples in refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'to_stats_refresh', gettext("Tuples out refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') ) self.session_stats_refresh = self.dashboard_preference.register( 'dashboards', 'bio_stats_refresh', gettext("Block I/O statistics refresh rate"), 'integer', 1, min_val=1, max_val=999999, category_label=gettext('Graphs'), help_str=gettext('The number of seconds between graph samples.') )