aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteCursor.java
blob: 84431491ec0d3bc4479596ff6f756a00020288f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package com.xtremelabs.robolectric.shadows;

import android.database.sqlite.SQLiteCursor;
import com.xtremelabs.robolectric.internal.Implementation;
import com.xtremelabs.robolectric.internal.Implements;

import java.sql.Clob;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 * Simulates an Android Cursor object, by wrapping a JDBC ResultSet.
 */
@Implements(SQLiteCursor.class)
public class ShadowSQLiteCursor extends ShadowAbstractCursor {

    private ResultSet resultSet;
    
    
    /**
     * Stores the column names so they are retrievable after the resultSet has closed
     */
    private void cacheColumnNames(ResultSet rs) {
    	try {
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();    
            columnNameArray = new String[columnCount];
            for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
                String cName = metaData.getColumnName(columnIndex).toLowerCase();
                this.columnNames.put(cName, columnIndex-1);
                this.columnNameArray[columnIndex-1]=cName;
            }
        } catch (SQLException e) {
            throw new RuntimeException("SQL exception in cacheColumnNames", e);
        }
    }
    
   

  
    private Integer getColIndex(String columnName) {
        if (columnName == null) {
            return -1;
        }
        
        Integer i  = this.columnNames.get(columnName.toLowerCase());
        if (i==null) return -1;
        return i;
    }
    
    @Implementation
    public int getColumnIndex(String columnName) {
    	return getColIndex(columnName);
    }

    @Implementation
    public int getColumnIndexOrThrow(String columnName) {
    	Integer columnIndex = getColIndex(columnName);
        if (columnIndex == -1) {
            throw new IllegalArgumentException("Column index does not exist");
        }
        return columnIndex;
    }

    @Implementation
    @Override
    public final boolean moveToLast() {
        return super.moveToLast();
    }
    
    @Implementation
    @Override
    public final boolean moveToFirst() {
        return super.moveToFirst();
    }

    @Implementation
    @Override
    public boolean moveToNext() {
        return super.moveToNext();
    }
    
    @Implementation
    @Override
    public boolean moveToPrevious() {
        return super.moveToPrevious();
    }
    
    @Implementation
    @Override
    public boolean moveToPosition(int pos) {
    	return super.moveToPosition(pos);
    }

    @Implementation
    public byte[] getBlob(int columnIndex) {
    	checkPosition();
        return (byte[]) this.currentRow.get(getColumnNames()[columnIndex]);
    }

    @Implementation
    public String getString(int columnIndex) {
        checkPosition();
        Object value = this.currentRow.get(getColumnNames()[columnIndex]);
        if (value instanceof Clob) {
            try {
                return ((Clob) value).getSubString(1, (int)((Clob) value).length());
            } catch (SQLException x) {
                throw new RuntimeException(x);
            }
        } else {
            return (String)value;
        }
    }
	
	@Implementation
	public short getShort(int columnIndex) {
		checkPosition();
		Object o =this.currentRow.get(getColumnNames()[columnIndex]);
    	if (o==null) return 0;
        return new Short(o.toString());
	}
	
    @Implementation
    public int getInt(int columnIndex) {
    	checkPosition();
    	Object o =this.currentRow.get(getColumnNames()[columnIndex]);
    	if (o==null) return 0;
        return new Integer(o.toString());
    }

    @Implementation
    public long getLong(int columnIndex) {
    	checkPosition();
    	Object o =this.currentRow.get(getColumnNames()[columnIndex]);
    	if (o==null) return 0;
        return new Long(o.toString());
    }

    @Implementation
    public float getFloat(int columnIndex) {
    	checkPosition();
    	Object o =this.currentRow.get(getColumnNames()[columnIndex]);
    	if (o==null) return 0;
        return new Float(o.toString());
        
    }

    @Implementation
    public double getDouble(int columnIndex) {
    	checkPosition();
    	Object o =this.currentRow.get(getColumnNames()[columnIndex]);
    	if (o==null) return 0;
    	return new Double(o.toString());
    }
    
    private void checkPosition() {
        if (-1 == currentRowNumber || getCount() == currentRowNumber) {      
            throw new IndexOutOfBoundsException(currentRowNumber + " " + getCount());
        }
    }

    @Implementation
    public void close() {
        if (resultSet == null) {
            return;
        }

        try {
            resultSet.close();
            resultSet = null;
            rows = null;
            currentRow = null;
        } catch (SQLException e) {
            throw new RuntimeException("SQL exception in close", e);
        }
    }

    @Implementation
    public boolean isClosed() {
        return (resultSet == null);
    }

    @Implementation
    public boolean isNull(int columnIndex) {
        Object o = this.currentRow.get(getColumnNames()[columnIndex]);
        return o == null;
    }

    /**
     * Allows test cases access to the underlying JDBC ResultSet, for use in
     * assertions.
     *
     * @return the result set
     */
    public ResultSet getResultSet() {
        return resultSet;
    }
    
    /**
     * Allows test cases access to the underlying JDBC ResultSetMetaData, for use in
     * assertions. Available even if cl
     *
     * @return the result set
     */
    public ResultSet getResultSetMetaData() {
        return resultSet;
    }    
    
    /**
     * loads a row's values
     * @param rs
     * @return
     * @throws SQLException
     */
    private Map<String,Object> fillRowValues(ResultSet rs) throws SQLException {
    	Map<String,Object> row = new HashMap<String,Object>();
    	for (String s : getColumnNames()) {
			  row.put(s, rs.getObject(s));
    	}
    	return row;
    }
    private void fillRows(String sql, Connection connection) throws SQLException {
    	//ResultSets in SQLite\Android are only TYPE_FORWARD_ONLY. Android caches results in the WindowedCursor to allow moveToPrevious() to function.
    	//Robolectric will have to cache the results too. In the rows map.
    	Statement statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        ResultSet rs = statement.executeQuery(sql);
        int count = 0;
        if (rs.next()) {  
        	     do {
        	    	Map<String,Object> row = fillRowValues(rs);
         	    	rows.put(count, row);
        	    	count++;
        	     } while (rs.next());  
        	 } else {  
        		 rs.close(); 
        	 } 
        
        rowCount = count;
        
    }
    
    public void setResultSet(ResultSet result, String sql) {
        this.resultSet = result;
        rowCount = 0;

        //Cache all rows.  Caching rows should be thought of as a simple replacement for ShadowCursorWindow
        if (resultSet != null) {
        	cacheColumnNames(resultSet);
        	try {
        		fillRows(sql, result.getStatement().getConnection());
			} catch (SQLException e) {
			    throw new RuntimeException("SQL exception in setResultSet", e);
			}
        }
    }
}