Search in sources :

Example 26 with SQLiteQueryBuilder

use of android.database.sqlite.SQLiteQueryBuilder in project mobile-center-sdk-android by Microsoft.

the class DatabaseManager method getCursor.

/**
     * Gets a cursor for all rows in the table, all rows where key matches value if specified.
     *
     * @param key   The optional key for query.
     * @param value The optional value for query.
     * @return A cursor for all rows that matches the given criteria.
     * @throws RuntimeException If an error occurs.
     */
Cursor getCursor(String key, Object value) throws RuntimeException {
    /* Build a query to get values. */
    SQLiteQueryBuilder builder = SQLiteUtils.newSQLiteQueryBuilder();
    builder.setTables(mTable);
    String[] selectionArgs;
    if (key == null)
        selectionArgs = null;
    else if (value == null) {
        builder.appendWhere(key + " IS NULL");
        selectionArgs = null;
    } else {
        builder.appendWhere(key + " = ?");
        selectionArgs = new String[] { String.valueOf(value.toString()) };
    }
    /* Query database. */
    return builder.query(getDatabase(), null, null, selectionArgs, null, null, PRIMARY_KEY);
}
Also used : SQLiteQueryBuilder(android.database.sqlite.SQLiteQueryBuilder)

Example 27 with SQLiteQueryBuilder

use of android.database.sqlite.SQLiteQueryBuilder in project android_frameworks_base by AOSPA.

the class LocalProvider method query.

@Override
public Cursor query(Uri url, String[] projectionIn, String selection, String[] selectionArgs, String sort) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    // Generate the body of the query
    int match = sURLMatcher.match(url);
    switch(match) {
        case DATA:
            qb.setTables("data");
            break;
        case DATA_ID:
            qb.setTables("data");
            qb.appendWhere("_id=");
            qb.appendWhere(url.getPathSegments().get(1));
            break;
        default:
            throw new IllegalArgumentException("Unknown URL " + url);
    }
    SQLiteDatabase db = mOpenHelper.getReadableDatabase();
    Cursor ret = qb.query(db, projectionIn, selection, selectionArgs, null, null, sort);
    if (ret == null) {
        if (false)
            Log.d(TAG, "Alarms.query: failed");
    } else {
        ret.setNotificationUri(getContext().getContentResolver(), url);
    }
    return ret;
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) Cursor(android.database.Cursor) SQLiteQueryBuilder(android.database.sqlite.SQLiteQueryBuilder)

Example 28 with SQLiteQueryBuilder

use of android.database.sqlite.SQLiteQueryBuilder in project mobile-center-sdk-android by Microsoft.

the class DatabaseManagerTest method switchInMemory.

@Test
public void switchInMemory() throws Exception {
    DatabaseManager databaseManagerMock;
    /* Put. */
    databaseManagerMock = getDatabaseManagerMock();
    databaseManagerMock.put(new ContentValues());
    verify(databaseManagerMock).switchToInMemory(eq("put"), any(RuntimeException.class));
    /* Update. */
    databaseManagerMock = getDatabaseManagerMock();
    databaseManagerMock.update(0, new ContentValues());
    verify(databaseManagerMock).switchToInMemory(eq("update"), any(RuntimeException.class));
    /* Get. */
    databaseManagerMock = getDatabaseManagerMock();
    databaseManagerMock.get(0);
    verify(databaseManagerMock).switchToInMemory(eq("get"), any(RuntimeException.class));
    /* Scanner. */
    {
        databaseManagerMock = getDatabaseManagerMock();
        databaseManagerMock.getScanner(null, null).iterator();
        verify(databaseManagerMock).switchToInMemory(eq("scan.iterator"), any(RuntimeException.class));
    }
    {
        databaseManagerMock = getDatabaseManagerMock();
        databaseManagerMock.getScanner(null, null).getCount();
        verify(databaseManagerMock).switchToInMemory(eq("scan.count"), any(RuntimeException.class));
    }
    {
        /* Cursor next failing but closing working. */
        databaseManagerMock = spy(new DatabaseManager(null, "database", "table", 1, null, null));
        when(databaseManagerMock.getDatabase()).thenReturn(mock(SQLiteDatabase.class));
        mockStatic(SQLiteUtils.class);
        Cursor cursor = mock(Cursor.class);
        SQLiteQueryBuilder sqLiteQueryBuilder = mock(SQLiteQueryBuilder.class, new Returns(cursor));
        when(SQLiteUtils.newSQLiteQueryBuilder()).thenReturn(sqLiteQueryBuilder);
        when(cursor.moveToNext()).thenThrow(new RuntimeException());
        DatabaseManager.Scanner scanner = databaseManagerMock.getScanner(null, null);
        assertFalse(scanner.iterator().hasNext());
        verify(databaseManagerMock).switchToInMemory(eq("scan.hasNext"), any(RuntimeException.class));
        /* We switched over in memory so closing will not switch again. Cursor is closed already. */
        doThrow(new RuntimeException()).when(cursor).close();
        scanner.close();
        verify(databaseManagerMock, never()).switchToInMemory(eq("scan.close"), any(RuntimeException.class));
    }
    {
        /* Cursor next failing and closing failing. */
        databaseManagerMock = spy(new DatabaseManager(null, "database", "table", 1, null, null));
        when(databaseManagerMock.getDatabase()).thenReturn(mock(SQLiteDatabase.class));
        mockStatic(SQLiteUtils.class);
        Cursor cursor = mock(Cursor.class);
        SQLiteQueryBuilder sqLiteQueryBuilder = mock(SQLiteQueryBuilder.class, new Returns(cursor));
        when(SQLiteUtils.newSQLiteQueryBuilder()).thenReturn(sqLiteQueryBuilder);
        when(cursor.moveToNext()).thenThrow(new RuntimeException());
        doThrow(new RuntimeException()).when(cursor).close();
        DatabaseManager.Scanner scanner = databaseManagerMock.getScanner(null, null);
        assertFalse(scanner.iterator().hasNext());
        verify(databaseManagerMock).switchToInMemory(eq("scan.hasNext"), any(RuntimeException.class));
        /* We switched over in memory so closing will not switch again. Cursor is closed already in hasNext(). */
        scanner.close();
        verify(databaseManagerMock, never()).switchToInMemory(eq("scan.close"), any(RuntimeException.class));
    }
    {
        /* Cursor closing failing. */
        databaseManagerMock = spy(new DatabaseManager(null, "database", "table", 1, null, null));
        when(databaseManagerMock.getDatabase()).thenReturn(mock(SQLiteDatabase.class));
        mockStatic(SQLiteUtils.class);
        Cursor cursor = mock(Cursor.class);
        SQLiteQueryBuilder sqLiteQueryBuilder = mock(SQLiteQueryBuilder.class, new Returns(cursor));
        when(SQLiteUtils.newSQLiteQueryBuilder()).thenReturn(sqLiteQueryBuilder);
        doThrow(new RuntimeException()).when(cursor).close();
        DatabaseManager.Scanner scanner = databaseManagerMock.getScanner(null, null);
        assertFalse(scanner.iterator().hasNext());
        scanner.close();
        verify(databaseManagerMock).switchToInMemory(eq("scan.close"), any(RuntimeException.class));
    }
    /* Delete. */
    databaseManagerMock = getDatabaseManagerMock();
    databaseManagerMock.delete(0);
    verify(databaseManagerMock).switchToInMemory(eq("delete"), any(RuntimeException.class));
    /* Delete multiple IDs. */
    databaseManagerMock = getDatabaseManagerMock();
    databaseManagerMock.delete(new ArrayList<Long>());
    verify(databaseManagerMock, never()).switchToInMemory(eq("delete"), any(RuntimeException.class));
    databaseManagerMock = getDatabaseManagerMock();
    databaseManagerMock.delete(Arrays.asList(new Long[] { 0L, 1L }));
    verify(databaseManagerMock).switchToInMemory(eq("delete"), any(RuntimeException.class));
    /* Clear. */
    databaseManagerMock = getDatabaseManagerMock();
    databaseManagerMock.clear();
    verify(databaseManagerMock).switchToInMemory(eq("clear"), any(RuntimeException.class));
    /* Close. */
    databaseManagerMock = getDatabaseManagerMock();
    databaseManagerMock.close();
    verify(databaseManagerMock).switchToInMemory(eq("close"), any(RuntimeException.class));
    /* Row count. */
    databaseManagerMock = getDatabaseManagerMock();
    databaseManagerMock.getRowCount();
    verify(databaseManagerMock).switchToInMemory(eq("count"), any(RuntimeException.class));
}
Also used : ContentValues(android.content.ContentValues) Returns(org.mockito.internal.stubbing.answers.Returns) Matchers.anyLong(org.mockito.Matchers.anyLong) Cursor(android.database.Cursor) SQLiteQueryBuilder(android.database.sqlite.SQLiteQueryBuilder) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 29 with SQLiteQueryBuilder

use of android.database.sqlite.SQLiteQueryBuilder in project android_frameworks_base by AOSPA.

the class SyncStorageEngine method readAndDeleteLegacyAccountInfoLocked.

/**
     * Load sync engine state from the old syncmanager database, and then
     * erase it.  Note that we don't deal with pending operations, active
     * sync, or history.
     */
private void readAndDeleteLegacyAccountInfoLocked() {
    // Look for old database to initialize from.
    File file = mContext.getDatabasePath("syncmanager.db");
    if (!file.exists()) {
        return;
    }
    String path = file.getPath();
    SQLiteDatabase db = null;
    try {
        db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLiteException e) {
    }
    if (db != null) {
        final boolean hasType = db.getVersion() >= 11;
        // Copy in all of the status information, as well as accounts.
        if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
            Slog.v(TAG_FILE, "Reading legacy sync accounts db");
        }
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables("stats, status");
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("_id", "status._id as _id");
        map.put("account", "stats.account as account");
        if (hasType) {
            map.put("account_type", "stats.account_type as account_type");
        }
        map.put("authority", "stats.authority as authority");
        map.put("totalElapsedTime", "totalElapsedTime");
        map.put("numSyncs", "numSyncs");
        map.put("numSourceLocal", "numSourceLocal");
        map.put("numSourcePoll", "numSourcePoll");
        map.put("numSourceServer", "numSourceServer");
        map.put("numSourceUser", "numSourceUser");
        map.put("lastSuccessSource", "lastSuccessSource");
        map.put("lastSuccessTime", "lastSuccessTime");
        map.put("lastFailureSource", "lastFailureSource");
        map.put("lastFailureTime", "lastFailureTime");
        map.put("lastFailureMesg", "lastFailureMesg");
        map.put("pending", "pending");
        qb.setProjectionMap(map);
        qb.appendWhere("stats._id = status.stats_id");
        Cursor c = qb.query(db, null, null, null, null, null, null);
        while (c.moveToNext()) {
            String accountName = c.getString(c.getColumnIndex("account"));
            String accountType = hasType ? c.getString(c.getColumnIndex("account_type")) : null;
            if (accountType == null) {
                accountType = "com.google";
            }
            String authorityName = c.getString(c.getColumnIndex("authority"));
            AuthorityInfo authority = this.getOrCreateAuthorityLocked(new EndPoint(new Account(accountName, accountType), authorityName, 0), -1, false);
            if (authority != null) {
                int i = mSyncStatus.size();
                boolean found = false;
                SyncStatusInfo st = null;
                while (i > 0) {
                    i--;
                    st = mSyncStatus.valueAt(i);
                    if (st.authorityId == authority.ident) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    st = new SyncStatusInfo(authority.ident);
                    mSyncStatus.put(authority.ident, st);
                }
                st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
                st.numSyncs = getIntColumn(c, "numSyncs");
                st.numSourceLocal = getIntColumn(c, "numSourceLocal");
                st.numSourcePoll = getIntColumn(c, "numSourcePoll");
                st.numSourceServer = getIntColumn(c, "numSourceServer");
                st.numSourceUser = getIntColumn(c, "numSourceUser");
                st.numSourcePeriodic = 0;
                st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
                st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
                st.lastFailureSource = getIntColumn(c, "lastFailureSource");
                st.lastFailureTime = getLongColumn(c, "lastFailureTime");
                st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
                st.pending = getIntColumn(c, "pending") != 0;
            }
        }
        c.close();
        // Retrieve the settings.
        qb = new SQLiteQueryBuilder();
        qb.setTables("settings");
        c = qb.query(db, null, null, null, null, null, null);
        while (c.moveToNext()) {
            String name = c.getString(c.getColumnIndex("name"));
            String value = c.getString(c.getColumnIndex("value"));
            if (name == null)
                continue;
            if (name.equals("listen_for_tickles")) {
                setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
            } else if (name.startsWith("sync_provider_")) {
                String provider = name.substring("sync_provider_".length(), name.length());
                int i = mAuthorities.size();
                while (i > 0) {
                    i--;
                    AuthorityInfo authority = mAuthorities.valueAt(i);
                    if (authority.target.provider.equals(provider)) {
                        authority.enabled = value == null || Boolean.parseBoolean(value);
                        authority.syncable = 1;
                    }
                }
            }
        }
        c.close();
        db.close();
        (new File(path)).delete();
    }
}
Also used : Account(android.accounts.Account) HashMap(java.util.HashMap) SyncStatusInfo(android.content.SyncStatusInfo) SQLiteException(android.database.sqlite.SQLiteException) Cursor(android.database.Cursor) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) File(java.io.File) SQLiteQueryBuilder(android.database.sqlite.SQLiteQueryBuilder)

Example 30 with SQLiteQueryBuilder

use of android.database.sqlite.SQLiteQueryBuilder in project YourAppIdea by Michenux.

the class AbstractContentProvider method query.

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteDatabase sqlDB = this.sqliteDatabaseFactory.getDatabase();
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
    queryBuilder.setTables(mTableName);
    int uriType = mUriMatcher.match(uri);
    switch(uriType) {
        case LIST:
            break;
        case ITEM_ID:
            // Adding the ID to the original query
            queryBuilder.appendWhere(ID_COLUMN + "=" + uri.getLastPathSegment());
            break;
        default:
            throw new IllegalArgumentException("Unknown URI: " + uri);
    }
    // SQLiteDatabase db = database.getWritableDatabase();
    Cursor cursor = queryBuilder.query(sqlDB, projection, selection, selectionArgs, null, null, sortOrder);
    // Make sure that potential listeners are getting notified
    cursor.setNotificationUri(getContext().getContentResolver(), uri);
    return cursor;
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) Cursor(android.database.Cursor) SQLiteQueryBuilder(android.database.sqlite.SQLiteQueryBuilder)

Aggregations

SQLiteQueryBuilder (android.database.sqlite.SQLiteQueryBuilder)106 Cursor (android.database.Cursor)93 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)44 ContentValues (android.content.ContentValues)8 Account (android.accounts.Account)7 SQLiteException (android.database.sqlite.SQLiteException)7 File (java.io.File)7 HashMap (java.util.HashMap)7 SyncStatusInfo (android.content.SyncStatusInfo)6 MatrixCursor (android.database.MatrixCursor)5 RowBuilder (android.database.MatrixCursor.RowBuilder)5 ContentResolver (android.content.ContentResolver)4 Test (org.junit.Test)2 Matchers.anyLong (org.mockito.Matchers.anyLong)2 Returns (org.mockito.internal.stubbing.answers.Returns)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 AbstractCursor (android.database.AbstractCursor)1 MergeCursor (android.database.MergeCursor)1 AtomicFile (android.util.AtomicFile)1 AtomicFile (com.android.internal.os.AtomicFile)1