-
Notifications
You must be signed in to change notification settings - Fork 73
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #217 from Trivadis/feature/issue-213-new-rule-for-…
…loop add G-4387: Never use a FOR LOOP for a query that should return not more than one row.
- Loading branch information
Showing
2 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
58 changes: 58 additions & 0 deletions
58
docs/4-language-usage/4-control-structures/3-flow-control/g-4387.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
# G-4387: Never use a FOR LOOP for a query that should return not more than one row. | ||
|
||
!!! bug "Blocker" | ||
Reliability, Efficiency, Readability | ||
|
||
!!! missing "Unsupported in db\* CODECOP Validators" | ||
Without access to the Oracle Data Dictionary, we cannot determine the number of rows to be processed. | ||
|
||
## Reason | ||
|
||
A `for loop` can hide a `too_many_rows` exception. The more complex a query is, the higher is the risk that more than one row will be processed. | ||
This affects performance and can lead to a wrong result. | ||
|
||
A `for loop` can also hide a `no_data_found` exception and the reader cannot determine whether this is intentional or not. | ||
|
||
## Example (bad) | ||
|
||
``` sql | ||
create or replace package body employee_api is | ||
function emp_name(in_empno in integer) return varchar2 is -- NOSONAR: non-deterministic | ||
l_ename emp.ename%type; | ||
begin | ||
<<fetch_name>> | ||
for r in ( | ||
select ename | ||
from emp | ||
where empno = in_empno | ||
) | ||
loop | ||
l_ename := r.ename; | ||
end loop fetch_name; | ||
return l_ename; | ||
end emp_name; | ||
end employee_api; | ||
/ | ||
``` | ||
|
||
## Example (good) | ||
|
||
``` sql | ||
create or replace package body employee_api is | ||
function emp_name(in_empno in integer) return varchar2 is -- NOSONAR: non-deterministic | ||
l_ename emp.ename%type; | ||
begin | ||
select ename | ||
into l_ename | ||
from emp | ||
where empno >= in_empno; | ||
return l_ename; | ||
exception | ||
when no_data_found then | ||
return null; | ||
when too_many_rows then | ||
raise; | ||
end emp_name; | ||
end employee_api; | ||
/ | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters