aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteStatement.java
blob: 2bbdce66ebdb3064b7b40dcd66af4109410bdf3e (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
package com.xtremelabs.robolectric.shadows;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDoneException;
import android.database.sqlite.SQLiteStatement;
import com.xtremelabs.robolectric.internal.Implementation;
import com.xtremelabs.robolectric.internal.Implements;

import java.sql.ResultSet;
import java.sql.SQLException;

@Implements(SQLiteStatement.class)
public class ShadowSQLiteStatement extends ShadowSQLiteProgram {
    String mSql;

    public void init(SQLiteDatabase db, String sql) {
        super.init(db, sql);
        mSql = sql;
    }

    @Implementation
    public void execute() {
        if (!mDatabase.isOpen()) {
            throw new IllegalStateException("database " + mDatabase.getPath() + " already closed");
        }
        try {
            actualDBstatement.execute();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Implementation
    public long executeInsert() {
        try {
            actualDBstatement.executeUpdate();
            ResultSet resultSet = actualDBstatement.getGeneratedKeys();

            if (resultSet.next()) {
                return resultSet.getLong(1);
            } else {
                throw new RuntimeException("Could not retrive generatedKeys");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Implementation
    public long simpleQueryForLong() {
        ResultSet rs;
        try {
            rs = actualDBstatement.executeQuery();
            rs.next();
            return rs.getLong(1);
        } catch (SQLException e) {
             handleException(e);
             throw new RuntimeException(e);
        }
    }

    @Implementation
    public String simpleQueryForString() {
        ResultSet rs;
        try {
            rs = actualDBstatement.executeQuery();
            rs.next();
            return rs.getString(1);
        } catch (SQLException e) {
            handleException(e);
            throw new RuntimeException(e);
        }
    }
    
    private void handleException(SQLException e)  {
        if (e.getMessage().contains("No data is available")) {
            //if the query returns zero rows
            throw new SQLiteDoneException("No data is available");
        } else if (e.getMessage().contains("ResultSet closed")) {
            //if the query returns zero rows (SQLiteMap)
            throw new SQLiteDoneException("ResultSet closed,(probably, no data available)");
        } 
    }
}