1 package com.xtremelabs.robolectric.shadows;
2 
3 import android.database.sqlite.SQLiteDatabase;
4 import android.database.sqlite.SQLiteDoneException;
5 import android.database.sqlite.SQLiteStatement;
6 import com.xtremelabs.robolectric.internal.Implementation;
7 import com.xtremelabs.robolectric.internal.Implements;
8 
9 import java.sql.ResultSet;
10 import java.sql.SQLException;
11 
12 @Implements(SQLiteStatement.class)
13 public class ShadowSQLiteStatement extends ShadowSQLiteProgram {
14     String mSql;
15 
init(SQLiteDatabase db, String sql)16     public void init(SQLiteDatabase db, String sql) {
17         super.init(db, sql);
18         mSql = sql;
19     }
20 
21     @Implementation
execute()22     public void execute() {
23         if (!mDatabase.isOpen()) {
24             throw new IllegalStateException("database " + mDatabase.getPath() + " already closed");
25         }
26         try {
27             actualDBstatement.execute();
28         } catch (SQLException e) {
29             throw new RuntimeException(e);
30         }
31     }
32 
33     @Implementation
executeInsert()34     public long executeInsert() {
35         try {
36             actualDBstatement.executeUpdate();
37             ResultSet resultSet = actualDBstatement.getGeneratedKeys();
38 
39             if (resultSet.next()) {
40                 return resultSet.getLong(1);
41             } else {
42                 throw new RuntimeException("Could not retrive generatedKeys");
43             }
44         } catch (SQLException e) {
45             throw new RuntimeException(e);
46         }
47     }
48 
49     @Implementation
simpleQueryForLong()50     public long simpleQueryForLong() {
51         ResultSet rs;
52         try {
53             rs = actualDBstatement.executeQuery();
54             rs.next();
55             return rs.getLong(1);
56         } catch (SQLException e) {
57              handleException(e);
58              throw new RuntimeException(e);
59         }
60     }
61 
62     @Implementation
simpleQueryForString()63     public String simpleQueryForString() {
64         ResultSet rs;
65         try {
66             rs = actualDBstatement.executeQuery();
67             rs.next();
68             return rs.getString(1);
69         } catch (SQLException e) {
70             handleException(e);
71             throw new RuntimeException(e);
72         }
73     }
74 
handleException(SQLException e)75     private void handleException(SQLException e)  {
76         if (e.getMessage().contains("No data is available")) {
77             //if the query returns zero rows
78             throw new SQLiteDoneException("No data is available");
79         } else if (e.getMessage().contains("ResultSet closed")) {
80             //if the query returns zero rows (SQLiteMap)
81             throw new SQLiteDoneException("ResultSet closed,(probably, no data available)");
82         }
83     }
84 }