Search in sources :

Example 11 with Query

use of com.squareup.sqlbrite3.SqlBrite.Query in project sqlbrite by square.

the class SqlBriteTest method asRowsEmptyWhenNullCursor.

@Test
public void asRowsEmptyWhenNullCursor() {
    Query nully = new Query() {

        @Nullable
        @Override
        public Cursor run() {
            return null;
        }
    };
    final AtomicInteger count = new AtomicInteger();
    nully.asRows(new Function<Cursor, Name>() {

        @Override
        public Name apply(Cursor cursor) throws Exception {
            count.incrementAndGet();
            return Name.MAP.apply(cursor);
        }
    }).test().assertNoValues().assertComplete();
    assertThat(count.get()).isEqualTo(0);
}
Also used : Function(io.reactivex.functions.Function) Query(com.squareup.sqlbrite3.SqlBrite.Query) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MatrixCursor(android.database.MatrixCursor) Cursor(android.database.Cursor) Test(org.junit.Test)

Example 12 with Query

use of com.squareup.sqlbrite3.SqlBrite.Query in project sqlbrite by square.

the class SqlBriteTest method asRows.

@Test
public void asRows() {
    MatrixCursor cursor = new MatrixCursor(COLUMN_NAMES);
    cursor.addRow(new Object[] { "Alice", "Allison" });
    cursor.addRow(new Object[] { "Bob", "Bobberson" });
    Query query = new CursorQuery(cursor);
    List<Name> names = query.asRows(Name.MAP).toList().blockingGet();
    assertThat(names).containsExactly(new Name("Alice", "Allison"), new Name("Bob", "Bobberson"));
}
Also used : Query(com.squareup.sqlbrite3.SqlBrite.Query) MatrixCursor(android.database.MatrixCursor) Test(org.junit.Test)

Example 13 with Query

use of com.squareup.sqlbrite3.SqlBrite.Query in project sqlbrite by square.

the class BriteContentResolver method createQuery.

/**
 * Create an observable which will notify subscribers with a {@linkplain Query query} for
 * execution. Subscribers are responsible for <b>always</b> closing {@link Cursor} instance
 * returned from the {@link Query}.
 * <p>
 * Subscribers will receive an immediate notification for initial data as well as subsequent
 * notifications for when the supplied {@code uri}'s data changes. Unsubscribe when you no longer
 * want updates to a query.
 * <p>
 * Since content resolver triggers are inherently asynchronous, items emitted from the returned
 * observable use the {@link Scheduler} supplied to {@link SqlBrite#wrapContentProvider}. For
 * consistency, the immediate notification sent on subscribe also uses this scheduler. As such,
 * calling {@link Observable#subscribeOn subscribeOn} on the returned observable has no effect.
 * <p>
 * Note: To skip the immediate notification and only receive subsequent notifications when data
 * has changed call {@code skip(1)} on the returned observable.
 * <p>
 * <b>Warning:</b> this method does not perform the query! Only by subscribing to the returned
 * {@link Observable} will the operation occur.
 *
 * @see ContentResolver#query(Uri, String[], String, String[], String)
 * @see ContentResolver#registerContentObserver(Uri, boolean, ContentObserver)
 */
@CheckResult
@NonNull
public QueryObservable createQuery(@NonNull final Uri uri, @Nullable final String[] projection, @Nullable final String selection, @Nullable final String[] selectionArgs, @Nullable final String sortOrder, final boolean notifyForDescendents) {
    final Query query = new Query() {

        @Override
        public Cursor run() {
            long startNanos = nanoTime();
            Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);
            if (logging) {
                long tookMillis = NANOSECONDS.toMillis(nanoTime() - startNanos);
                log("QUERY (%sms)\n  uri: %s\n  projection: %s\n  selection: %s\n  selectionArgs: %s\n  " + "sortOrder: %s\n  notifyForDescendents: %s", tookMillis, uri, Arrays.toString(projection), selection, Arrays.toString(selectionArgs), sortOrder, notifyForDescendents);
            }
            return cursor;
        }
    };
    Observable<Query> queries = Observable.create(new ObservableOnSubscribe<Query>() {

        @Override
        public void subscribe(final ObservableEmitter<Query> e) throws Exception {
            final ContentObserver observer = new ContentObserver(contentObserverHandler) {

                @Override
                public void onChange(boolean selfChange) {
                    if (!e.isDisposed()) {
                        e.onNext(query);
                    }
                }
            };
            contentResolver.registerContentObserver(uri, notifyForDescendents, observer);
            e.setCancellable(new Cancellable() {

                @Override
                public void cancel() throws Exception {
                    contentResolver.unregisterContentObserver(observer);
                }
            });
            if (!e.isDisposed()) {
                // Trigger initial query.
                e.onNext(query);
            }
        }
    });
    return // 
    queries.observeOn(// 
    scheduler).compose(// Apply the user's query transformer.
    queryTransformer).to(QUERY_OBSERVABLE);
}
Also used : Query(com.squareup.sqlbrite3.SqlBrite.Query) Cancellable(io.reactivex.functions.Cancellable) Cursor(android.database.Cursor) ContentObserver(android.database.ContentObserver) CheckResult(android.support.annotation.CheckResult) NonNull(android.support.annotation.NonNull)

Example 14 with Query

use of com.squareup.sqlbrite3.SqlBrite.Query in project sqlbrite by square.

the class QueryObservableTest method mapToListThrowsFromMapFunction.

@Test
public void mapToListThrowsFromMapFunction() {
    Query query = new Query() {

        @Override
        public Cursor run() {
            MatrixCursor cursor = new MatrixCursor(new String[] { "col1" });
            cursor.addRow(new Object[] { "value1" });
            return cursor;
        }
    };
    final IllegalStateException error = new IllegalStateException("test exception");
    // 
    new QueryObservable(Observable.just(query)).mapToList(new Function<Cursor, Object>() {

        @Override
        public Object apply(Cursor cursor) {
            throw error;
        }
    }).test().assertNoValues().assertError(error);
}
Also used : Function(io.reactivex.functions.Function) Query(com.squareup.sqlbrite3.SqlBrite.Query) QueryObservable(com.squareup.sqlbrite3.QueryObservable) MatrixCursor(android.database.MatrixCursor) Cursor(android.database.Cursor) MatrixCursor(android.database.MatrixCursor) Test(org.junit.Test)

Example 15 with Query

use of com.squareup.sqlbrite3.SqlBrite.Query in project sqlbrite by square.

the class BriteDatabaseTest method transactionCreatedFromTransactionNotificationWorks.

@Test
public void transactionCreatedFromTransactionNotificationWorks() {
    // Tests the case where a transaction is created in the subscriber to a query which gets
    // notified as the result of another transaction being committed. With improper ordering, this
    // can result in creating a new transaction before the old is committed on the underlying DB.
    db.createQuery(TABLE_EMPLOYEE, SELECT_EMPLOYEES).subscribe(new Consumer<Query>() {

        @Override
        public void accept(Query query) {
            db.newTransaction().end();
        }
    });
    Transaction transaction = db.newTransaction();
    try {
        db.insert(TABLE_EMPLOYEE, CONFLICT_NONE, employee("john", "John Johnson"));
        transaction.markSuccessful();
    } finally {
        transaction.end();
    }
}
Also used : Query(com.squareup.sqlbrite3.SqlBrite.Query) SimpleSQLiteQuery(android.arch.persistence.db.SimpleSQLiteQuery) Transaction(com.squareup.sqlbrite3.BriteDatabase.Transaction) Test(org.junit.Test)

Aggregations

Query (com.squareup.sqlbrite3.SqlBrite.Query)15 Test (org.junit.Test)14 Cursor (android.database.Cursor)6 MatrixCursor (android.database.MatrixCursor)6 Transaction (com.squareup.sqlbrite3.BriteDatabase.Transaction)4 SimpleSQLiteQuery (android.arch.persistence.db.SimpleSQLiteQuery)3 Employee (com.squareup.sqlbrite3.TestDb.Employee)3 Function (io.reactivex.functions.Function)3 TestObserver (io.reactivex.observers.TestObserver)3 SdkSuppress (android.support.test.filters.SdkSuppress)2 QueryObservable (com.squareup.sqlbrite3.QueryObservable)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 TargetApi (android.annotation.TargetApi)1 SupportSQLiteOpenHelper (android.arch.persistence.db.SupportSQLiteOpenHelper)1 Configuration (android.arch.persistence.db.SupportSQLiteOpenHelper.Configuration)1 Factory (android.arch.persistence.db.SupportSQLiteOpenHelper.Factory)1 FrameworkSQLiteOpenHelperFactory (android.arch.persistence.db.framework.FrameworkSQLiteOpenHelperFactory)1 ContentObserver (android.database.ContentObserver)1 CheckResult (android.support.annotation.CheckResult)1