ronantakizawa/codereview-bench huggingface dataset:
Repository: hasura/graphql-engine
File: console/src/components/Services/ApiExplorer/Analyzer/QueryAnalyzer.js (JavaScript)

Code before:
    Modal.setAppElement('body');
    this.state = {
      analyseData: [],
      activeNode: 0,
    };
  }
  modifyResponse = data => {
    // analyze on subscriptions returns an object
    if (!Array.isArray(data)) {
      return [data];
    }

    return data;
  };
  componentDidMount() {
    this.props
      .analyzeFetcher(this.props.analyseQuery.query)
      .then(r => {
        if (r.ok) {
          return r.json();
        }
        return r.text().then(rText => Promise.reject(new Error(rText)));
      })
      .then(data => {
        this.setState({
          analyseData: this.modifyResponse(data),
          activeNode: 0,
        });
      })
      .catch(e => {
        alert(`Unable to fetch: ${e.message}.`);
        this.props.clearAnalyse();
      });
  }
  renderAnalysisList() {
    return this.state.analyseData.map((analysis, i) => {
      if (analysis.hasOwnProperty('field')) {
        return (
          <li
            className={i === this.state.activeNode ? 'active' : ''}
            key={i}
            data-key={i}
            onClick={this.handleAnalyseNodeChange.bind(this)}
          >
            {console.log(analysis)}
            <i className="fa fa-table" aria-hidden="true" />
            {analysis.field}
          </li>
        );
      }
    });

Review comment (suggestion):
Let's inline it
```suggestion
          analyseData: Array.isArray(data) ? data : [data],
```

Code after:
    super();
    Modal.setAppElement('body');
    this.state = {
      analyseData: [],
      activeNode: 0,
    };
  }

  componentDidMount() {
    this.props
      .analyzeFetcher(this.props.analyseQuery.query)
      .then(r => {
        if (r.ok) {
          return r.json();
        }
        return r.text().then(rText => Promise.reject(new Error(rText)));
      })
      .then(data => {
        this.setState({
          analyseData: Array.isArray(data) ? data : [data],
          activeNode: 0,
        });
      })
      .catch(e => {
        alert(`Unable to fetch: ${e.message}.`);
        this.props.clearAnalyse();
      });
  }
  render() {
    const { show, clearAnalyse } = this.props;
    return (
      <Modal
        className="modalWrapper"
        overlayClassName="myOverlayClass"
        isOpen={show && this.state.analyseData.length > 0}
      >
        <div className="modalHeader">
          <div className="modalTitle">Query Analysis</div>
          <div className="modalClose">
            <button onClick={clearAnalyse} className="form-control">
              x
            </button>
          </div>
        </div>
        <div className="modalBody">
          <div className="wd25">
            <div className="topLevelNodesWrapper">
              <div className="title">Top level nodes</div>
              <RootFields
                data={this.state.analyseData}
                activeNode={this.state.activeNode}
Repository: hasura/graphql-engine
File: console/src/components/Services/ApiExplorer/Analyzer/RootFields.tsx (TypeScript)

Code before:
import React from 'react';

type ExplainPayload = {
  field: string;
  sql: string;
  plan: string[];
};

type RootFieldsProps = {
  data: ExplainPayload[];
  activeNode: number;
  onClick: (e: React.MouseEvent<HTMLLIElement>) => void;
};

const AnalyzeText: React.FC<RootFieldsProps> = ({
  data,
  activeNode,
  onClick,
}) => (
  <ul>
    {data.map((analysis, i) => {
      return (
        analysis.field && (
          // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
          <li
            className={i === activeNode ? 'active' : ''}
            key={i}
            data-key={i}
            onClick={onClick}
          >
            <i className="fa fa-table" aria-hidden="true" />
            {analysis.field}
          </li>
        )
      );
    })}
  </ul>
);

export default AnalyzeText;

Review comment (suggestion):
```suggestion
const RootFields: React.FC<RootFieldsProps> = ({
```

Code after:
import React from 'react';

type ExplainPayload = {
  field: string;
  sql: string;
  plan: string[];
};

type RootFieldsProps = {
  data: ExplainPayload[];
  activeNode: number;
  onClick: (e: React.MouseEvent<HTMLLIElement>) => void;
};

const RootFields: React.FC<RootFieldsProps> = ({
  data,
  activeNode,
  onClick,
}) => (
  <ul>
    {data.map((analysis, i) => {
      return (
        analysis.field && (
          // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
          <li
            className={i === activeNode ? 'active' : ''}
            key={i}
            data-key={i}
            onClick={onClick}
          >
            <i className="fa fa-table" aria-hidden="true" />
            {analysis.field}
          </li>
        )
      );
    })}
  </ul>
);

export default RootFields;
Repository: hasura/graphql-engine
File: console/src/components/Main/utils.ts (TypeScript)

Code before:
export const bootIntercom = () => {
  if (!window.Intercom) return;
  window.Intercom!('boot', {
    app_id: INTERCOM_ID,
  });
};

export const closeIntercom = () => {
  if (window.Intercom) window.Intercom('shutdown');
};

export const startIntercom = () => {
  if (window.Intercom) bootIntercom();

  const head = document.getElementsByTagName('head')[0];
  const script = document.createElement('script');
  script.type = 'text/javascript';
  script.onload = bootIntercom;
  script.src = INTERCOM_URL;
  head.appendChild(script);
};

const chatState = 'console:chatEnabled';

export const persistChatState = (isEnabled: boolean) => {
  window.localStorage.setItem(chatState, String(isEnabled));
};

export const getPersistedChatState = () => {
  const state = window.localStorage.getItem(chatState);
  try {
    if (state) {
      return JSON.parse(state);
    }
    return false;
  } catch {
    return false;
  }
};

const loveConsentState = 'console:loveIcon';
const proClickState = 'console:pro';
const defaultState = {
  isDismissed: false,
};
const defaultProClickState = {
  isProClicked: false,
};

const setLoveConsentState = (stateData: { isDismissed: boolean }) => {
  window.localStorage.setItem(loveConsentState, JSON.stringify(stateData));

Review comment (refactor):
we have a utility for this `getLocalStorageItem`, we can re-use if you want, do as you wish :see_no_evil:

Code after:
  isDismissed: false,
};
const defaultProClickState = {
  isProClicked: false,
};

const setLoveConsentState = (stateData: { isDismissed: boolean }) => {
  window.localStorage.setItem(loveConsentState, JSON.stringify(stateData));
};

const getLoveConsentState = () => {
  const s = window.localStorage.getItem(loveConsentState);

  if (s) {
    return JSON.parse(s);
  }

  window.localStorage.setItem(loveConsentState, JSON.stringify(defaultState));

  return defaultState;
};

const setProClickState = (proStateData: { isProClicked: boolean }) => {
  window.localStorage.setItem(proClickState, JSON.stringify(proStateData));
};

const getProClickState = () => {
  try {
    const p = window.localStorage.getItem(proClickState);

    if (p) {
      return JSON.parse(p);
    }

    window.localStorage.setItem(
      proClickState,
      JSON.stringify(defaultProClickState)
    );

    return defaultProClickState;
  } catch (e) {
    console.error(e);
    return defaultProClickState;
  }
};

export {
  getLoveConsentState,
  setLoveConsentState,
  getProClickState,
  setProClickState,
Repository: hasura/graphql-engine
File: cli/migrate/database/hasuradb/metadata.go (Go)

Code before:
func (h *HasuraDB) DropInconsistentMetadata() error {
	query := HasuraInterfaceQuery{
		Type: "drop_inconsistent_metadata",
		Args: HasuraArgs{},
	}

	resp, body, err := h.sendv1Query(query)
	if err != nil {
		h.logger.Debug(err)
		return err
	}
	h.logger.Debug("response: ", string(body))

	if resp.StatusCode != http.StatusOK {
		return NewHasuraError(body, h.config.isCMD)
	}
	return nil
}

func (h *HasuraDB) BuildMetadata() (yaml.MapSlice, error) {
	var tmpMeta yaml.MapSlice
	for _, plg := range h.config.Plugins {
		err := plg.Build(&tmpMeta)
		if err != nil {
			if os.IsNotExist(errors.Cause(err)) {
				h.logger.Debugf("metadata file for %s was not found, assuming an empty files", plg.Name())
				continue
			}
			return tmpMeta, errors.Wrap(err, fmt.Sprintf("cannot build %s from metadata", plg.Name()))
		}
	}
	return tmpMeta, nil
}

func (h *HasuraDB) ApplyMetadata() error {
	tmpMeta, err := h.BuildMetadata()
	if err != nil {
		return err
	}
	yByt, err := yaml.Marshal(tmpMeta)
	if err != nil {
		return err
	}
	jbyt, err := gyaml.YAMLToJSON(yByt)
	if err != nil {
		return err
	}
	var obj interface{}
	err = json.Unmarshal(jbyt, &obj)
	if err != nil {
		return err

Review comment (bug):
```suggestion
				h.logger.Debugf("metadata file for %s was not found, assuming an empty file", plg.Name())
```

Code after:
func (h *HasuraDB) DropInconsistentMetadata() error {
	query := HasuraInterfaceQuery{
		Type: "drop_inconsistent_metadata",
		Args: HasuraArgs{},
	}

	resp, body, err := h.sendv1Query(query)
	if err != nil {
		h.logger.Debug(err)
		return err
	}
	h.logger.Debug("response: ", string(body))

	if resp.StatusCode != http.StatusOK {
		return NewHasuraError(body, h.config.isCMD)
	}
	return nil
}

func (h *HasuraDB) BuildMetadata() (yaml.MapSlice, error) {
	var tmpMeta yaml.MapSlice
	for _, plg := range h.config.Plugins {
		err := plg.Build(&tmpMeta)
		if err != nil {
			if os.IsNotExist(errors.Cause(err)) {
				h.logger.Debugf("metadata file for %s was not found, assuming an empty file", plg.Name())
				continue
			}
			return tmpMeta, errors.Wrap(err, fmt.Sprintf("cannot build %s from metadata", plg.Name()))
		}
	}
	return tmpMeta, nil
}

func (h *HasuraDB) ApplyMetadata() error {
	tmpMeta, err := h.BuildMetadata()
	if err != nil {
		return err
	}
	yByt, err := yaml.Marshal(tmpMeta)
	if err != nil {
		return err
	}
	jbyt, err := gyaml.YAMLToJSON(yByt)
	if err != nil {
		return err
	}
	var obj interface{}
	err = json.Unmarshal(jbyt, &obj)
	if err != nil {
		return err
Repository: hasura/graphql-engine
File: console/src/components/Services/Events/AdhocEvents/PendingEvents/PendingEvents.tsx (TypeScript)

Code before:
} from '../../../../Common/FilterQuery/types';
import { adhocEventsTable } from '../utils';
import EventsTable from '../../Common/Components/EventsTable';
import { makeOrderBy } from '../../../../Common/utils/v1QueryUtils';
import { Dispatch } from '../../../../../types';
import { cancelEvent } from '../../ServerIO';
import {
  getConfirmation,
  convertDateTimeToLocale,
} from '../../../../Common/utils/jsUtils';

type Props = {
  dispatch: Dispatch;
};

const PendingEvents: React.FC<Props> = props => {
  const { dispatch } = props;

  const onCancelOneOffScheduledEvent = (
    id: string,
    scheduledAt: string,
    onSuccess: () => void
  ) => {
    const localeTime = convertDateTimeToLocale(scheduledAt);
    const shouldCancelEvent = getConfirmation(
      `This will delete the one-off event ${id} scheduled for ${localeTime}`
    );
    if (shouldCancelEvent) {
      dispatch(
        cancelEvent('one-off scheduled', 'hdb_scheduled_events', id, onSuccess)
      );
    }
  };

  const renderRows: FilterRenderProp = (
    rows,
    count,
    filterState,
    setFilterState,
    runQuery
  ) => (
    <EventsTable
      rows={rows}
      count={count}
      filterState={filterState}
      setFilterState={setFilterState}
      runQuery={runQuery}
      columns={[
        'actions',
        'id',
        'status',

Review comment (suggestion):
```suggestion
      `This will delete the one-off event "${id}" scheduled for "${localeTime}"`
```

Code after:
} from '../../../../Common/FilterQuery/types';
import { adhocEventsTable } from '../utils';
import EventsTable from '../../Common/Components/EventsTable';
import { makeOrderBy } from '../../../../Common/utils/v1QueryUtils';
import { Dispatch } from '../../../../../types';
import { cancelEvent } from '../../ServerIO';
import {
  getConfirmation,
  convertDateTimeToLocale,
} from '../../../../Common/utils/jsUtils';

type Props = {
  dispatch: Dispatch;
};

const PendingEvents: React.FC<Props> = props => {
  const { dispatch } = props;

  const onCancelOneOffScheduledEvent = (
    id: string,
    scheduledAt: string,
    onSuccess: () => void
  ) => {
    const localeTime = convertDateTimeToLocale(scheduledAt);
    const shouldCancelEvent = getConfirmation(
      `This will delete the one-off event "${id}" scheduled for "${localeTime}"`
    );
    if (shouldCancelEvent) {
      dispatch(
        cancelEvent('one-off scheduled', 'hdb_scheduled_events', id, onSuccess)
      );
    }
  };

  const renderRows: FilterRenderProp = (
    rows,
    count,
    filterState,
    setFilterState,
    runQuery
  ) => (
    <EventsTable
      rows={rows}
      count={count}
      filterState={filterState}
      setFilterState={setFilterState}
      runQuery={runQuery}
      columns={[
        'actions',
        'id',
        'status',
Repository: hasura/graphql-engine
File: console/src/components/Services/Events/CronTriggers/PendingEvents/PendingEvents.tsx (TypeScript)

Code before:
import { Dispatch } from '../../../../../types';
import EventsTable from '../../Common/Components/EventsTable';
import { makeOrderBy } from '../../../../Common/utils/v1QueryUtils';
import { cancelEvent } from '../../ServerIO';
import {
  getConfirmation,
  convertDateTimeToLocale,
} from '../../../../Common/utils/jsUtils';

type Props = {
  currentTrigger?: ScheduledTrigger;
  dispatch: Dispatch;
};

const PendingEvents: React.FC<Props> = props => {
  const { dispatch, currentTrigger } = props;
  const triggerName = currentTrigger ? currentTrigger.name : '';

  const onCancelCronTrigger = (
    id: string,
    scheduledAt: string,
    onSuccess: () => void
  ) => {
    const localeTime = convertDateTimeToLocale(scheduledAt);
    const shouldCancelEvent = getConfirmation(
      `This will delete the ${triggerName} cron event ${id} scheduled for ${localeTime}`
    );
    if (shouldCancelEvent) {
      dispatch(cancelEvent('cron', 'hdb_cron_events', id, onSuccess));
    }
  };

  const renderRows: FilterRenderProp = (
    rows,
    count,
    filterState,
    setFilterState,
    runQuery
  ) => (
    <EventsTable
      rows={rows}
      count={count}
      filterState={filterState}
      setFilterState={setFilterState}
      runQuery={runQuery}
      columns={[
        'actions',
        'id',
        'status',
        'scheduled_time',
        'created_at',

Review comment (suggestion):
```suggestion
      `This will delete the "${triggerName}" cron event "${id}" scheduled for "${localeTime}"`
```

Code after:
import { Dispatch } from '../../../../../types';
import EventsTable from '../../Common/Components/EventsTable';
import { makeOrderBy } from '../../../../Common/utils/v1QueryUtils';
import { cancelEvent } from '../../ServerIO';
import {
  getConfirmation,
  convertDateTimeToLocale,
} from '../../../../Common/utils/jsUtils';

type Props = {
  currentTrigger?: ScheduledTrigger;
  dispatch: Dispatch;
};

const PendingEvents: React.FC<Props> = props => {
  const { dispatch, currentTrigger } = props;
  const triggerName = currentTrigger ? currentTrigger.name : '';

  const onCancelCronTrigger = (
    id: string,
    scheduledAt: string,
    onSuccess: () => void
  ) => {
    const localeTime = convertDateTimeToLocale(scheduledAt);
    const shouldCancelEvent = getConfirmation(
      `This will delete the "${triggerName}" cron event "${id}" scheduled for "${localeTime}"`
    );
    if (shouldCancelEvent) {
      dispatch(cancelEvent('cron', 'hdb_cron_events', id, onSuccess));
    }
  };

  const renderRows: FilterRenderProp = (
    rows,
    count,
    filterState,
    setFilterState,
    runQuery
  ) => (
    <EventsTable
      rows={rows}
      count={count}
      filterState={filterState}
      setFilterState={setFilterState}
      runQuery={runQuery}
      columns={[
        'actions',
        'id',
        'status',
        'scheduled_time',
        'created_at',
Repository: hasura/graphql-engine
File: console/src/components/Services/Data/utils.js (JavaScript)

Code before:
          ...i.args,
          ...(isPgCascade && { sql: cascadePGSqlQuery(i.args.sql) }),
          cascade: true,
        },
      };
    }
    return i;
  });

export const getDependencyError = (err = {}) => {
  const dflt = {};
  if (err.code == ERROR_CODES.dependencyError.code) {
    // direct dependency error
    return { dependencyError: err };
  } else if (err.code == ERROR_CODES.dataApiError.code) {
    // message is coming as error, further parssing willbe based on message key
    const actualError = isJsonString(err.message)
      ? JSON.parse(err.message)
      : {};
    if (actualError.code == ERROR_CODES.dependencyError.code)
      return {
        dependencyError: { ...actualError, message: actualError.error },
      };
    else if (
      actualError.code === ERROR_CODES.postgresError.code &&
      actualError?.internal?.error?.status_code === '2BP01' // pg dependent error > https://www.postgresql.org/docs/12/errcodes-appendix.html
    )
      return {
        pgDependencyError: { ...actualError, message: actualError.error },
      };
  }
  return dflt;
};


Review comment (suggestion):
```suggestion
      actualError?.internal?.error?.status_code === '2BP01' // pg dependent error > https://www.postgresql.org/docs/current/errcodes-appendix.html
```

Code after:
      return {
        ...i,
        args: {
          ...i.args,
          ...(isPgCascade && { sql: cascadePGSqlQuery(i.args.sql) }),
          cascade: true,
        },
      };
    }
    return i;
  });

export const getDependencyError = (err = {}) => {
  if (err.code == ERROR_CODES.dependencyError.code) {
    // direct dependency error
    return { dependencyError: err };
  }
  if (err.code == ERROR_CODES.dataApiError.code) {
    // with CLI mode, error is getting as a string with the key `message`
    err = isJsonString(err.message) ? JSON.parse(err.message) : {};
  }

  if (err.code == ERROR_CODES.dependencyError.code)
    return {
      dependencyError: { ...err, message: err.error },
    };
  if (
    err.code === ERROR_CODES.postgresError.code &&
    err?.internal?.error?.status_code === '2BP01' // pg dependent error > https://www.postgresql.org/docs/current/errcodes-appendix.html
  )
    return {
      pgDependencyError: {
        ...err,
        message: `${err?.internal?.error?.message}:\n
         ${err?.internal?.error?.description || ''}`,
      },
    };
  return {};
};
Repository: hasura/graphql-engine
File: console/src/components/Services/Data/TableBrowseRows/ViewActions.js (JavaScript)

Code before:
      }
    );
  };
};

const vMakeCountRequest = () => {
  return (dispatch, getState) => {
    const {
      currentTable: originalTable,
      currentSchema,
      view,
    } = getState().tables;
    const url = Endpoints.query;

    const selectQuery = getSelectQuery(
      'count',
      generateTableDef(originalTable, currentSchema),
      view.query.columns,
      view.query.where,
      view.query.offset,
      view.query.limit,
      view.query.order_by
    );

    const timeoutQuery = getRunSqlQuery(
      getStatementTimeoutSql(2) + `select pg_sleep(5)`
    );

    const requestBody = {
      type: 'bulk',
      args: [timeoutQuery, selectQuery],
    };

    const options = {
      method: 'POST',
      body: JSON.stringify(requestBody),
      headers: dataHeaders(getState),
      credentials: globalCookiePolicy,
    };

    return dispatch(requestAction(url, options)).then(
      data => {
        if (data.length > 1) {
          const currentTable = getState().tables.currentTable;

          // in case table has changed before count load
          if (currentTable === originalTable) {
            dispatch({
              type: V_COUNT_REQUEST_SUCCESS,
              count: data[1].count,
            });

Review comment (suggestion):
```suggestion
      getStatementTimeoutSql(2)
```

Code after:
      }
    );
  };
};

const vMakeCountRequest = () => {
  return (dispatch, getState) => {
    const {
      currentTable: originalTable,
      currentSchema,
      view,
    } = getState().tables;
    const url = Endpoints.query;

    const selectQuery = getSelectQuery(
      'count',
      generateTableDef(originalTable, currentSchema),
      view.query.columns,
      view.query.where,
      view.query.offset,
      view.query.limit,
      view.query.order_by
    );

    const timeoutQuery = getRunSqlQuery(getStatementTimeoutSql(2));

    const requestBody = {
      type: 'bulk',
      args: [timeoutQuery, selectQuery],
    };

    const options = {
      method: 'POST',
      body: JSON.stringify(requestBody),
      headers: dataHeaders(getState),
      credentials: globalCookiePolicy,
    };

    return dispatch(requestAction(url, options)).then(
      data => {
        if (data.length > 1) {
          const currentTable = getState().tables.currentTable;

          // in case table has changed before count load
          if (currentTable === originalTable) {
            dispatch({
              type: V_COUNT_REQUEST_SUCCESS,
              count: data[1].count,
            });
          }
        }
Repository: hasura/graphql-engine
File: console/src/components/Services/Data/Common/Components/TableRow.tsx (TypeScript)

Code before:
  prevValue?: unknown,
  clone?: Record<string, unknown>
) => {
  const isEditing = prevValue !== undefined;

  const hasDefault = col.column_default
    ? col.column_default.trim() !== ''
    : false;

  const isAutoIncrement = !!isColumnAutoIncrement(col);
  const isIdentity = col.is_identity ? col.is_identity !== 'NO' : false;
  const isGenerated = col.is_generated ? col.is_generated !== 'NEVER' : false;
  const isNullable = col.is_nullable ? col.is_nullable !== 'NO' : false;
  const identityGeneration = col.identity_generation;

  const isDisabled = isAutoIncrement || isGenerated || isIdentity;

  let columnValueType;
  switch (true) {
    case clone &&
      clone[col.column_name] &&
      !isDisabled &&
      !['uuid', 'timestamptz'].includes(col.udt_name):
      columnValueType = 'value';
      break;
    case !isEditing && (isIdentity || hasDefault || isGenerated):
    case identityGeneration === 'ALWAYS':
      columnValueType = 'default';
      break;

    case prevValue === null:
    case !prevValue && isNullable:
      columnValueType = 'null';
      break;
    default:
      columnValueType = 'value';
      break;
  }

  return {
    colName: col.column_name,
    isDisabled,
    isNullable,
    hasDefault,
    isIdentity,
    isGenerated,
    identityGeneration,
    columnValueType,
  };
};


Review comment (refactor):
We can simplify it.
Instead of adding another `case` we can handle it along with the first case as:
```
case !isEditing && !clone && (isIdentity || hasDefault || isGenerated):
```
Notice added `!clone` part.

Code after:
  prevValue?: unknown,
  clone?: Record<string, unknown>
) => {
  const isEditing = prevValue !== undefined;

  const hasDefault = col.column_default
    ? col.column_default.trim() !== ''
    : false;

  const isAutoIncrement = !!isColumnAutoIncrement(col);
  const isIdentity = col.is_identity ? col.is_identity !== 'NO' : false;
  const isGenerated = col.is_generated ? col.is_generated !== 'NEVER' : false;
  const isNullable = col.is_nullable ? col.is_nullable !== 'NO' : false;
  const identityGeneration = col.identity_generation;

  const isDisabled = isAutoIncrement || isGenerated || isIdentity;

  let columnValueType;
  switch (true) {
    case !isEditing && !clone && (isIdentity || hasDefault || isGenerated):
    case clone && isDisabled:
    case identityGeneration === 'ALWAYS':
      columnValueType = 'default';
      break;

    case prevValue === null:
    case !prevValue && isNullable:
      columnValueType = 'null';
      break;
    default:
      columnValueType = 'value';
      break;
  }

  return {
    colName: col.column_name,
    isDisabled,
    isNullable,
    hasDefault,
    isIdentity,
    isGenerated,
    identityGeneration,
    columnValueType,
  };
};

export interface TableRowProps {
  column: TableColumn;
  setRef: (
    refName: 'valueNode' | 'nullNode' | 'defaultNode' | 'insertRadioNode',
    node: HTMLInputElement | null