Fix sonarqube issues for the rule - 'If' statement should not be the only statement in 'else' block

This commit is contained in:
Aditya Toshniwal 2024-02-26 11:55:36 +05:30
parent e272552780
commit a5530f59f7
26 changed files with 409 additions and 481 deletions

View File

@ -72,12 +72,10 @@ const getAppDataPath = () => {
default:
if (platform().startsWith('win')) {
appDataPath = path.join(process.env.APPDATA, 'pgadmin');
} else if ('XDG_CONFIG_HOME' in process.env) {
appDataPath = path.join(process.env.XDG_CONFIG_HOME, 'pgadmin');
} else {
if ('XDG_CONFIG_HOME' in process.env) {
appDataPath = path.join(process.env.XDG_CONFIG_HOME, 'pgadmin');
} else {
appDataPath = path.join(homedir(), '.config', 'pgadmin');
}
appDataPath = path.join(homedir(), '.config', 'pgadmin');
}
}
@ -108,12 +106,10 @@ const getLocalAppDataPath = () => {
default:
if (platform().startsWith('win')) {
localAppDataPath = path.join(process.env.LOCALAPPDATA, 'pgadmin');
} else if ('XDG_DATA_HOME' in process.env) {
localAppDataPath = path.join(process.env.XDG_DATA_HOME, 'pgadmin');
} else {
if ('XDG_DATA_HOME' in process.env) {
localAppDataPath = path.join(process.env.XDG_DATA_HOME, 'pgadmin');
} else {
localAppDataPath = path.join(homedir(), '.local', 'share', 'pgadmin');
}
localAppDataPath = path.join(homedir(), '.local', 'share', 'pgadmin');
}
}
@ -412,14 +408,12 @@ let ConfigureStore = {
...this.jsonData,
...key,
};
} else {
if(value === '' || value == null || typeof(value) == 'undefined') {
if(this.jsonData[key] !== undefined) {
delete this.jsonData[key];
}
} else {
this.jsonData[key] = value;
} else if(value === '' || value == null || typeof(value) == 'undefined') {
if(this.jsonData[key] !== undefined) {
delete this.jsonData[key];
}
} else {
this.jsonData[key] = value;
}
},
};

View File

@ -633,10 +633,8 @@ function updateCheckedMenuItem(menuItem) {
sm.checked = menuItem.checked
}
})
} else {
if (sub.label == menuItem.label && type == 'checkbox') {
sub.checked = menuItem.checked
}
} else if (sub.label == menuItem.label && type == 'checkbox') {
sub.checked = menuItem.checked
}
});
});

View File

@ -449,15 +449,13 @@ export default class FunctionSchema extends BaseUISchema {
setError('prosrc_c', null);
}
}else {
}else if (isEmptyString(state.prosrc)) {
/* code validation*/
if (isEmptyString(state.prosrc)) {
errmsg = gettext('Code cannot be empty.');
setError('prosrc', errmsg);
return true;
} else {
setError('prosrc', null);
}
errmsg = gettext('Code cannot be empty.');
setError('prosrc', errmsg);
return true;
} else {
setError('prosrc', null);
}
}
}

View File

@ -1079,6 +1079,7 @@ class TableView(BaseTableView, DataTypeReader, SchemaDiffTableCompare):
return super().update(
gid, sid, did, scid, tid, data=data, res=res)
except Exception as e:
current_app.logger.exception(e)
return internal_server_error(errormsg=str(e))
@BaseTableView.check_precondition

View File

@ -90,17 +90,15 @@ export default class MainMenuFactory {
options.module[options.callback].apply(options.module, [options.data, pgAdmin.Browser.tree?.selected()]);
} else if (options?.callback) {
options.callback(options);
} else {
if (options.url != '#') {
let api = getApiInstance();
api(
url_for('tools.initialize')
).then(()=>{
window.open(options.url);
}).catch(()=>{
pgAdmin.Browser.notifier.error(gettext('Error in opening window'));
});
}
} else if (options.url != '#') {
let api = getApiInstance();
api(
url_for('tools.initialize')
).then(()=>{
window.open(options.url);
}).catch(()=>{
pgAdmin.Browser.notifier.error(gettext('Error in opening window'));
});
}
}}, (menu, item)=> {
pgAdmin.Browser.Events.trigger('pgadmin:nw-enable-disable-menu-items', menu, item);

View File

@ -56,21 +56,18 @@ define('pgadmin.browser', [
// calc method logic
calc: (passed_width) => {
let iw = window.innerWidth;
if(iw > passed_width){
if(iw > passed_width)
return passed_width;
}else{
if (iw > pgAdmin.Browser.stdW.lg)
return pgAdmin.Browser.stdW.lg;
else if (iw > pgAdmin.Browser.stdW.md)
return pgAdmin.Browser.stdW.md;
else if (iw > pgAdmin.Browser.stdW.sm)
return pgAdmin.Browser.stdW.sm;
else
// if avilable screen resolution is still
// less then return the width value as it
return iw;
}
else if (iw > pgAdmin.Browser.stdW.lg)
return pgAdmin.Browser.stdW.lg;
else if (iw > pgAdmin.Browser.stdW.md)
return pgAdmin.Browser.stdW.md;
else if (iw > pgAdmin.Browser.stdW.sm)
return pgAdmin.Browser.stdW.sm;
else
// if avilable screen resolution is still
// less then return the width value as it
return iw;
},
},
stdH: {
@ -83,18 +80,16 @@ define('pgadmin.browser', [
calc: (passed_height) => {
// We are excluding sm as it is too small for dialog
let ih = window.innerHeight;
if (ih > passed_height){
if (ih > passed_height)
return passed_height;
} else {
if (ih > pgAdmin.Browser.stdH.lg)
return pgAdmin.Browser.stdH.lg;
else if (ih > pgAdmin.Browser.stdH.md)
return pgAdmin.Browser.stdH.md;
else
// if avilable screen resolution is still
// less then return the height value as it
return ih;
}
else if (ih > pgAdmin.Browser.stdH.lg)
return pgAdmin.Browser.stdH.lg;
else if (ih > pgAdmin.Browser.stdH.md)
return pgAdmin.Browser.stdH.md;
else
// if avilable screen resolution is still
// less then return the height value as it
return ih;
},
},
// Default panels
@ -666,10 +661,8 @@ define('pgadmin.browser', [
if (d._type === 'column') {
if (pgAdmin.numeric_comparator(d._id, _data._id) == 1)
return true;
} else {
if (pgAdmin.natural_sort(d._label, _data._label) == 1)
return true;
}
} else if (pgAdmin.natural_sort(d._label, _data._label) == 1)
return true;
s++;
}
//when the current element is greater than the end element
@ -693,10 +686,8 @@ define('pgadmin.browser', [
if (d._type === 'column') {
if (pgAdmin.numeric_comparator(d._id, _data._id) != -1)
return true;
} else {
if (pgAdmin.natural_sort(d._label, _data._label) != -1)
return true;
}
} else if (pgAdmin.natural_sort(d._label, _data._label) != -1)
return true;
i = items[e];
d = __ctx.t.itemData(i);
let result;
@ -767,16 +758,14 @@ define('pgadmin.browser', [
) {
___ctx.t.open(___ctx.i);
___ctx.t.select(_i);
} else {
if (_parent_data) {
// Unload the parent node so that we'll get
// latest data when we try to expand it
___ctx.t.unload(___ctx.i).then(
() => {
___ctx.t.open(___ctx.i);
}
);
}
} else if (_parent_data) {
// Unload the parent node so that we'll get
// latest data when we try to expand it
___ctx.t.unload(___ctx.i).then(
() => {
___ctx.t.open(___ctx.i);
}
);
}
if (typeof(___ctx?.o?.success) == 'function') {
___ctx.o.success.apply(___ctx.t, [_i, _data]);
@ -1154,10 +1143,8 @@ define('pgadmin.browser', [
if (d._type === 'column') {
if (pgAdmin.numeric_comparator(d._id, _new._id) == 1)
return true;
} else {
if (pgAdmin.natural_sort(d._label, _new._label) == 1)
return true;
}
} else if (pgAdmin.natural_sort(d._label, _new._label) == 1)
return true;
s++;
}
if (e != items.length - 1) {
@ -1174,10 +1161,8 @@ define('pgadmin.browser', [
if (d._type === 'column') {
if (pgAdmin.numeric_comparator(d._id, _new._id) != -1)
return true;
} else {
if (pgAdmin.natural_sort(d._label, _new._label) != -1)
return true;
}
} else if (pgAdmin.natural_sort(d._label, _new._label) != -1)
return true;
i = items[e];
d = __ctx.t.itemData(i);
let result;
@ -1678,14 +1663,10 @@ define('pgadmin.browser', [
);
});
if (_callback) {
_callback();
}
_callback?.();
});
} else {
if (_callback) {
_callback();
}
_callback?.();
}
},

View File

@ -821,22 +821,18 @@ define('pgadmin.browser.node', [
/* Fit to standard sizes */
if(w <= pgBrowser.stdW.sm) {
w = pgBrowser.stdW.sm;
} else if(w <= pgBrowser.stdW.md) {
w = pgBrowser.stdW.md;
} else {
if(w <= pgBrowser.stdW.md) {
w = pgBrowser.stdW.md;
} else {
w = pgBrowser.stdW.lg;
}
w = pgBrowser.stdW.lg;
}
if(h <= pgBrowser.stdH.sm) {
h = pgBrowser.stdH.sm;
} else if(h <= pgBrowser.stdH.md) {
h = pgBrowser.stdH.md;
} else {
if(h <= pgBrowser.stdH.md) {
h = pgBrowser.stdH.md;
} else {
h = pgBrowser.stdH.lg;
}
h = pgBrowser.stdH.lg;
}
if(update) {

View File

@ -616,10 +616,8 @@ export default function FileManager({params, closeModal, onOK, onCancel, sharedS
const onItemEnter = useCallback(async (row)=>{
if(row.file_type == 'dir' || row.file_type == 'drive') {
await openDir(row.Path, selectedSS);
} else {
if(params.dialog_type == 'select_file') {
onOkClick();
}
} else if(params.dialog_type == 'select_file') {
onOkClick();
}
}, [filteredItems]);
const onItemSelect = useCallback((idx)=>{

View File

@ -147,18 +147,14 @@ export default function ObjectNodeProperties({panelId, node, treeNodeInfo, nodeD
if (server.server_type == 'ppas' && node.epasHelp) {
fullUrl = getEPASHelpUrl(server.version);
} else if (node.sqlCreateHelp == '' && node.sqlAlterHelp != '') {
fullUrl = getHelpUrl(helpUrl, node.sqlAlterHelp, server.version);
} else if (node.sqlCreateHelp != '' && node.sqlAlterHelp == '') {
fullUrl = getHelpUrl(helpUrl, node.sqlCreateHelp, server.version);
} else if (isNew) {
fullUrl = getHelpUrl(helpUrl, node.sqlCreateHelp, server.version);
} else {
if (node.sqlCreateHelp == '' && node.sqlAlterHelp != '') {
fullUrl = getHelpUrl(helpUrl, node.sqlAlterHelp, server.version);
} else if (node.sqlCreateHelp != '' && node.sqlAlterHelp == '') {
fullUrl = getHelpUrl(helpUrl, node.sqlCreateHelp, server.version);
} else {
if (isNew) {
fullUrl = getHelpUrl(helpUrl, node.sqlCreateHelp, server.version);
} else {
fullUrl = getHelpUrl(helpUrl, node.sqlAlterHelp, server.version);
}
}
fullUrl = getHelpUrl(helpUrl, node.sqlAlterHelp, server.version);
}
window.open(fullUrl, 'postgres_help');

View File

@ -390,11 +390,9 @@ function parsePlan(data, ctx) {
plans.push(plan);
idx++;
});
} else{
if('loops' in data && 'exclusive' in data) {
data['inclusive'] = Math.ceil10(data['Actual Total Time'] / data['loops'] || 1, -3);
data['exclusive'] = data['inclusive'];
}
} else if('loops' in data && 'exclusive' in data) {
data['inclusive'] = Math.ceil10(data['Actual Total Time'] / data['loops'] || 1, -3);
data['exclusive'] = data['inclusive'];
}
if ('exclusive' in data) {

View File

@ -41,12 +41,10 @@ export function menuSearch(param, props) {
if(subMenu.getMenuItems()) {
iterItem(subMenu.getMenuItems(), getMenuName(subMenu), path);
}
} else if(typeof(subMenu) == 'object' && !(subMenu instanceof NewMenuItem)) {
iterItem(Object.values(subMenu), path, parentPath);
} else {
if(typeof(subMenu) == 'object' && !(subMenu instanceof NewMenuItem)) {
iterItem(Object.values(subMenu), path, parentPath);
} else {
iterItem(subMenu, path, parentPath);
}
iterItem(subMenu, path, parentPath);
}
});
};

View File

@ -157,99 +157,97 @@ function getChangedData(topSchema, viewHelperProps, sessData, stringify=false, i
...levelChanges,
...parseChanges(field.schema, origVal, sessVal),
};
} else {
} else if(isEdit && !_.isEqual(_.get(origVal, field.id), _.get(sessVal, field.id))) {
/* Check for changes only if its in edit mode, otherwise everything can go through comparator */
if(isEdit && !_.isEqual(_.get(origVal, field.id), _.get(sessVal, field.id))) {
let change = null;
if(field.type === 'collection') {
/* Use diffArray package to get the array diff and extract the info.
cid is used to identify the rows uniquely */
const changeDiff = diffArray(
_.get(origVal, field.id) || [],
_.get(sessVal, field.id) || [],
'cid',
{
compareFunction: isObjectEqual,
}
);
change = {};
if(changeDiff.added.length > 0) {
change['added'] = cleanCid(changeDiff.added, viewHelperProps.keepCid);
}
if(changeDiff.removed.length > 0) {
change['deleted'] = cleanCid(changeDiff.removed.map((row)=>{
/* Deleted records should be original, not the changed */
return _.find(_.get(origVal, field.id), ['cid', row.cid]);
}), viewHelperProps.keepCid);
}
if(changeDiff.updated.length > 0) {
/* There is change in collection. Parse further to go deep */
let changed = [];
for(const changedRow of changeDiff.updated) {
let finalChangedRow = {};
let rowIndxSess = _.findIndex(_.get(sessVal, field.id), (r)=>r.cid==changedRow.cid);
let rowIndxOrig = _.findIndex(_.get(origVal, field.id), (r)=>r.cid==changedRow.cid);
finalChangedRow = parseChanges(field.schema, _.get(origVal, [field.id, rowIndxOrig]), _.get(sessVal, [field.id, rowIndxSess]));
if(_.isEmpty(finalChangedRow)) {
continue;
}
/* If the id attr value is present, then only changed keys can be passed.
Otherwise, passing all the keys is useful */
let idAttrValue = _.get(sessVal, [field.id, rowIndxSess, field.schema.idAttribute]);
if(_.isUndefined(idAttrValue)) {
changed.push({
...changedRow,
...finalChangedRow,
});
} else {
changed.push({
[field.schema.idAttribute]: idAttrValue,
...finalChangedRow,
});
}
}
if(changed.length > 0) {
change['changed'] = cleanCid(changed, viewHelperProps.keepCid);
}
}
if(Object.keys(change).length > 0) {
attrChanged(field.id, change, true);
}
} else {
attrChanged(field.id);
}
} else if(!isEdit) {
if(field.type === 'collection') {
const origColl = _.get(origVal, field.id) || [];
const sessColl = _.get(sessVal, field.id) || [];
let changeDiff = diffArray(origColl,sessColl,'cid',{
let change = null;
if(field.type === 'collection') {
/* Use diffArray package to get the array diff and extract the info.
cid is used to identify the rows uniquely */
const changeDiff = diffArray(
_.get(origVal, field.id) || [],
_.get(sessVal, field.id) || [],
'cid',
{
compareFunction: isObjectEqual,
});
}
);
change = {};
if(changeDiff.added.length > 0) {
change['added'] = cleanCid(changeDiff.added, viewHelperProps.keepCid);
}
if(changeDiff.removed.length > 0) {
change['deleted'] = cleanCid(changeDiff.removed.map((row)=>{
/* Deleted records should be original, not the changed */
return _.find(_.get(origVal, field.id), ['cid', row.cid]);
}), viewHelperProps.keepCid);
}
if(changeDiff.updated.length > 0) {
/* There is change in collection. Parse further to go deep */
let changed = [];
for(const changedRow of changeDiff.updated) {
let finalChangedRow = {};
let rowIndxSess = _.findIndex(_.get(sessVal, field.id), (r)=>r.cid==changedRow.cid);
let rowIndxOrig = _.findIndex(_.get(origVal, field.id), (r)=>r.cid==changedRow.cid);
finalChangedRow = parseChanges(field.schema, _.get(origVal, [field.id, rowIndxOrig]), _.get(sessVal, [field.id, rowIndxSess]));
/* For fixed rows, check only the updated changes */
/* If canReorder, check the updated changes */
if((!_.isUndefined(field.fixedRows) && changeDiff.updated.length > 0)
|| (_.isUndefined(field.fixedRows) && (
changeDiff.added.length > 0 || changeDiff.removed.length > 0 || changeDiff.updated.length > 0
))
|| (field.canReorder && _.differenceBy(origColl, sessColl, 'cid'))
) {
if(_.isEmpty(finalChangedRow)) {
continue;
}
/* If the id attr value is present, then only changed keys can be passed.
Otherwise, passing all the keys is useful */
let idAttrValue = _.get(sessVal, [field.id, rowIndxSess, field.schema.idAttribute]);
if(_.isUndefined(idAttrValue)) {
changed.push({
...changedRow,
...finalChangedRow,
});
} else {
changed.push({
[field.schema.idAttribute]: idAttrValue,
...finalChangedRow,
});
}
}
if(changed.length > 0) {
change['changed'] = cleanCid(changed, viewHelperProps.keepCid);
}
}
if(Object.keys(change).length > 0) {
attrChanged(field.id, change, true);
}
} else {
attrChanged(field.id);
}
} else if(!isEdit) {
if(field.type === 'collection') {
const origColl = _.get(origVal, field.id) || [];
const sessColl = _.get(sessVal, field.id) || [];
let changeDiff = diffArray(origColl,sessColl,'cid',{
compareFunction: isObjectEqual,
});
/* For fixed rows, check only the updated changes */
/* If canReorder, check the updated changes */
if((!_.isUndefined(field.fixedRows) && changeDiff.updated.length > 0)
|| (_.isUndefined(field.fixedRows) && (
changeDiff.added.length > 0 || changeDiff.removed.length > 0 || changeDiff.updated.length > 0
))
|| (field.canReorder && _.differenceBy(origColl, sessColl, 'cid'))
) {
let change = cleanCid(_.get(sessVal, field.id), viewHelperProps.keepCid);
attrChanged(field.id, change, true);
return;
}
if(field.canReorder) {
changeDiff = diffArray(origColl,sessColl);
if(changeDiff.updated.length > 0) {
let change = cleanCid(_.get(sessVal, field.id), viewHelperProps.keepCid);
attrChanged(field.id, change, true);
return;
}
if(field.canReorder) {
changeDiff = diffArray(origColl,sessColl);
if(changeDiff.updated.length > 0) {
let change = cleanCid(_.get(sessVal, field.id), viewHelperProps.keepCid);
attrChanged(field.id, change, true);
}
}
} else {
attrChanged(field.id);
}
} else {
attrChanged(field.id);
}
}
});
@ -294,11 +292,9 @@ function validateSchema(schema, sessData, setError, accessPath=[], collLabel=nul
return true;
}
}
} else {
} else if(validateSchema(field.schema, sessData, setError, accessPath)) {
/* A nested schema ? Recurse */
if(validateSchema(field.schema, sessData, setError, accessPath)) {
return true;
}
return true;
}
} else {
/* Normal field, default validations */

View File

@ -122,7 +122,7 @@ export default function cmOverride(theme) {
'&.pg-autocomp-loader': {
position: 'absolute',
paddingRight: '8px',
paddingRight: '1px 12px 1px 2px',
}
}
};

View File

@ -182,28 +182,26 @@ export const PgIconButton = forwardRef(({icon, title, shortcut, className, split
</DefaultButton>
);
}
} else if(color == 'primary') {
return (
<Tooltip title={shortcutTitle || title || ''} aria-label={title || ''}>
<PrimaryButton ref={ref} style={style}
className={clsx(classes.iconButton, (splitButton ? classes.splitButton : ''), className)}
accessKey={accesskey} data-label={title || ''} {...props}>
{icon}
</PrimaryButton>
</Tooltip>
);
} else {
if(color == 'primary') {
return (
<Tooltip title={shortcutTitle || title || ''} aria-label={title || ''}>
<PrimaryButton ref={ref} style={style}
className={clsx(classes.iconButton, (splitButton ? classes.splitButton : ''), className)}
accessKey={accesskey} data-label={title || ''} {...props}>
{icon}
</PrimaryButton>
</Tooltip>
);
} else {
return (
<Tooltip title={shortcutTitle || title || ''} aria-label={title || ''}>
<DefaultButton ref={ref} style={style}
className={clsx(classes.iconButton, classes.iconButtonDefault, (splitButton ? classes.splitButton : ''), className)}
accessKey={accesskey} data-label={title || ''} {...props}>
{icon}
</DefaultButton>
</Tooltip>
);
}
return (
<Tooltip title={shortcutTitle || title || ''} aria-label={title || ''}>
<DefaultButton ref={ref} style={style}
className={clsx(classes.iconButton, classes.iconButtonDefault, (splitButton ? classes.splitButton : ''), className)}
accessKey={accesskey} data-label={title || ''} {...props}>
{icon}
</DefaultButton>
</Tooltip>
);
}
});
PgIconButton.displayName = 'PgIconButton';

View File

@ -857,12 +857,10 @@ function getRealValue(options, value, creatable, formatter) {
/* If multi select options need to be in some format by UI, use formatter */
if (formatter) {
realValue = formatter.fromRaw(realValue, options);
} else if (creatable) {
realValue = realValue.map((val) => ({ label: val, value: val }));
} else {
if (creatable) {
realValue = realValue.map((val) => ({ label: val, value: val }));
} else {
realValue = realValue.map((val) => (_.find(options, (option) => _.isEqual(option.value, val))));
}
realValue = realValue.map((val) => (_.find(options, (option) => _.isEqual(option.value, val))));
}
} else {
let flatOptions = flattenSelectOptions(options);

View File

@ -7,18 +7,11 @@
//
//////////////////////////////////////////////////////////////
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import React, { useEffect, useMemo, useRef } from 'react';
import ReactDOMServer from 'react-dom/server';
import PropTypes from 'prop-types';
import gettext from 'sources/gettext';
import { makeStyles } from '@material-ui/core';
import { PgIconButton } from '../../Buttons';
import { checkTrojanSource } from '../../../utils';
import { copyToClipboard } from '../../../clipboard';
import { useDelayedCaller } from '../../../custom_hooks';
import usePreferences from '../../../../../preferences/static/js/store';
import FileCopyRoundedIcon from '@material-ui/icons/FileCopyRounded';
import CheckRoundedIcon from '@material-ui/icons/CheckRounded';
import KeyboardArrowRightRoundedIcon from '@material-ui/icons/KeyboardArrowRightRounded';
import ExpandMoreRoundedIcon from '@material-ui/icons/ExpandMoreRounded';
@ -44,7 +37,6 @@ import {
foldKeymap,
} from '@codemirror/language';
import FindDialog from './FindDialog';
import syntaxHighlighting from '../extensions/highlighting';
import PgSQL from '../extensions/dialect';
import { sql } from '@codemirror/lang-sql';
@ -52,43 +44,10 @@ import errorMarkerExtn from '../extensions/errorMarker';
import CustomEditorView from '../CustomEditorView';
import breakpointGutter, { breakpointEffect } from '../extensions/breakpointGutter';
import activeLineExtn from '../extensions/activeLineMarker';
import GotoDialog from './GotoDialog';
const arrowRightHtml = ReactDOMServer.renderToString(<KeyboardArrowRightRoundedIcon style={{fontSize: '1.2em'}} />);
const arrowDownHtml = ReactDOMServer.renderToString(<ExpandMoreRoundedIcon style={{fontSize: '1.2em'}} />);
const useStyles = makeStyles(() => ({
copyButton: {
position: 'absolute',
zIndex: 99,
right: '4px',
top: '4px',
}
}));
export function CopyButton({ editor }) {
const classes = useStyles();
const [isCopied, setIsCopied] = useState(false);
const revertCopiedText = useDelayedCaller(() => {
setIsCopied(false);
});
return (
<PgIconButton size="small" className={classes.copyButton} icon={isCopied ? <CheckRoundedIcon /> : <FileCopyRoundedIcon />}
title={isCopied ? gettext('Copied!') : gettext('Copy')}
onClick={() => {
copyToClipboard(editor?.getValue());
setIsCopied(true);
revertCopiedText(1500);
}}
/>
);
}
CopyButton.propTypes = {
editor: PropTypes.object,
};
function handleDrop(e, editor) {
let dropDetails = null;
try {
@ -104,7 +63,6 @@ function handleDrop(e, editor) {
}
} catch (error) {
/* if parsing fails, it must be the drag internal of codemirror text */
// editor.inputState.handlers.drop(e, editor);
return false;
}
@ -171,11 +129,8 @@ const defaultExtensions = [
export default function Editor({
currEditor, name, value, options, onCursorActivity, onChange, readonly, disabled, autocomplete = false,
breakpoint = false, onBreakPointChange, showActiveLine=false, showCopyBtn = false,
keepHistory = true, cid, helpid, labelledBy}) {
const [[showFind, isReplace], setShowFind] = useState([false, false]);
const [showGoto, setShowGoto] = useState(false);
const [showCopy, setShowCopy] = useState(false);
breakpoint = false, onBreakPointChange, showActiveLine=false,
keepHistory = true, cid, helpid, labelledBy, customKeyMap}) {
const editorContainerRef = useRef();
const editor = useRef();
@ -189,28 +144,6 @@ export default function Editor({
const configurables = useRef(new Compartment());
const editableConfig = useRef(new Compartment());
const editMenuKeyMap = [{
key: 'Mod-f', run: (view, e) => {
e.preventDefault();
e.stopPropagation();
setShowFind([false, false]);
setShowFind([true, false]);
}
}, {
key: 'Mod-Alt-f', run: (view, e) => {
e.preventDefault();
e.stopPropagation();
setShowFind([false, false]);
setShowFind([true, true]);
},
}, {
key: 'Mod-l', run: (view, e) => {
e.preventDefault();
e.stopPropagation();
setShowGoto(true);
},
}];
useEffect(() => {
const finalOptions = { ...defaultOptions, ...options };
const finalExtns = [
@ -237,7 +170,7 @@ export default function Editor({
extensions: [
...finalExtns,
configurables.current.of([]),
keymap.of(editMenuKeyMap),
keymap.of(customKeyMap??[]),
editableConfig.current.of([
EditorView.editable.of(!disabled),
EditorState.readOnly.of(readonly),
@ -403,27 +336,9 @@ export default function Editor({
});
}, [readonly, disabled, keepHistory]);
const closeFind = () => {
setShowFind([false, false]);
editor.current?.focus();
};
const closeGoto = () => {
setShowGoto(false);
editor.current?.focus();
};
const onMouseEnter = useCallback(()=>{showCopyBtn && setShowCopy(true);});
const onMouseLeave = useCallback(()=>{showCopyBtn && setShowCopy(false);});
return (
<div onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} style={{height: '100%'}}>
<div style={{ height: '100%' }} ref={editorContainerRef} name={name}></div>
{showCopy && <CopyButton editor={editor.current} />}
<FindDialog editor={editor.current} show={showFind} replace={isReplace} onClose={closeFind} />
<GotoDialog editor={editor.current} show={showGoto} onClose={closeGoto} />
</div>
);
return useMemo(()=>(
<div style={{ height: '100%' }} ref={editorContainerRef} name={name}></div>
), []);
}
Editor.propTypes = {
@ -444,4 +359,5 @@ Editor.propTypes = {
cid: PropTypes.string,
helpid: PropTypes.string,
labelledBy: PropTypes.string,
customKeyMap: PropTypes.array,
};

View File

@ -7,27 +7,121 @@
//
//////////////////////////////////////////////////////////////
import React from 'react';
import React, { useCallback, useMemo, useRef, useState } from 'react';
import { makeStyles } from '@material-ui/core';
import FileCopyRoundedIcon from '@material-ui/icons/FileCopyRounded';
import CheckRoundedIcon from '@material-ui/icons/CheckRounded';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import gettext from 'sources/gettext';
import { PgIconButton } from '../Buttons';
import { copyToClipboard } from '../../clipboard';
import { useDelayedCaller } from '../../custom_hooks';
import Editor from './components/Editor';
import CustomPropTypes from '../../custom_prop_types';
import FindDialog from './components/FindDialog';
import GotoDialog from './components/GotoDialog';
const useStyles = makeStyles(() => ({
root: {
position: 'relative',
height: '100%'
},
copyButton: {
position: 'absolute',
zIndex: 99,
right: '4px',
top: '4px',
}
}));
export default function CodeMirror({className, ...props}) {
function CopyButton({ editor }) {
const classes = useStyles();
const [isCopied, setIsCopied] = useState(false);
const revertCopiedText = useDelayedCaller(() => {
setIsCopied(false);
});
return (
<div className={clsx(className, classes.root)}>
<Editor {...props} />
<PgIconButton size="small" className={classes.copyButton} icon={isCopied ? <CheckRoundedIcon /> : <FileCopyRoundedIcon />}
title={isCopied ? gettext('Copied!') : gettext('Copy')}
onClick={() => {
copyToClipboard(editor?.getValue());
setIsCopied(true);
revertCopiedText(1500);
}}
/>
);
}
CopyButton.propTypes = {
editor: PropTypes.object,
};
export default function CodeMirror({className, currEditor, showCopyBtn=false, ...props}) {
const classes = useStyles();
const editor = useRef();
const [[showFind, isReplace], setShowFind] = useState([false, false]);
const [showGoto, setShowGoto] = useState(false);
const [showCopy, setShowCopy] = useState(false);
const editMenuKeyMap = useMemo(()=>[{
key: 'Mod-f', run: (_view, e) => {
e.preventDefault();
e.stopPropagation();
setShowFind([false, false]);
setShowFind([true, false]);
}
}, {
key: 'Mod-Alt-f', run: (_view, e) => {
e.preventDefault();
e.stopPropagation();
setShowFind([false, false]);
setShowFind([true, true]);
},
}, {
key: 'Mod-l', run: (_view, e) => {
e.preventDefault();
e.stopPropagation();
setShowGoto(true);
},
}], []);
const closeFind = () => {
setShowFind([false, false]);
editor.current?.focus();
};
const closeGoto = () => {
setShowGoto(false);
editor.current?.focus();
};
const currEditorWrap = useCallback((obj)=>{
editor.current = obj;
currEditor?.(obj);
}, []);
const onMouseEnter = useCallback(()=>{showCopyBtn && setShowCopy(true);}, []);
const onMouseLeave = useCallback(()=>{showCopyBtn && setShowCopy(false);}, []);
return (
<div className={clsx(className, classes.root)} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} >
<Editor currEditor={currEditorWrap} customKeyMap={editMenuKeyMap} {...props} />
{showCopy && <CopyButton editor={editor.current} />}
<FindDialog editor={editor.current} show={showFind} replace={isReplace} onClose={closeFind} />
<GotoDialog editor={editor.current} show={showGoto} onClose={closeGoto} />
</div>
);
}
CodeMirror.propTypes = {
currEditor: PropTypes.func,
className: CustomPropTypes.className,
showCopyBtn: PropTypes.bool,
};

View File

@ -133,32 +133,30 @@ class Notifier {
if(!error.response) {
msg = parseApiError(error);
promptmsg = gettext('Connection Lost');
} else {
if(error.response.headers['content-type'] == 'application/json') {
let resp = error.response.data;
if(resp.info == 'CRYPTKEY_MISSING') {
let pgBrowser = window.pgAdmin.Browser;
pgBrowser.set_master_password('', ()=> {
if(onJSONResult && typeof(onJSONResult) == 'function') {
onJSONResult('CRYPTKEY_SET');
}
}, ()=> {
if(onJSONResult && typeof(onJSONResult) == 'function') {
onJSONResult('CRYPTKEY_NOT_SET');
}
});
return;
} else if (resp.result != null && (!resp.errormsg || resp.errormsg == '') &&
onJSONResult && typeof(onJSONResult) == 'function') {
return onJSONResult(resp.result);
}
msg = _.escape(resp.result) || _.escape(resp.errormsg) || 'Unknown error';
} else {
if (type === 'error') {
this.alert('Error', promptmsg);
}
} else if(error.response.headers['content-type'] == 'application/json') {
let resp = error.response.data;
if(resp.info == 'CRYPTKEY_MISSING') {
let pgBrowser = window.pgAdmin.Browser;
pgBrowser.set_master_password('', ()=> {
if(onJSONResult && typeof(onJSONResult) == 'function') {
onJSONResult('CRYPTKEY_SET');
}
}, ()=> {
if(onJSONResult && typeof(onJSONResult) == 'function') {
onJSONResult('CRYPTKEY_NOT_SET');
}
});
return;
} else if (resp.result != null && (!resp.errormsg || resp.errormsg == '') &&
onJSONResult && typeof(onJSONResult) == 'function') {
return onJSONResult(resp.result);
}
msg = _.escape(resp.result) || _.escape(resp.errormsg) || 'Unknown error';
} else {
if (type === 'error') {
this.alert('Error', promptmsg);
}
return;
}
if(type == 'error-noalert' && onJSONResult && typeof(onJSONResult) == 'function') {
return onJSONResult();

View File

@ -39,38 +39,36 @@ function manageTreeEvents(event, eventName, item) {
console.warn(e.stack || e);
return false;
}
} else {
} else if (d && obj.Nodes[d._type]) {
// Events for browser tree.
if (d && obj.Nodes[d._type]) {
node = obj.Nodes[d._type];
node = obj.Nodes[d._type];
// If the Browser tree is not initialised yet
if (obj.tree === null) return;
// If the Browser tree is not initialised yet
if (obj.tree === null) return;
if (eventName == 'dragstart') {
obj.tree.handleDraggable(event, item);
}
if (eventName == 'added' || eventName == 'beforeopen' || eventName == 'loaded') {
obj.tree.addNewNode(item.getMetadata('data').id, item.getMetadata('data'), item, item.parent.path);
}
if(eventName == 'copied') {
obj.tree.copyHandler?.(item.getMetadata('data'), item);
}
if (_.isObject(node.callbacks) &&
eventName in node.callbacks &&
typeof node.callbacks[eventName] == 'function') {
node.callbacks[eventName].apply(node, [item, d, obj, [], eventName]);
}
if (eventName == 'dragstart') {
obj.tree.handleDraggable(event, item);
}
if (eventName == 'added' || eventName == 'beforeopen' || eventName == 'loaded') {
obj.tree.addNewNode(item.getMetadata('data').id, item.getMetadata('data'), item, item.parent.path);
}
if(eventName == 'copied') {
obj.tree.copyHandler?.(item.getMetadata('data'), item);
}
if (_.isObject(node.callbacks) &&
eventName in node.callbacks &&
typeof node.callbacks[eventName] == 'function') {
node.callbacks[eventName].apply(node, [item, d, obj, [], eventName]);
}
/* Raise tree events for the nodes */
try {
obj.Events.trigger(
'pgadmin-browser:tree:' + eventName, item, d, node
);
} catch (e) {
console.warn(e.stack || e);
return false;
}
/* Raise tree events for the nodes */
try {
obj.Events.trigger(
'pgadmin-browser:tree:' + eventName, item, d, node
);
} catch (e) {
console.warn(e.stack || e);
return false;
}
}
return true;
@ -510,12 +508,10 @@ export class Tree {
Object.keys(typeOrTypeDict).forEach((type) => {
this.registerDraggableType(type, typeOrTypeDict[type]);
});
} else {
if (dropDetailsFunc != null) {
typeOrTypeDict.replace(/ +/, ' ').split(' ').forEach((type) => {
this.draggableTypes[type] = dropDetailsFunc;
});
}
} else if (dropDetailsFunc != null) {
typeOrTypeDict.replace(/ +/, ' ').split(' ').forEach((type) => {
this.draggableTypes[type] = dropDetailsFunc;
});
}
}
@ -542,16 +538,14 @@ export class Tree {
to: dropDetails.length,
},
};
} else {
if (!dropDetails.cur) {
dropDetails = {
...dropDetails,
cur: {
from: dropDetails.text.length,
to: dropDetails.text.length,
},
};
}
} else if (!dropDetails.cur) {
dropDetails = {
...dropDetails,
cur: {
from: dropDetails.text.length,
to: dropDetails.text.length,
},
};
}
e.dataTransfer.setData('text', JSON.stringify(dropDetails));

View File

@ -37,14 +37,10 @@ export function retrieveAncestorOfTypeServer(pgBrowser, item, errorAlertTitle) {
'Databases with = symbols in the name cannot be backed up or restored using this utility.'
)
);
} else {
if (databaseNode.anyParent(isServerNode))
serverInformation = nodeData;
}
} else {
if (treeNode.anyFamilyMember(isServerNode))
} else if (databaseNode.anyParent(isServerNode))
serverInformation = nodeData;
}
} else if (treeNode.anyFamilyMember(isServerNode))
serverInformation = nodeData;
}
if (serverInformation === null) {

View File

@ -556,10 +556,8 @@ export default class DebuggerModule {
pgAdmin.Browser.notifier.alert(gettext('Debugger Error'), error);
}
);
} else {
if (err.success == 0) {
pgAdmin.Browser.notifier.alert(gettext('Debugger Error'), err.errormsg);
}
} else if (err.success == 0) {
pgAdmin.Browser.notifier.alert(gettext('Debugger Error'), err.errormsg);
}
} catch (e) {
console.warn(e.stack || e);

View File

@ -326,17 +326,15 @@ export default function DebuggerArgumentComponent({ debuggerInfo, restartDebug,
'default_value': defValList[i],
'disable_use_default': defValList[i] == DEBUGGER_ARGS.NO_DEFAULT_VALUE,
});
} else {
if (argMode && (argMode[i] == 'i' || argMode[i] == 'b' ||
} else if (argMode && (argMode[i] == 'i' || argMode[i] == 'b' ||
(isEdbProc && argMode[i] == 'o'))) {
myObj.push({
'name': myargname[i],
'type': argType[i],
'use_default': useDefValue,
'default_value': defValList[i],
'disable_use_default': defValList[i] == DEBUGGER_ARGS.NO_DEFAULT_VALUE,
});
}
myObj.push({
'name': myargname[i],
'type': argType[i],
'use_default': useDefValue,
'default_value': defValList[i],
'disable_use_default': defValList[i] == DEBUGGER_ARGS.NO_DEFAULT_VALUE,
});
}
}
return myObj;
@ -528,21 +526,19 @@ export default function DebuggerArgumentComponent({ debuggerInfo, restartDebug,
'type': arg.type,
'value': 'NULL',
});
} else {
} else if (arg.use_default) {
// Check if default value to be used or not
if (arg.use_default) {
argsValueList.push({
'name': arg.name,
'type': arg.type,
'value': arg.default_value,
});
} else {
argsValueList.push({
'name': arg.name,
'type': arg.type,
'value': arg.value,
});
}
argsValueList.push({
'name': arg.name,
'type': arg.type,
'value': arg.default_value,
});
} else {
argsValueList.push({
'name': arg.name,
'type': arg.type,
'value': arg.value,
});
}
}
function getFunctionID(d, treeInfo) {

View File

@ -264,12 +264,10 @@ export class OneToManyLinkWidget extends RightAngleLinkWidget {
} else {
points[i].setPosition(points[i - 1].getX(), points[i].getY());
}
} else if (this.props.link.getLastPathXdirection()) {
points[i - 1].setPosition(points[i - 1].getX(), points[i].getY());
} else {
if (this.props.link.getLastPathXdirection()) {
points[i - 1].setPosition(points[i - 1].getX(), points[i].getY());
} else {
points[i - 1].setPosition(points[i].getX(), points[i - 1].getY());
}
points[i - 1].setPosition(points[i].getX(), points[i - 1].getY());
}
}
}

View File

@ -311,11 +311,8 @@ function expandRows(children, filterParams, tempChild, newRows, rowIndex) {
}
}
else {
if (filterParams.includes(child.status)) {
tempChild.push(child);
}
else if (filterParams.includes(child.status)) {
tempChild.push(child);
}
});
if (tempChild.length > 0) {
@ -548,16 +545,14 @@ export function ResultGridComponent({ gridData, allRowIds, filterParams, selecte
let clsName = null;
if (selectedRowIds.includes(`${row.id}`) || isCellSelected || row.id == activeRowId) {
clsName = isCheckbox ? classes.selectedRowCheckBox : classes.selectedRow;
} else {
if (row.status == FILTER_NAME.DIFFERENT) {
clsName = classes.different;
} else if (row.status == FILTER_NAME.SOURCE_ONLY) {
clsName = classes.source;
} else if (row.status == FILTER_NAME.TARGET_ONLY) {
clsName = classes.target;
} else if (row.status == FILTER_NAME.IDENTICAL) {
clsName = classes.identical;
}
} else if (row.status == FILTER_NAME.DIFFERENT) {
clsName = classes.different;
} else if (row.status == FILTER_NAME.SOURCE_ONLY) {
clsName = classes.source;
} else if (row.status == FILTER_NAME.TARGET_ONLY) {
clsName = classes.target;
} else if (row.status == FILTER_NAME.IDENTICAL) {
clsName = classes.identical;
}
return clsName;

View File

@ -251,9 +251,6 @@ export default function Query() {
eventBus.registerListener(QUERY_TOOL_EVENTS.EDITOR_SET_SQL, (value, focus=true)=>{
focus && editor.current?.focus();
editor.current?.setValue(value, !queryToolCtx.params.is_query_tool);
if (value == '' && editor.current) {
editor.current.state.autoCompleteList = [];
}
});
eventBus.registerListener(QUERY_TOOL_EVENTS.TRIGGER_QUERY_CHANGE, ()=>{
change();

View File

@ -1187,17 +1187,15 @@ export function ResultSet() {
let clientPK = row[rsu.current.clientPK];
if(clientPK in dataChangeStore.deleted) {
remove.push(clientPK);
} else {
} else if(clientPK in dataChangeStore.added) {
/* If deleted from newly added */
if(clientPK in dataChangeStore.added) {
removeNewlyAdded.push(clientPK);
} else {
let primaryKeys = {};
Object.keys(queryData.primary_keys).forEach((k)=>{
primaryKeys[k] = row[k];
});
add[clientPK] = primaryKeys;
}
removeNewlyAdded.push(clientPK);
} else {
let primaryKeys = {};
Object.keys(queryData.primary_keys).forEach((k)=>{
primaryKeys[k] = row[k];
});
add[clientPK] = primaryKeys;
}
}
if(removeNewlyAdded.length > 0) {