View Javadoc
1   /*
2    *    Copyright 2009-2021 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       http://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.apache.ibatis.cursor.defaults;
17  
18  import static org.junit.jupiter.api.Assertions.assertEquals;
19  import static org.junit.jupiter.api.Assertions.assertFalse;
20  import static org.junit.jupiter.api.Assertions.assertTrue;
21  import static org.mockito.Mockito.doReturn;
22  import static org.mockito.Mockito.when;
23  
24  import java.sql.ResultSet;
25  import java.sql.ResultSetMetaData;
26  import java.sql.SQLException;
27  import java.sql.Types;
28  import java.util.ArrayList;
29  import java.util.HashMap;
30  import java.util.Iterator;
31  import java.util.List;
32  import java.util.Map;
33  
34  import org.apache.ibatis.builder.StaticSqlSource;
35  import org.apache.ibatis.executor.Executor;
36  import org.apache.ibatis.executor.parameter.ParameterHandler;
37  import org.apache.ibatis.executor.resultset.DefaultResultSetHandler;
38  import org.apache.ibatis.executor.resultset.ResultSetWrapper;
39  import org.apache.ibatis.mapping.BoundSql;
40  import org.apache.ibatis.mapping.MappedStatement;
41  import org.apache.ibatis.mapping.ResultMap;
42  import org.apache.ibatis.mapping.ResultMapping;
43  import org.apache.ibatis.mapping.SqlCommandType;
44  import org.apache.ibatis.session.Configuration;
45  import org.apache.ibatis.session.ResultHandler;
46  import org.apache.ibatis.session.RowBounds;
47  import org.apache.ibatis.type.TypeHandlerRegistry;
48  import org.junit.jupiter.api.Test;
49  import org.junit.jupiter.api.extension.ExtendWith;
50  import org.mockito.Mock;
51  import org.mockito.Spy;
52  import org.mockito.junit.jupiter.MockitoExtension;
53  
54  @ExtendWith(MockitoExtension.class)
55  class DefaultCursorTest {
56    @Spy
57    private ImpatientResultSet rs;
58    @Mock
59    protected ResultSetMetaData rsmd;
60  
61    @SuppressWarnings("unchecked")
62    @Test
63    void shouldCloseImmediatelyIfResultSetIsClosed() throws Exception {
64      final MappedStatement ms = getNestedAndOrderedMappedStatement();
65      final ResultMap rm = ms.getResultMaps().get(0);
66  
67      final Executor executor = null;
68      final ParameterHandler parameterHandler = null;
69      final ResultHandler<?> resultHandler = null;
70      final BoundSql boundSql = null;
71      final RowBounds rowBounds = RowBounds.DEFAULT;
72  
73      final DefaultResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, ms, parameterHandler,
74        resultHandler, boundSql, rowBounds);
75  
76  
77      when(rsmd.getColumnCount()).thenReturn(2);
78      doReturn("id").when(rsmd).getColumnLabel(1);
79      doReturn(Types.INTEGER).when(rsmd).getColumnType(1);
80      doReturn(Integer.class.getCanonicalName()).when(rsmd).getColumnClassName(1);
81      doReturn("role").when(rsmd).getColumnLabel(2);
82      doReturn(Types.VARCHAR).when(rsmd).getColumnType(2);
83      doReturn(String.class.getCanonicalName()).when(rsmd).getColumnClassName(2);
84  
85      final ResultSetWrapper rsw = new ResultSetWrapper(rs, ms.getConfiguration());
86  
87      try (DefaultCursor<?> cursor = new DefaultCursor<>(resultSetHandler, rm, rsw, RowBounds.DEFAULT)) {
88        Iterator<?> iter = cursor.iterator();
89        assertTrue(iter.hasNext());
90        Map<String, Object> map = (Map<String, Object>) iter.next();
91        assertEquals(1, map.get("id"));
92        assertEquals("CEO", ((Map<String, Object>) map.get("roles")).get("role"));
93  
94        assertFalse(cursor.isConsumed());
95        assertTrue(cursor.isOpen());
96  
97        assertFalse(iter.hasNext());
98        assertTrue(cursor.isConsumed());
99        assertFalse(cursor.isOpen());
100     }
101   }
102 
103   @SuppressWarnings("serial")
104   private MappedStatement getNestedAndOrderedMappedStatement() {
105     final Configuration config = new Configuration();
106     final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
107 
108     ResultMap nestedResultMap = new ResultMap.Builder(config, "roleMap", HashMap.class,
109       new ArrayList<ResultMapping>() {
110         {
111           add(new ResultMapping.Builder(config, "role", "role", registry.getTypeHandler(String.class))
112             .build());
113         }
114       }).build();
115     config.addResultMap(nestedResultMap);
116 
117     return new MappedStatement.Builder(config, "selectPerson", new StaticSqlSource(config, "select person..."),
118       SqlCommandType.SELECT).resultMaps(
119         new ArrayList<ResultMap>() {
120           {
121             add(new ResultMap.Builder(config, "personMap", HashMap.class, new ArrayList<ResultMapping>() {
122               {
123                 add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(Integer.class))
124                   .build());
125                 add(new ResultMapping.Builder(config, "roles").nestedResultMapId("roleMap").build());
126               }
127             }).build());
128           }
129         })
130         .resultOrdered(true)
131         .build();
132   }
133 
134   /*
135    * Simulate a driver that closes ResultSet automatically when next() returns false (e.g. DB2).
136    */
137   protected abstract class ImpatientResultSet implements ResultSet {
138     private int rowIndex = -1;
139     private List<Map<String, Object>> rows = new ArrayList<>();
140 
141     protected ImpatientResultSet() {
142       Map<String, Object> row = new HashMap<>();
143       row.put("id", 1);
144       row.put("role", "CEO");
145       rows.add(row);
146     }
147 
148     @Override
149     public boolean next() throws SQLException {
150       throwIfClosed();
151       return ++rowIndex < rows.size();
152     }
153 
154     @Override
155     public boolean isClosed() {
156       return rowIndex >= rows.size();
157     }
158 
159     @Override
160     public String getString(String columnLabel) throws SQLException {
161       throwIfClosed();
162       return (String) rows.get(rowIndex).get(columnLabel);
163     }
164 
165     @Override
166     public int getInt(String columnLabel) throws SQLException {
167       throwIfClosed();
168       return (Integer) rows.get(rowIndex).get(columnLabel);
169     }
170 
171     @Override
172     public boolean wasNull() throws SQLException {
173       throwIfClosed();
174       return false;
175     }
176 
177     @Override
178     public ResultSetMetaData getMetaData() {
179       return rsmd;
180     }
181 
182     @Override
183     public int getType() throws SQLException {
184       throwIfClosed();
185       return ResultSet.TYPE_FORWARD_ONLY;
186     }
187 
188     private void throwIfClosed() throws SQLException {
189       if (rowIndex >= rows.size()) {
190         throw new SQLException("Invalid operation: result set is closed.");
191       }
192     }
193   }
194 }