Search in sources :

Example 1 with Cursor

use of android.database.Cursor in project persistence by casidiablo.

the class SqliteAdapterImpl method count.

@Override
public <T> int count(Class<T> clazz) {
    Cursor query = SQLHelper.getCursorFindAllWhere(mDbHelper.getDatabase(), clazz, null, null, null, mDatabaseSpec);
    int count = query.getCount();
    query.close();
    return count;
}
Also used : Cursor(android.database.Cursor)

Example 2 with Cursor

use of android.database.Cursor in project persistence by casidiablo.

the class SqliteAdapterImpl method findFirst.

@Override
public <T> T findFirst(T sample) {
    Class<T> clazz = (Class<T>) sample.getClass();
    ArrayList<String> args = new ArrayList<String>();
    String where = SQLHelper.getWhere(clazz, sample, args, null, mDatabaseSpec);
    Cursor query = mDbHelper.getDatabase().query(SQLHelper.getTableName(clazz), null, where, args.toArray(new String[args.size()]), null, null, null, "1");
    return findFirstFromCursor(clazz, query);
}
Also used : ArrayList(java.util.ArrayList) Cursor(android.database.Cursor)

Example 3 with Cursor

use of android.database.Cursor in project persistence by casidiablo.

the class SqliteAdapterImpl method store.

@Override
public <T, G> Object store(T bean, G attachedTo) {
    if (bean == null) {
        return null;
    }
    Class<?> theClass = bean.getClass();
    List<String> transactions = new ArrayList<String>();
    String sqlStatement = getSqlStatement(bean, new Node(theClass), attachedTo);
    if (sqlStatement != null) {
        String[] statements = sqlStatement.split(SQLHelper.STATEMENT_SEPARATOR);
        for (String statement : statements) {
            if (TextUtils.isEmpty(statement)) {
                continue;
            }
            transactions.add(statement);
        }
    }
    executeTransactions(transactions);
    Field idField = SQLHelper.getPrimaryKeyField(theClass);
    // if it is autoincrement, we will try to populate the id field with the inserted id
    if (mDatabaseSpec.isAutoincrement(theClass)) {
        if (idField.getType() != Long.class && idField.getType() != long.class) {
            throw new IllegalStateException("Your primary key is currently '" + idField.getType() + "' but 'long' was expected");
        }
        Cursor lastId = mDbHelper.getDatabase().query("sqlite_sequence", new String[] { "seq" }, "name = ?", new String[] { SQLHelper.getTableName(theClass) }, null, null, null);
        if (lastId != null && lastId.moveToFirst()) {
            long id = lastId.getLong(0);
            lastId.close();
            if (idField != null) {
                idField.setAccessible(true);
                try {
                    idField.set(bean, id);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
            }
            return id;
        } else if (lastId != null) {
            lastId.close();
        }
    } else {
        try {
            idField.setAccessible(true);
            return idField.get(bean);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}
Also used : ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) Field(java.lang.reflect.Field)

Example 4 with Cursor

use of android.database.Cursor in project persistence by casidiablo.

the class SqliteAdapterImpl method delete.

@Override
public <T> int delete(Class<T> theClass, String where, String[] whereArgs, boolean onCascade) {
    DatabaseSpec.Relationship relationship = mDatabaseSpec.getRelationship(theClass);
    if (!relationship.equals(DatabaseSpec.Relationship.UNKNOWN)) {
        Field idField = SQLHelper.getPrimaryKeyField(theClass);
        idField.setAccessible(true);
        switch(relationship) {
            case HAS_MANY:
                if (onCascade) {
                    HasMany hasMany = mDatabaseSpec.has(theClass);
                    List<T> toDelete = findAll(theClass, where, whereArgs);
                    for (T object : toDelete) {
                        try {
                            Object objectId = idField.get(object);
                            Class<?> containedClass = hasMany.getContainedClass();
                            String whereForeign = String.format("%s = '%s'", hasMany.getForeignKey(), String.valueOf(objectId));
                            delete(containedClass, whereForeign, null);
                        } catch (IllegalAccessException ignored) {
                        }
                    }
                }
                break;
            case MANY_TO_MANY:
                List<ManyToMany> manyToManyList = mDatabaseSpec.getManyToMany(theClass);
                for (ManyToMany manyToMany : manyToManyList) {
                    String foreignKey;
                    String foreignCurrentKey;
                    Class<?> relationTable;
                    if (manyToMany.getFirstRelation() == theClass) {
                        foreignKey = manyToMany.getMainKey();
                        foreignCurrentKey = manyToMany.getSecondaryKey();
                        relationTable = manyToMany.getSecondRelation();
                    } else {
                        foreignKey = manyToMany.getSecondaryKey();
                        foreignCurrentKey = manyToMany.getMainKey();
                        relationTable = manyToMany.getFirstRelation();
                    }
                    List<T> toRemove = findAll(theClass, where, whereArgs);
                    for (T object : toRemove) {
                        try {
                            Object objectId = idField.get(object);
                            String whereForeign = String.format("%s = '%s'", foreignKey, String.valueOf(objectId));
                            List<String> ids = new ArrayList<String>();
                            if (onCascade) {
                                Cursor deletionCursor = mDbHelper.getDatabase().query(manyToMany.getTableName(), null, whereForeign, null, null, null, null);
                                if (deletionCursor.moveToFirst()) {
                                    do {
                                        int index = deletionCursor.getColumnIndex(foreignCurrentKey);
                                        ids.add(deletionCursor.getString(index));
                                    } while (deletionCursor.moveToNext());
                                }
                                deletionCursor.close();
                            }
                            mDbHelper.getDatabase().delete(manyToMany.getTableName(), whereForeign, null);
                            for (String id : ids) {
                                String whereRest = String.format("%s = '%s'", foreignCurrentKey, id);
                                Cursor cursorRest = mDbHelper.getDatabase().query(manyToMany.getTableName(), null, whereRest, null, null, null, null);
                                // this means there is no other relation with this object, so we can delete it on cascade :)
                                if (cursorRest.getCount() == 0) {
                                    mDbHelper.getDatabase().delete(SQLHelper.getTableName(relationTable), SQLHelper._ID + " = ?", new String[] { id });
                                }
                            }
                        } catch (IllegalAccessException ignored) {
                        }
                    }
                }
                break;
        }
    }
    return mDbHelper.getDatabase().delete(SQLHelper.getTableName(theClass), where, whereArgs);
}
Also used : ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) Field(java.lang.reflect.Field)

Example 5 with Cursor

use of android.database.Cursor in project persistence by casidiablo.

the class RawQueryTest method findAllByQuery.

@Test
public void findAllByQuery() {
    ExampleAutoincrement foo = new ExampleAutoincrement();
    foo.name = "Foo Bar";
    foo.number = 111;
    foo.decimal = 222f;
    foo.bool = false;
    foo.blob = foo.name.getBytes();
    getAdapter().store(foo);
    foo = new ExampleAutoincrement();
    foo.name = "Bar Foo";
    foo.number = 333;
    foo.decimal = 444f;
    foo.bool = true;
    foo.blob = foo.name.getBytes();
    getAdapter().store(foo);
    RawQuery rawQuery = Persistence.getRawQuery(new Activity());
    ExampleAutoincrement sample = new ExampleAutoincrement();
    sample.bool = true;
    Cursor cursor = rawQuery.findAll(ExampleAutoincrement.class, "bool = 1", null);
    assertNotNull(cursor);
    assertTrue(cursor.moveToFirst());
    assertEquals(2, cursor.getLong(cursor.getColumnIndex("_id")));
    assertEquals(foo.name, cursor.getString(cursor.getColumnIndex("name")));
    assertEquals(foo.number, cursor.getInt(cursor.getColumnIndex("number")));
    assertEquals(foo.decimal, cursor.getFloat(cursor.getColumnIndex("decimal")), 0.0f);
    assertEquals(foo.bool, cursor.getInt(cursor.getColumnIndex("bool")) == 1);
    assertEquals(new String(foo.blob), new String(cursor.getBlob(cursor.getColumnIndex("blob"))));
    Cursor rawCursor = rawQuery.rawQuery("SELECT * FROM automatic WHERE bool = 1");
    assertNotNull(rawCursor);
    assertTrue(rawCursor.moveToFirst());
    assertEquals(2, rawCursor.getLong(rawCursor.getColumnIndex("_id")));
    assertEquals(foo.name, rawCursor.getString(rawCursor.getColumnIndex("name")));
    assertEquals(foo.number, rawCursor.getInt(rawCursor.getColumnIndex("number")));
    assertEquals(foo.decimal, rawCursor.getFloat(rawCursor.getColumnIndex("decimal")), 0.0f);
    assertEquals(foo.bool, rawCursor.getInt(rawCursor.getColumnIndex("bool")) == 1);
    assertEquals(new String(foo.blob), new String(rawCursor.getBlob(rawCursor.getColumnIndex("blob"))));
}
Also used : RawQuery(com.codeslap.persistence.RawQuery) Activity(android.app.Activity) Cursor(android.database.Cursor) Test(org.junit.Test)

Aggregations

Cursor (android.database.Cursor)3795 ArrayList (java.util.ArrayList)522 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)499 Uri (android.net.Uri)455 ContentValues (android.content.ContentValues)300 ContentResolver (android.content.ContentResolver)188 RemoteException (android.os.RemoteException)182 Test (org.junit.Test)172 File (java.io.File)164 IOException (java.io.IOException)156 MatrixCursor (android.database.MatrixCursor)154 Intent (android.content.Intent)119 MediumTest (android.test.suitebuilder.annotation.MediumTest)116 SQLException (android.database.SQLException)115 HashMap (java.util.HashMap)108 SQLiteCursor (android.database.sqlite.SQLiteCursor)88 SQLiteException (android.database.sqlite.SQLiteException)85 Query (android.app.DownloadManager.Query)76 MergeCursor (android.database.MergeCursor)75 LargeTest (android.test.suitebuilder.annotation.LargeTest)69