openrewrite / openrewrite/rewrite

ForLoopIncrementInUpdate should refrain from moving increment to the update part of the for in case the variable is incremented multiple times

Open
#3,675 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
Java
Stars
3.7k
Forks
570
Avg merge
13h 12m
Merged PRs (30d)
261

Description

What problem are you trying to solve?

I want to keep the code reasonable, and ForLoopIncrementInUpdate produces suboptimal results.

Describe the solution you'd like

PreparedStatement ps
...
      // Multi values(),(),() case
      for (int i = 0; i < p1nrows; ) {
        for (int k = 0, pos = 1; k < p2multi; k++, i++) {
          ps.setInt(pos, i);
          pos++;
          ps.setString(pos, strings[i]);
          pos++;
          ps.setInt(pos, i);
          pos++;
        }
        ps.addBatch();
      }

Unfortunately, ForLoopIncrementInUpdate moves the last increment of pos to the for which makes the code awkward:

      for (int i = 0; i < p1nrows; ) {
        for (int k = 0, pos = 1; k < p2multi; k++, pos++, i++) { // <-- pos++ is weird here
          ps.setInt(pos, i);
          pos++;
          ps.setString(pos, strings[i]);
          pos++;
          ps.setInt(pos, i);
        }
        ps.addBatch();
      }

I think it would be reasonable if ForLoopIncrementInUpdate does not touch variables that are incremented several times in the loop body.

Have you considered any alternatives or workarounds?

THere's an option to ignore and accept the change.

Additional context

https://github.com/pgjdbc/pgjdbc/pull/2979

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating the ForLoopIncrementInUpdate recipe and inspect how it identifies increments moved into a for-loop update clause. Use the provided nested-loop example as the reproduction case. Done means variables incremented multiple times in the loop body are left in the body, while eligible increments still behave as before; add or run the relevant recipe tests once located.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.