Skip to content

Commit

Permalink
Added 'affectData' attribute to SELECT statements
Browse files Browse the repository at this point in the history
To indicate the SELECT affects DB data.
e.g. PostgreSQL's RETURNING, MS SQL Server's OUTPUT
  • Loading branch information
harawata committed Nov 19, 2022
1 parent eccb9c6 commit 52fd6eb
Show file tree
Hide file tree
Showing 12 changed files with 112 additions and 11 deletions.
9 changes: 9 additions & 0 deletions src/main/java/org/apache/ibatis/annotations/Select.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,15 @@
*/
String databaseId() default "";

/**
* Returns whether this select affects DB data.<br>
* e.g. RETURNING of PostgreSQL or OUTPUT of MS SQL Server.
*
* @return {@code true} if this select affects DB data; {@code false} if otherwise
* @since 3.5.12
*/
boolean affectData() default false;

/**
* The container annotation for {@link Select}.
* @author Kazuki Shimizu
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,15 @@
*/
String databaseId() default "";

/**
* Returns whether this select affects DB data.<br>
* e.g. RETURNING of PostgreSQL or OUTPUT of MS SQL Server.
*
* @return {@code true} if this select affects DB data; {@code false} if otherwise
* @since 3.5.12
*/
boolean affectData() default false;

/**
* The container annotation for {@link SelectProvider}.
* @author Kazuki Shimizu
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,8 @@ public MappedStatement addMappedStatement(
String keyColumn,
String databaseId,
LanguageDriver lang,
String resultSets) {
String resultSets,
boolean dirtySelect) {

if (unresolvedCacheRef) {
throw new IncompleteElementException("Cache-ref not yet resolved");
Expand All @@ -285,7 +286,8 @@ public MappedStatement addMappedStatement(
.resultSetType(resultSetType)
.flushCacheRequired(flushCache)
.useCache(useCache)
.cache(currentCache);
.cache(currentCache)
.dirtySelect(dirtySelect);

ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);
if (statementParameterMap != null) {
Expand Down Expand Up @@ -344,12 +346,24 @@ public MappedStatement addMappedStatement(String id, SqlSource sqlSource, Statem
SqlCommandType sqlCommandType, Integer fetchSize, Integer timeout, String parameterMap, Class<?> parameterType,
String resultMap, Class<?> resultType, ResultSetType resultSetType, boolean flushCache, boolean useCache,
boolean resultOrdered, KeyGenerator keyGenerator, String keyProperty, String keyColumn, String databaseId,
LanguageDriver lang) {
LanguageDriver lang, String resultSets) {
return addMappedStatement(
id, sqlSource, statementType, sqlCommandType, fetchSize, timeout,
parameterMap, parameterType, resultMap, resultType, resultSetType,
flushCache, useCache, resultOrdered, keyGenerator, keyProperty,
keyColumn, databaseId, lang, null);
keyColumn, databaseId, lang, null, false);
}

public MappedStatement addMappedStatement(String id, SqlSource sqlSource, StatementType statementType,
SqlCommandType sqlCommandType, Integer fetchSize, Integer timeout, String parameterMap, Class<?> parameterType,
String resultMap, Class<?> resultType, ResultSetType resultSetType, boolean flushCache, boolean useCache,
boolean resultOrdered, KeyGenerator keyGenerator, String keyProperty, String keyColumn, String databaseId,
LanguageDriver lang) {
return addMappedStatement(
id, sqlSource, statementType, sqlCommandType, fetchSize, timeout,
parameterMap, parameterType, resultMap, resultType, resultSetType,
flushCache, useCache, resultOrdered, keyGenerator, keyProperty,
keyColumn, databaseId, lang, null);
}

private <T> T valueOrDefault(T value, T defaultValue) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,8 @@ void parseStatement(Method method) {
statementAnnotation.getDatabaseId(),
languageDriver,
// ResultSets
options != null ? nullOrEmpty(options.resultSets()) : null);
options != null ? nullOrEmpty(options.resultSets()) : null,
statementAnnotation.isDirtySelect());
});
}

Expand Down Expand Up @@ -604,7 +605,7 @@ private KeyGenerator handleSelectKeyAnnotation(SelectKey selectKeyAnnotation, St

assistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass, resultSetTypeEnum,
flushCache, useCache, false,
keyGenerator, keyProperty, keyColumn, databaseId, languageDriver, null);
keyGenerator, keyProperty, keyColumn, databaseId, languageDriver, null, false);

id = assistant.applyCurrentNamespace(id, false);

Expand Down Expand Up @@ -672,13 +673,15 @@ private class AnnotationWrapper {
private final Annotation annotation;
private final String databaseId;
private final SqlCommandType sqlCommandType;
private boolean dirtySelect;

AnnotationWrapper(Annotation annotation) {
super();
this.annotation = annotation;
if (annotation instanceof Select) {
databaseId = ((Select) annotation).databaseId();
sqlCommandType = SqlCommandType.SELECT;
dirtySelect = ((Select) annotation).affectData();
} else if (annotation instanceof Update) {
databaseId = ((Update) annotation).databaseId();
sqlCommandType = SqlCommandType.UPDATE;
Expand All @@ -691,6 +694,7 @@ private class AnnotationWrapper {
} else if (annotation instanceof SelectProvider) {
databaseId = ((SelectProvider) annotation).databaseId();
sqlCommandType = SqlCommandType.SELECT;
dirtySelect = ((SelectProvider) annotation).affectData();
} else if (annotation instanceof UpdateProvider) {
databaseId = ((UpdateProvider) annotation).databaseId();
sqlCommandType = SqlCommandType.UPDATE;
Expand Down Expand Up @@ -723,5 +727,9 @@ SqlCommandType getSqlCommandType() {
String getDatabaseId() {
return databaseId;
}

boolean isDirtySelect() {
return dirtySelect;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,12 @@ public void parseStatementNode() {
String keyProperty = context.getStringAttribute("keyProperty");
String keyColumn = context.getStringAttribute("keyColumn");
String resultSets = context.getStringAttribute("resultSets");
boolean dirtySelect = context.getBooleanAttribute("affectData", Boolean.FALSE);

builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets, dirtySelect);
}

private void processSelectKeyNodes(String id, Class<?> parameterTypeClass, LanguageDriver langDriver) {
Expand Down Expand Up @@ -160,7 +161,7 @@ private void parseSelectKeyNode(String id, XNode nodeToHandle, Class<?> paramete
builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
resultSetTypeEnum, flushCache, useCache, resultOrdered,
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, null);
keyGenerator, keyProperty, keyColumn, databaseId, langDriver, null, false);

id = builderAssistant.applyCurrentNamespace(id, false);

Expand Down
10 changes: 10 additions & 0 deletions src/main/java/org/apache/ibatis/mapping/MappedStatement.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ public final class MappedStatement {
private Log statementLog;
private LanguageDriver lang;
private String[] resultSets;
private boolean dirtySelect;

MappedStatement() {
// constructor disabled
Expand Down Expand Up @@ -174,6 +175,11 @@ public Builder resultSets(String resultSet) {
return this;
}

public Builder dirtySelect(boolean dirtySelect) {
mappedStatement.dirtySelect = dirtySelect;
return this;
}

/**
* Resul sets.
*
Expand Down Expand Up @@ -290,6 +296,10 @@ public String[] getResultSets() {
return resultSets;
}

public boolean isDirtySelect() {
return dirtySelect;
}

/**
* Gets the resul sets.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ public <E> List<E> selectList(String statement, Object parameter, RowBounds rowB
private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
dirty |= ms.isDirtySelect();
return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ databaseId CDATA #IMPLIED
lang CDATA #IMPLIED
resultOrdered (true|false) #IMPLIED
resultSets CDATA #IMPLIED
affectData (true|false) #IMPLIED
>

<!ELEMENT insert (#PCDATA | selectKey | include | trim | where | set | foreach | choose | if | bind)*>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,27 @@ void shouldRollbackIfCalled_Provider() {
}
}

@Test
void shouldNonDirtySelectNotUnsetDirtyFlag() {
Integer id;
try (SqlSession sqlSession = sqlSessionFactory.openSession(false)) {
Mapper mapper = sqlSession.getMapper(Mapper.class);
// INSERT
User user = new User();
user.setName("Bobby");
mapper.insert(user);
id = user.getId();
assertNotNull(id);
assertEquals("Bobby", user.getName());
// Non-dirty SELECT
mapper.selectById(id);
sqlSession.rollback();
}
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
Mapper mapper = sqlSession.getMapper(Mapper.class);
User user = mapper.selectById(id);
assertNull(user);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
*/
package org.apache.ibatis.submitted.dirty_select;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;

Expand All @@ -23,14 +25,18 @@ public interface Mapper {
@Select("select * from users where id = #{id}")
User selectById(Integer id);

@Select(value = "insert into users (name) values (#{name}) returning id, name")
@Select(value = "insert into users (name) values (#{name}) returning id, name", affectData = true)
User insertReturn(String name);

User insertReturnXml(String name);

@SelectProvider(type = MyProvider.class, method = "getSql")
@SelectProvider(type = MyProvider.class, method = "getSql", affectData = true)
User insertReturnProvider(String name);

@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
@Insert("insert into users (name) values (#{name}) returning id, name")
int insert(User user);

static class MyProvider {
public static String getSql() {
return "insert into users (name) values (#{name}) returning id, name";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
-- limitations under the License.
--

drop table if exists users;

create table users (
id serial primary key,
name varchar(30)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2009-2022 the original author or authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
namespace="org.apache.ibatis.submitted.dirty_select.Mapper">

<select id="insertReturnXml"
<select id="insertReturnXml" affectData="true"
resultType="org.apache.ibatis.submitted.dirty_select.User">
insert into users (name) values (#{name})
returning id, name
Expand Down

0 comments on commit 52fd6eb

Please sign in to comment.