Fixed code smell reported by SonarQube.

This commit is contained in:
Akshay Joshi 2022-01-20 16:58:21 +05:30
parent d945c6f843
commit 1013d7ccdd
39 changed files with 90 additions and 141 deletions

View File

@ -29,6 +29,9 @@ from pgadmin.utils.constants import LDAP
ERROR_SEARCHING_LDAP_DIRECTORY = gettext( ERROR_SEARCHING_LDAP_DIRECTORY = gettext(
"Error searching the LDAP directory: {}") "Error searching the LDAP directory: {}")
ERROR_CONNECTING_LDAP_SERVER = gettext(
"Error connecting to the LDAP server: {}\n")
class LDAPAuthentication(BaseAuthentication): class LDAPAuthentication(BaseAuthentication):
"""Ldap Authentication Class""" """Ldap Authentication Class"""
@ -122,18 +125,16 @@ class LDAPAuthentication(BaseAuthentication):
except LDAPSocketOpenError as e: except LDAPSocketOpenError as e:
current_app.logger.exception( current_app.logger.exception(
"Error connecting to the LDAP server: {}\n".format(e)) ERROR_CONNECTING_LDAP_SERVER.format(e))
return False, gettext("Error connecting to the LDAP server: {}\n" return False, ERROR_CONNECTING_LDAP_SERVER.format(e.args[0])
).format(e.args[0])
except LDAPBindError as e: except LDAPBindError as e:
current_app.logger.exception( current_app.logger.exception(
"Error binding to the LDAP server.") "Error binding to the LDAP server.")
return False, gettext("Error binding to the LDAP server.") return False, gettext("Error binding to the LDAP server.")
except Exception as e: except Exception as e:
current_app.logger.exception( current_app.logger.exception(
"Error connecting to the LDAP server: {}\n".format(e)) ERROR_CONNECTING_LDAP_SERVER.format(e))
return False, gettext("Error connecting to the LDAP server: {}\n" return False, ERROR_CONNECTING_LDAP_SERVER.format(e.args[0])
).format(e.args[0])
# Enable TLS if STARTTLS is configured # Enable TLS if STARTTLS is configured
if self.start_tls: if self.start_tls:

View File

@ -1512,10 +1512,10 @@ class ServerNode(PGChildNodeView):
# Check if any psql terminal is running for the current disconnecting # Check if any psql terminal is running for the current disconnecting
# server. If any terminate the psql tool connection. # server. If any terminate the psql tool connection.
if 'sid_soid_mapping' in current_app.config and str(sid) in \ if 'sid_soid_mapping' in current_app.config and str(sid) in \
current_app.config['sid_soid_mapping']: current_app.config['sid_soid_mapping'] and \
if str(sid) in current_app.config['sid_soid_mapping']: str(sid) in current_app.config['sid_soid_mapping']:
for i in current_app.config['sid_soid_mapping'][str(sid)]: for i in current_app.config['sid_soid_mapping'][str(sid)]:
sio.emit('disconnect-psql', namespace='/pty', to=i) sio.emit('disconnect-psql', namespace='/pty', to=i)
status = manager.release() status = manager.release()

View File

@ -38,13 +38,10 @@ export default class LanguageSchema extends BaseUISchema {
} }
// This function check whether the server is less than 13 or not. // This function check whether the server is less than 13 or not.
isLessThan13(){ isLessThan13(){
if(!_.isUndefined(this.node_info) return !_.isUndefined(this.node_info)
&& !_.isUndefined(this.node_info['node_info']) && !_.isUndefined(this.node_info['node_info'])
&& !_.isUndefined(this.node_info['node_info'].version) && !_.isUndefined(this.node_info['node_info'].version)
&& this.node_info['node_info'].version < 130000) && this.node_info['node_info'].version < 130000;
{ return true; }
else{ return false; }
} }
isDisabled(state){ isDisabled(state){
if (this.templateList.some(template => template.tmplname === state.name)){ if (this.templateList.some(template => template.tmplname === state.name)){

View File

@ -70,11 +70,7 @@ export default class SynonymSchema extends BaseUISchema {
readonly: function(state) { readonly: function(state) {
// If tagetType is synonym then disable it // If tagetType is synonym then disable it
if(!obj.inCatalog()) { if(!obj.inCatalog()) {
if(state.targettype == 's') { return state.targettype == 's';
return true;
} else {
return false;
}
} }
return true; return true;
}, },

View File

@ -196,12 +196,12 @@ export default class ColumnSchema extends BaseUISchema {
editable: function(state) { editable: function(state) {
// If primary key already exist then disable. // If primary key already exist then disable.
if ( if (
obj.top && (( obj.top && (
!_.isUndefined(obj.top.origData['oid']) !_.isUndefined(obj.top.origData['oid'])
&& !_.isUndefined(obj.top.origData['primary_key']) && !_.isUndefined(obj.top.origData['primary_key'])
&& obj.top.origData['primary_key'].length > 0 && obj.top.origData['primary_key'].length > 0
&& !_.isUndefined(obj.top.origData['primary_key'][0]['oid']) && !_.isUndefined(obj.top.origData['primary_key'][0]['oid'])
)) )
) { ) {
return false; return false;
} }

View File

@ -325,11 +325,7 @@ export default class ExclusionConstraintSchema extends BaseUISchema {
deps: ['condeferrable'], deps: ['condeferrable'],
disabled: function(state) { disabled: function(state) {
// Disable if condeferred is false or unselected. // Disable if condeferred is false or unselected.
if(state.condeferrable) { return !state.condeferrable;
return false;
} else {
return true;
}
}, },
readonly: obj.isReadonly, readonly: obj.isReadonly,
depChange: (state)=>{ depChange: (state)=>{

View File

@ -204,11 +204,7 @@ export default class ForeignKeySchema extends BaseUISchema {
deps: ['condeferrable'], deps: ['condeferrable'],
disabled: function(state) { disabled: function(state) {
// Disable if condeferred is false or unselected. // Disable if condeferred is false or unselected.
if(state.condeferrable) { return !state.condeferrable;
return false;
} else {
return true;
}
}, },
readonly: obj.isReadonly, readonly: obj.isReadonly,
depChange: (state)=>{ depChange: (state)=>{
@ -284,11 +280,7 @@ export default class ForeignKeySchema extends BaseUISchema {
mode: ['properties', 'create', 'edit'], group: gettext('Definition'), mode: ['properties', 'create', 'edit'], group: gettext('Definition'),
deps:['autoindex', 'hasindex'], deps:['autoindex', 'hasindex'],
disabled: (state)=>{ disabled: (state)=>{
if(!state.autoindex && !state.hasindex) { return !state.autoindex && !state.hasindex;
return true;
} else {
return false;
}
}, },
readonly: this.isReadonly, readonly: this.isReadonly,
},{ },{

View File

@ -27,7 +27,7 @@ export function getColumnSchema(nodeObj, treeNodeInfo, itemNodeData) {
} }
export class ColumnSchema extends BaseUISchema { export class ColumnSchema extends BaseUISchema {
constructor(fieldOptions = {}, nodeData, initValues={}) { constructor(fieldOptions = {}, nodeData = [], initValues={}) {
super({ super({
name: null, name: null,
oid: undefined, oid: undefined,
@ -121,7 +121,6 @@ export class ColumnSchema extends BaseUISchema {
_.each(this.op_class_types, function(v, k) { _.each(this.op_class_types, function(v, k) {
if(amname === k) { if(amname === k) {
options = v; options = v;
return;
} }
}); });
return options; return options;
@ -209,7 +208,7 @@ function inSchema(node_info) {
} }
export default class IndexSchema extends BaseUISchema { export default class IndexSchema extends BaseUISchema {
constructor(getColumnSchema, fieldOptions = {}, nodeData, initValues={}) { constructor(getColumnSchema, fieldOptions = {}, nodeData = [], initValues={}) {
super({ super({
name: undefined, name: undefined,
oid: undefined, oid: undefined,

View File

@ -4,7 +4,7 @@ import BaseUISchema from 'sources/SchemaView/base_schema.ui';
import { emptyValidator, isEmptyString } from '../../../../../../../../static/js/validators'; import { emptyValidator, isEmptyString } from '../../../../../../../../static/js/validators';
export class PartitionKeysSchema extends BaseUISchema { export class PartitionKeysSchema extends BaseUISchema {
constructor(columns=[], getCollations, getOperatorClass) { constructor(columns=[], getCollations=[], getOperatorClass=[]) {
super({ super({
key_type: 'column', key_type: 'column',
}); });
@ -424,7 +424,9 @@ export class PartitionsSchema extends BaseUISchema {
msg = gettext('For hash partition Modulus field cannot be empty.'); msg = gettext('For hash partition Modulus field cannot be empty.');
setError('values_modulus', msg); setError('values_modulus', msg);
return true; return true;
} if(isEmptyString(state.values_remainder)) { }
if(isEmptyString(state.values_remainder)) {
msg = gettext('For hash partition Remainder field cannot be empty.'); msg = gettext('For hash partition Remainder field cannot be empty.');
setError('values_remainder', msg); setError('values_remainder', msg);
return true; return true;

View File

@ -333,10 +333,10 @@ class BaseTableView(PGChildNodeView, BasePartitionTable, VacuumSettings):
:return: True or False based on condition :return: True or False based on condition
""" """
# check whether the table is partition or not, then check conislocal # check whether the table is partition or not, then check conislocal
if 'relispartition' in data and data['relispartition'] is True: if 'relispartition' in data and data['relispartition'] is True and \
if 'conislocal' in constraint \ 'conislocal' in constraint and \
and constraint['conislocal'] is False: constraint['conislocal'] is False:
return True return True
return False return False
def get_table_dependents(self, tid): def get_table_dependents(self, tid):

View File

@ -958,7 +958,6 @@ class CompositeSchema extends BaseUISchema {
// set the values in state // set the values in state
state.is_tlength = false; state.is_tlength = false;
} }
return;
} }
}); });
} }
@ -1306,7 +1305,6 @@ export default class TypeSchema extends BaseUISchema {
tempCol.forEach(function(enumVal) { tempCol.forEach(function(enumVal) {
if(enumVal == undefined) { if(enumVal == undefined) {
dontAddColumn = true; dontAddColumn = true;
return;
} }
}); });
} }
@ -1314,7 +1312,7 @@ export default class TypeSchema extends BaseUISchema {
} }
schemaCheck(state) { schemaCheck(state) {
if(this.fieldOptions.node_info && 'schema' in this.fieldOptions.node_info) if(this.fieldOptions.node_info && this.fieldOptions.node_info.indexOf('schema') >= 0)
{ {
if(!state) if(!state)
return true; return true;

View File

@ -19,7 +19,7 @@ import current_user from 'pgadmin.user_management.current_user';
import { isEmptyString } from 'sources/validators'; import { isEmptyString } from 'sources/validators';
export default class ServerSchema extends BaseUISchema { export default class ServerSchema extends BaseUISchema {
constructor(serverGroupOptions=[], userId, initValues={}) { constructor(serverGroupOptions=[], userId=0, initValues={}) {
super({ super({
gid: undefined, gid: undefined,
id: undefined, id: undefined,

View File

@ -68,9 +68,7 @@ _.extend(pgBrowser, {
// clear the wcDocker before reset layout. // clear the wcDocker before reset layout.
docker.clear(); docker.clear();
Notify.info(gettext('pgAdmin has reset the layout because the previously saved layout is invalid.'), null); Notify.info(gettext('pgAdmin has reset the layout because the previously saved layout is invalid.'), null);
if(defaultLayoutCallback){ defaultLayoutCallback(docker);
defaultLayoutCallback(docker);
}
} }
} }
} }

View File

@ -171,9 +171,6 @@ define(
p.pgResizeTimeout = null; p.pgResizeTimeout = null;
/** Calculations based on https://getbootstrap.com/docs/4.1/layout/grid/#grid-options **/ /** Calculations based on https://getbootstrap.com/docs/4.1/layout/grid/#grid-options **/
if (w < 480) {
elAttr = 'xs';
}
if (w >= 480) { if (w >= 480) {
elAttr = 'sm'; elAttr = 'sm';
} }

View File

@ -40,6 +40,7 @@ SCHEMA_VERSION = 32
db = SQLAlchemy() db = SQLAlchemy()
USER_ID = 'user.id' USER_ID = 'user.id'
SERVER_ID = 'server.id'
# Define models # Define models
roles_users = db.Table( roles_users = db.Table(
@ -341,7 +342,7 @@ class QueryHistoryModel(db.Model):
db.Integer, db.ForeignKey(USER_ID), nullable=False, primary_key=True db.Integer, db.ForeignKey(USER_ID), nullable=False, primary_key=True
) )
sid = db.Column( sid = db.Column(
db.Integer(), db.ForeignKey('server.id'), nullable=False, db.Integer(), db.ForeignKey(SERVER_ID), nullable=False,
primary_key=True) primary_key=True)
dbname = db.Column(db.String(), nullable=False, primary_key=True) dbname = db.Column(db.String(), nullable=False, primary_key=True)
query_info = db.Column(db.String(), nullable=False) query_info = db.Column(db.String(), nullable=False)
@ -357,7 +358,7 @@ class Database(db.Model):
schema_res = db.Column(db.String(256), nullable=True) schema_res = db.Column(db.String(256), nullable=True)
server = db.Column( server = db.Column(
db.Integer, db.Integer,
db.ForeignKey('server.id'), db.ForeignKey(SERVER_ID),
nullable=False, nullable=False,
primary_key=True primary_key=True
) )
@ -370,7 +371,7 @@ class SharedServer(db.Model):
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
osid = db.Column( osid = db.Column(
db.Integer, db.Integer,
db.ForeignKey('server.id'), db.ForeignKey(SERVER_ID),
nullable=False nullable=False
) )
user_id = db.Column( user_id = db.Column(

View File

@ -11,8 +11,8 @@ import React, { useCallback } from 'react';
import _ from 'lodash'; import _ from 'lodash';
import { FormInputText, FormInputSelect, FormInputSwitch, FormInputCheckbox, FormInputColor, import { FormInputText, FormInputSelect, FormInputSwitch, FormInputCheckbox, FormInputColor,
FormInputFileSelect, FormInputToggle, InputSwitch, FormInputSQL, FormNote, FormInputDateTimePicker, PlainString } from '../components/FormComponents'; FormInputFileSelect, FormInputToggle, InputSwitch, FormInputSQL, FormNote, FormInputDateTimePicker, PlainString,
import { InputSelect, InputText, InputCheckbox, InputDateTimePicker } from '../components/FormComponents'; InputSelect, InputText, InputCheckbox, InputDateTimePicker } from '../components/FormComponents';
import Privilege from '../components/Privilege'; import Privilege from '../components/Privilege';
import { evalFunc } from 'sources/utils'; import { evalFunc } from 'sources/utils';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';

View File

@ -89,15 +89,11 @@ function isValueEqual(val1, val2) {
/* If the orig value was null and new one is empty string, then its a "no change" */ /* If the orig value was null and new one is empty string, then its a "no change" */
/* If the orig value and new value are of different datatype but of same value(numeric) "no change" */ /* If the orig value and new value are of different datatype but of same value(numeric) "no change" */
/* If the orig value is undefined or null and new value is boolean false "no change" */ /* If the orig value is undefined or null and new value is boolean false "no change" */
if ((_.isEqual(val1, val2) return (_.isEqual(val1, val2)
|| ((val1 === null || _.isUndefined(val1)) && val2 === '') || ((val1 === null || _.isUndefined(val1)) && val2 === '')
|| ((val1 === null || _.isUndefined(val1)) && typeof(val2) === 'boolean' && !val2) || ((val1 === null || _.isUndefined(val1)) && typeof(val2) === 'boolean' && !val2)
|| (attrDefined ? _.isEqual(val1.toString(), val2.toString()) : false || (attrDefined ? _.isEqual(val1.toString(), val2.toString()) : false
))) { ));
return true;
} else {
return false;
}
} }
function getChangedData(topSchema, viewHelperProps, sessData, stringify=false, includeSkipChange=true) { function getChangedData(topSchema, viewHelperProps, sessData, stringify=false, includeSkipChange=true) {

View File

@ -74,8 +74,7 @@ define([
return m; return m;
} }
var idx = 1, var idx, len = _.size(m);
len = _.size(m);
switch (mode) { switch (mode) {
case 'properties': case 'properties':

View File

@ -1589,9 +1589,10 @@ define([
if (_.isUndefined(rawValue) || _.isNull(rawValue)) return ''; if (_.isUndefined(rawValue) || _.isNull(rawValue)) return '';
var pass = ''; var pass = '';
for (var i = 0; i < rawValue.length; i++) { rawValue.forEach(() => {
pass += '*'; pass += '*';
} });
return pass; return pass;
}, },
}); });

View File

@ -14,7 +14,7 @@ import axios from 'axios';
export function setPGCSRFToken(header, token) { export function setPGCSRFToken(header, token) {
if (!token) { if (!token) {
// Throw error message. // Throw error message.
throw 'csrf-token meta tag has not been set'; throw new Error('csrf-token meta tag has not been set');
} }
// Configure Backbone.sync to set CSRF-Token-header request header for // Configure Backbone.sync to set CSRF-Token-header request header for

View File

@ -9,8 +9,7 @@
import $ from 'jquery'; import $ from 'jquery';
import Mousetrap from 'mousetrap'; import Mousetrap from 'mousetrap';
import { findAndSetFocus } from './utils'; import { findAndSetFocus, parseShortcutValue } from './utils';
import { parseShortcutValue } from './utils';
class dialogTabNavigator { class dialogTabNavigator {
constructor(dialogContainer, backwardShortcut, forwardShortcut) { constructor(dialogContainer, backwardShortcut, forwardShortcut) {

View File

@ -220,7 +220,7 @@ var Notifier = {
} }
this.alert(promptmsg, msg.replace(new RegExp(/\r?\n/, 'g'), '<br />')); this.alert(promptmsg, msg.replace(new RegExp(/\r?\n/, 'g'), '<br />'));
}, },
alert: (title, text, okLabel=gettext('OK'), onOkClick)=>{ alert: (title, text, onOkClick, okLabel=gettext('OK'))=>{
if(!modalInitialized) { if(!modalInitialized) {
initializeModalProvider(); initializeModalProvider();
} }

View File

@ -12,9 +12,8 @@ import { render } from 'react-dom';
import { FileTreeX, TreeModelX } from 'pgadmin4-tree'; import { FileTreeX, TreeModelX } from 'pgadmin4-tree';
import {Tree} from './tree'; import {Tree} from './tree';
import { IBasicFileSystemHost } from 'react-aspen'; import { IBasicFileSystemHost, Directory } from 'react-aspen';
import { ManageTreeNodes } from './tree_nodes'; import { ManageTreeNodes } from './tree_nodes';
import { Directory } from 'react-aspen';
import pgAdmin from 'sources/pgadmin'; import pgAdmin from 'sources/pgadmin';
var initBrowserTree = async (pgBrowser) => { var initBrowserTree = async (pgBrowser) => {
@ -29,8 +28,7 @@ var initBrowserTree = async (pgBrowser) => {
const host: IBasicFileSystemHost = { const host: IBasicFileSystemHost = {
pathStyle: 'unix', pathStyle: 'unix',
getItems: async (path) => { getItems: async (path) => {
let nodes = await mtree.readNode(path); return await mtree.readNode(path);
return nodes;
}, },
sortComparator: (a: FileEntry | Directory, b: FileEntry | Directory) => { sortComparator: (a: FileEntry | Directory, b: FileEntry | Directory) => {
// No nee to sort columns // No nee to sort columns
@ -39,9 +37,13 @@ var initBrowserTree = async (pgBrowser) => {
if (a.constructor === b.constructor) { if (a.constructor === b.constructor) {
return pgAdmin.natural_sort(a.fileName, b.fileName); return pgAdmin.natural_sort(a.fileName, b.fileName);
} }
return a.constructor === Directory ? -1 let retval = 0;
: b.constructor === Directory ? 1 if (a.constructor === Directory) {
: 0 retval = -1;
} else if (b.constructor === Directory) {
retval = 1;
}
return retval;
}, },
} }

View File

@ -14,7 +14,7 @@ import _ from 'underscore';
import { FileType } from 'react-aspen' import { FileType } from 'react-aspen'
import { findInTree } from './tree'; import { findInTree } from './tree';
import { dirname, unix } from 'path-fx'; import { unix } from 'path-fx';
export class ManageTreeNodes { export class ManageTreeNodes {
constructor(fs) { constructor(fs) {
@ -115,17 +115,17 @@ export class ManageTreeNodes {
} }
} }
async function jsonData(url) { async function jsonData(fetch_url) {
let res = await fetch(url, { let result = await fetch(fetch_url, {
headers: { headers: {
'X-Requested-With': 'XMLHttpRequest', 'X-Requested-With': 'XMLHttpRequest',
'X-pgA-CSRFToken': pgAdmin.csrf_token 'X-pgA-CSRFToken': pgAdmin.csrf_token
}, },
}); });
if (res.status == 200) { if (result.status == 200) {
try { try {
let json = await res.json(); let json = await result.json();
return json.data; return json.data;
} catch (e) { } catch (e) {
console.warn(e); console.warn(e);
@ -146,7 +146,7 @@ export class ManageTreeNodes {
} }
} }
let d = await fill(treeData); await fill(treeData);
if (node.children.length > 0) res(node.children); if (node.children.length > 0) res(node.children);
else res(null); else res(null);

View File

@ -318,7 +318,7 @@ div.jsoneditor-value[contenteditable=true]:hover
.jsoneditor .jsoneditor-text-errors { .jsoneditor .jsoneditor-text-errors {
width: 100%; width: 100%;
border-collapse: collapse; border-collapse: collapse;
border-top: 1px solid $color-gray;; border-top: 1px solid $color-gray;
} }

View File

@ -62,9 +62,6 @@
display: -webkit-flex; /* Safari */ display: -webkit-flex; /* Safari */
display: flex; display: flex;
}
.wcFrameButtonBar {
flex-direction: row-reverse; flex-direction: row-reverse;
} }

View File

@ -363,10 +363,10 @@
keyPathAccessor: function(obj, path) { keyPathAccessor: function(obj, path) {
var res = obj; var res = obj;
path = path.split('.'); path = path.split('.');
for (var i = 0; i < path.length; i++) { for (let path_val of path) {
if (_.isNull(res)) return null; if (_.isNull(res)) return null;
if (_.isEmpty(path[i])) continue; if (_.isEmpty(path_val)) continue;
if (!_.isUndefined(res[path[i]])) res = res[path[i]]; if (!_.isUndefined(res[path_val])) res = res[path_val];
} }
return _.isObject(res) && !_.isArray(res) ? null : res; return _.isObject(res) && !_.isArray(res) ? null : res;
}, },

View File

@ -381,7 +381,7 @@ export function getMiscellaneousSchema(fieldOptions) {
} }
export default class BackupSchema extends BaseUISchema { export default class BackupSchema extends BaseUISchema {
constructor(getSectionSchema, getTypeObjSchema, getSaveOptSchema, getQueryOptionSchema, getDisabledOptionSchema, getMiscellaneousSchema, fieldOptions = {}, treeNodeInfo, pgBrowser, backupType) { constructor(getSectionSchema, getTypeObjSchema, getSaveOptSchema, getQueryOptionSchema, getDisabledOptionSchema, getMiscellaneousSchema, fieldOptions = {}, treeNodeInfo=[], pgBrowser=null, backupType='server') {
super({ super({
file: undefined, file: undefined,
format: 'custom', format: 'custom',

View File

@ -10,8 +10,7 @@
/* /*
* The ERDCore is the middleware between the canvas engine and the UI DOM. * The ERDCore is the middleware between the canvas engine and the UI DOM.
*/ */
import createEngine from '@projectstorm/react-diagrams'; import createEngine, {DagreEngine, PathFindingLinkFactory, PortModelAlignment} from '@projectstorm/react-diagrams';
import {DagreEngine, PathFindingLinkFactory, PortModelAlignment} from '@projectstorm/react-diagrams';
import { ZoomCanvasAction } from '@projectstorm/react-canvas-core'; import { ZoomCanvasAction } from '@projectstorm/react-canvas-core';
import _ from 'lodash'; import _ from 'lodash';

View File

@ -189,8 +189,7 @@ export default function GrantWizard({ sid, did, nodeInfo, nodeData }) {
}, [nodeData]); }, [nodeData]);
const wizardStepChange = (data) => { const wizardStepChange = (data) => {
switch (data.currentStep) { if (data.currentStep == 2) {
case 2:
setLoaderText('Loading SQL ...'); setLoaderText('Loading SQL ...');
var msql_url = url_for( var msql_url = url_for(
'grant_wizard.modified_sql', { 'grant_wizard.modified_sql', {
@ -209,9 +208,6 @@ export default function GrantWizard({ sid, did, nodeInfo, nodeData }) {
.catch(() => { .catch(() => {
Notify.error(gettext('Error while fetching SQL.')); Notify.error(gettext('Error while fetching SQL.'));
}); });
break;
default:
break;
} }
}; };

View File

@ -131,8 +131,7 @@ export default function ImportExportServers() {
}); });
const wizardStepChange= (data) => { const wizardStepChange= (data) => {
switch (data.currentStep) { if (data.currentStep == 2) {
case 2: {
let sumData = [], let sumData = [],
serverSerialNumber = 0; serverSerialNumber = 0;
serverData.forEach((server_group) => { serverData.forEach((server_group) => {
@ -158,10 +157,6 @@ export default function ImportExportServers() {
setNoteText('On a successful import process, the browser tree will be refreshed.'); setNoteText('On a successful import process, the browser tree will be refreshed.');
} }
} }
break;
}
default:
break;
} }
}; };

View File

@ -331,7 +331,7 @@ export function getRestoreMiscellaneousSchema(fieldOptions) {
//Restore Schema //Restore Schema
export default class RestoreSchema extends BaseUISchema { export default class RestoreSchema extends BaseUISchema {
constructor(getRestoreSectionSchema, getRestoreTypeObjSchema, getRestoreSaveOptSchema, getRestoreQueryOptionSchema, getRestoreDisableOptionSchema, getRestoreMiscellaneousSchema, fieldOptions = {}, treeNodeInfo, pgBrowser) { constructor(getRestoreSectionSchema, getRestoreTypeObjSchema, getRestoreSaveOptSchema, getRestoreQueryOptionSchema, getRestoreDisableOptionSchema, getRestoreMiscellaneousSchema, fieldOptions = {}, treeNodeInfo=[], pgBrowser=null) {
super({ super({
custom: false, custom: false,
file: undefined, file: undefined,

View File

@ -569,18 +569,17 @@ WHERE db.datname = current_database()""")
FROM FROM
pg_catalog.pg_stat_gssapi pg_catalog.pg_stat_gssapi
WHERE pid = pg_backend_pid()""") WHERE pid = pg_backend_pid()""")
if status is None: if status is None and cur.rowcount > 0:
if cur.rowcount > 0: res_enc = cur.fetchmany(1)[0]
res_enc = cur.fetchmany(1)[0] manager.db_info[res['did']]['gss_authenticated'] =\
manager.db_info[res['did']]['gss_authenticated'] =\ res_enc['gss_authenticated']
res_enc['gss_authenticated'] manager.db_info[res['did']]['gss_encrypted'] = \
manager.db_info[res['did']]['gss_encrypted'] = \ res_enc['encrypted']
res_enc['encrypted']
if len(manager.db_info) == 1: if len(manager.db_info) == 1:
manager.gss_authenticated = \ manager.gss_authenticated = \
res_enc['gss_authenticated'] res_enc['gss_authenticated']
manager.gss_encrypted = res_enc['encrypted'] manager.gss_encrypted = res_enc['encrypted']
self._set_user_info(cur, manager, **kwargs) self._set_user_info(cur, manager, **kwargs)

View File

@ -3,8 +3,7 @@ import React from 'react';
import {mount} from 'enzyme'; import {mount} from 'enzyme';
import '../helper/enzyme.helper'; import '../helper/enzyme.helper';
import Graphs, {GraphsWrapper} from '../../../pgadmin/dashboard/static/js/Graphs'; import Graphs, {GraphsWrapper, X_AXIS_LENGTH, POINT_SIZE, transformData, legendCallback,
import {X_AXIS_LENGTH, POINT_SIZE, transformData, legendCallback,
getStatsUrl, statsReducer} from '../../../pgadmin/dashboard/static/js/Graphs'; getStatsUrl, statsReducer} from '../../../pgadmin/dashboard/static/js/Graphs';
describe('Graphs.js', ()=>{ describe('Graphs.js', ()=>{
@ -166,4 +165,4 @@ describe('Graphs.js', ()=>{
done(); done();
}); });
}); });
}); });

View File

@ -15,8 +15,7 @@ import pgAdmin from 'sources/pgadmin';
import {messages} from '../fake_messages'; import {messages} from '../fake_messages';
import SchemaView from '../../../pgadmin/static/js/SchemaView'; import SchemaView from '../../../pgadmin/static/js/SchemaView';
import BaseUISchema from 'sources/SchemaView/base_schema.ui'; import BaseUISchema from 'sources/SchemaView/base_schema.ui';
import DomainSchema from '../../../pgadmin/browser/server_groups/servers/databases/schemas/domains/static/js/domain.ui'; import DomainSchema, { DomainConstSchema } from '../../../pgadmin/browser/server_groups/servers/databases/schemas/domains/static/js/domain.ui';
import { DomainConstSchema } from '../../../pgadmin/browser/server_groups/servers/databases/schemas/domains/static/js/domain.ui';
describe('DomainSchema', ()=>{ describe('DomainSchema', ()=>{
let mount; let mount;

View File

@ -14,8 +14,7 @@ import { createMount } from '@material-ui/core/test-utils';
import pgAdmin from 'sources/pgadmin'; import pgAdmin from 'sources/pgadmin';
import {messages} from '../fake_messages'; import {messages} from '../fake_messages';
import SchemaView from '../../../pgadmin/static/js/SchemaView'; import SchemaView from '../../../pgadmin/static/js/SchemaView';
import PgaJobScheduleSchema from '../../../pgadmin/browser/server_groups/servers/pgagent/schedules/static/js/pga_schedule.ui'; import PgaJobScheduleSchema, { ExceptionsSchema } from '../../../pgadmin/browser/server_groups/servers/pgagent/schedules/static/js/pga_schedule.ui';
import { ExceptionsSchema } from '../../../pgadmin/browser/server_groups/servers/pgagent/schedules/static/js/pga_schedule.ui';
describe('PgaJobScheduleSchema', ()=>{ describe('PgaJobScheduleSchema', ()=>{
let mount; let mount;

View File

@ -73,7 +73,7 @@ describe('SearchObjectsDialogWrapper', () => {
}, },
keyboardNavigation: jasmine.createSpyObj('keyboardNavigation', ['getDialogTabNavigator']), keyboardNavigation: jasmine.createSpyObj('keyboardNavigation', ['getDialogTabNavigator']),
}; };
pgBrowser.tree = new TreeFake(pgBrowser), pgBrowser.tree = new TreeFake(pgBrowser);
noDataNode = pgBrowser.tree.addNewNode('level1.1', undefined, [{id: 'level1'}]); noDataNode = pgBrowser.tree.addNewNode('level1.1', undefined, [{id: 'level1'}]);
serverTreeNode = pgBrowser.tree.addNewNode('level2.1', { serverTreeNode = pgBrowser.tree.addNewNode('level2.1', {
_type: 'server', _type: 'server',

View File

@ -26,9 +26,7 @@ describe('#enableTriggers', () => {
tree = new TreeFake(); tree = new TreeFake();
spyOn(tree, 'unload').and.callFake(function() { spyOn(tree, 'unload').and.callFake(function() {
return new Promise((resolve)=>{ return Promise.resolve('Success!');
resolve('Success!');
});
}); });
const server1 = tree.addNewNode('server1', {_id: 1}, ['<li>server1</li>']); const server1 = tree.addNewNode('server1', {_id: 1}, ['<li>server1</li>']);
@ -180,9 +178,7 @@ describe('#disableTriggers', () => {
generateUrlSpy = jasmine.createSpy('generateUrl'); generateUrlSpy = jasmine.createSpy('generateUrl');
generateUrlSpy.and.returnValue('/some/place'); generateUrlSpy.and.returnValue('/some/place');
spyOn(tree, 'unload').and.callFake(function() { spyOn(tree, 'unload').and.callFake(function() {
return new Promise((resolve)=>{ return Promise.resolve('Success!');
resolve('Success!');
});
}); });
}); });

View File

@ -181,9 +181,7 @@ describe('tree tests', () => {
'setActiveFile', 'closeDirectory', 'getActiveFile', 'setActiveFile', 'closeDirectory', 'getActiveFile',
'deSelectActiveFile']); 'deSelectActiveFile']);
tree.tree.unload.and.callFake(function() { tree.tree.unload.and.callFake(function() {
return new Promise((resolve)=>{ return Promise.resolve('Success!');
resolve('Success!');
});
}); });
}); });
@ -260,9 +258,7 @@ describe('tree tests', () => {
tree.addNewNode('level3', {data: 'more data'}, ['<li>level3</li>'], ['level1','level2']); tree.addNewNode('level3', {data: 'more data'}, ['<li>level3</li>'], ['level1','level2']);
tree.tree = jasmine.createSpyObj('tree', ['unload']); tree.tree = jasmine.createSpyObj('tree', ['unload']);
tree.tree.unload.and.callFake(() => { tree.tree.unload.and.callFake(() => {
return new Promise((resolve)=>{ return Promise.resolve('Success!');
resolve('Success!');
});
}); });
}); });