RoomDatabase

public abstract class RoomDatabase


Base class for all Room databases. All classes that are annotated with Database must extend this class.

RoomDatabase provides direct access to the underlying database implementation but you should prefer using Dao classes.

See also
Database

Summary

Nested types

public class RoomDatabase.Builder<T extends RoomDatabase>

Builder for RoomDatabase.

public abstract class RoomDatabase.Callback

Callback for RoomDatabase.

public enum RoomDatabase.JournalMode extends Enum

Journal modes for SQLite database.

A container to hold migrations.

Callback for Builder.createFromAsset, Builder.createFromFile and Builder.createFromInputStream

public fun interface RoomDatabase.QueryCallback

Callback interface for when SQLite queries are executed.

Protected fields

volatile final SupportSQLiteDatabase

This field is deprecated. Will be hidden in the next release.

Public constructors

You cannot create an instance of a database, instead, you should acquire it via #Room.databaseBuilder or #Room.inMemoryDatabaseBuilder.

Public methods

void

This method is deprecated. beginTransaction() is deprecated

abstract void

Deletes all rows from all the tables that are registered to this database as Database.entities.

void

Closes the database if it is already open.

@NonNull SupportSQLiteStatement

Wrapper for SupportSQLiteDatabase.compileStatement.

void

This method is deprecated. endTransaction() is deprecated

@NonNull InvalidationTracker

The invalidation tracker for this database.

@NonNull SupportSQLiteOpenHelper

The SQLite open helper used by this database.

@NonNull Executor

The Executor in use by this database for async queries.

@NonNull Executor

The Executor in use by this database for async transactions.

T
<T extends Object> getTypeConverter(@NonNull Class<@NonNull T> klass)

Gets the instance of the given Type Converter.

boolean

Returns true if current thread is in a transaction.

void

Called by Room when it is initialized.

boolean

True if database connection is open and initialized.

@NonNull Cursor
query(@NonNull String query, Object[] args)

Convenience method to query the database with arguments.

@NonNull Cursor

Wrapper for SupportSQLiteDatabase.query.

@NonNull V
<V extends Object> runInTransaction(@NonNull Callable<@NonNull V> body)

Executes the specified Callable in a database transaction.

void

Executes the specified Runnable in a database transaction.

void

This method is deprecated. setTransactionSuccessful() is deprecated

Protected methods

abstract @NonNull InvalidationTracker

Called when the RoomDatabase is created.

abstract @NonNull SupportSQLiteOpenHelper

Creates the open helper to access the database.

void

Called by the generated code when database is open.

Extension functions

final @NonNull Flow<@NonNull Set<@NonNull String>>
RoomDatabaseKt.invalidationTrackerFlow(
    @NonNull RoomDatabase receiver,
    @NonNull String tables,
    boolean emitInitialState
)

Creates a Flow that listens for changes in the database via the InvalidationTracker and emits sets of the tables that were invalidated.

Protected fields

mDatabase

Added in 2.0.0
Deprecated in 2.1.0
volatile protected final SupportSQLiteDatabase mDatabase

Set by the generated open helper.

Public constructors

RoomDatabase

Added in 2.0.0
public RoomDatabase()

You cannot create an instance of a database, instead, you should acquire it via #Room.databaseBuilder or #Room.inMemoryDatabaseBuilder.

Public methods

beginTransaction

Added in 2.0.0
Deprecated in 2.1.0
public void beginTransaction()

Wrapper for SupportSQLiteDatabase.beginTransaction.

clearAllTables

Added in 2.0.0
@WorkerThread
public abstract void clearAllTables()

Deletes all rows from all the tables that are registered to this database as Database.entities.

This does NOT reset the auto-increment value generated by PrimaryKey.autoGenerate.

After deleting the rows, Room will set a WAL checkpoint and run VACUUM. This means that the data is completely erased. The space will be reclaimed by the system if the amount surpasses the threshold of database file size.

See SQLite documentation for details. FileFormat

close

Added in 2.0.0
public void close()

Closes the database if it is already open.

compileStatement

Added in 2.0.0
public @NonNull SupportSQLiteStatement compileStatement(@NonNull String sql)

Wrapper for SupportSQLiteDatabase.compileStatement.

Parameters
@NonNull String sql

The query to compile.

Returns
@NonNull SupportSQLiteStatement

The compiled query.

endTransaction

Added in 2.0.0
Deprecated in 2.1.0
public void endTransaction()

Wrapper for SupportSQLiteDatabase.endTransaction.

getInvalidationTracker

Added in 2.0.0
public @NonNull InvalidationTracker getInvalidationTracker()

The invalidation tracker for this database.

You can use the invalidation tracker to get notified when certain tables in the database are modified.

Returns
@NonNull InvalidationTracker

The invalidation tracker for the database.

getOpenHelper

Added in 2.0.0
public @NonNull SupportSQLiteOpenHelper getOpenHelper()

The SQLite open helper used by this database.

getQueryExecutor

Added in 2.0.0
public @NonNull Executor getQueryExecutor()

The Executor in use by this database for async queries.

getTransactionExecutor

Added in 2.1.0
public @NonNull Executor getTransactionExecutor()

The Executor in use by this database for async transactions.

getTypeConverter

Added in 2.3.0
public T <T extends Object> getTypeConverter(@NonNull Class<@NonNull T> klass)

Gets the instance of the given Type Converter.

Parameters
<T extends Object>

The type of the expected Type Converter subclass.

@NonNull Class<@NonNull T> klass

The Type Converter class.

Returns
T

An instance of T if it is provided in the builder.

inTransaction

Added in 2.0.0
public boolean inTransaction()

Returns true if current thread is in a transaction.

Returns
boolean

True if there is an active transaction in current thread, false otherwise.

See also
inTransaction

init

Added in 2.0.0
@CallSuper
public void init(@NonNull DatabaseConfiguration configuration)

Called by Room when it is initialized.

Parameters
@NonNull DatabaseConfiguration configuration

The database configuration.

Throws
kotlin.IllegalArgumentException

if initialization fails.

isOpen

Added in 2.0.0
public boolean isOpen()

True if database connection is open and initialized.

When Room is configured with RoomDatabase.Builder.setAutoCloseTimeout the database is considered open even if internally the connection has been closed, unless manually closed.

Returns
boolean

true if the database connection is open, false otherwise.

query

Added in 2.0.0
public @NonNull Cursor query(@NonNull String query, Object[] args)

Convenience method to query the database with arguments.

Parameters
@NonNull String query

The sql query

Object[] args

The bind arguments for the placeholders in the query

Returns
@NonNull Cursor

A Cursor obtained by running the given query in the Room database.

query

Added in 2.2.0
public @NonNull Cursor query(@NonNull SupportSQLiteQuery query, CancellationSignal signal)

Wrapper for SupportSQLiteDatabase.query.

Parameters
@NonNull SupportSQLiteQuery query

The Query which includes the SQL and a bind callback for bind arguments.

CancellationSignal signal

The cancellation signal to be attached to the query.

Returns
@NonNull Cursor

Result of the query.

runInTransaction

Added in 2.0.0
public @NonNull V <V extends Object> runInTransaction(@NonNull Callable<@NonNull V> body)

Executes the specified Callable in a database transaction. The transaction will be marked as successful unless an exception is thrown in the Callable.

Room will only perform at most one transaction at a time.

Parameters
<V extends Object>

The type of the return value.

@NonNull Callable<@NonNull V> body

The piece of code to execute.

Returns
@NonNull V

The value returned from the Callable.

runInTransaction

Added in 2.0.0
public void runInTransaction(@NonNull Runnable body)

Executes the specified Runnable in a database transaction. The transaction will be marked as successful unless an exception is thrown in the Runnable.

Room will only perform at most one transaction at a time.

Parameters
@NonNull Runnable body

The piece of code to execute.

setTransactionSuccessful

Added in 2.0.0
Deprecated in 2.1.0
public void setTransactionSuccessful()

Wrapper for SupportSQLiteDatabase.setTransactionSuccessful.

Protected methods

createInvalidationTracker

Added in 2.0.0
protected abstract @NonNull InvalidationTracker createInvalidationTracker()

Called when the RoomDatabase is created.

This is already implemented by the generated code.

Returns
@NonNull InvalidationTracker

Creates a new InvalidationTracker.

createOpenHelper

Added in 2.0.0
protected abstract @NonNull SupportSQLiteOpenHelper createOpenHelper(@NonNull DatabaseConfiguration config)

Creates the open helper to access the database. Generated class already implements this method. Note that this method is called when the RoomDatabase is initialized.

Parameters
@NonNull DatabaseConfiguration config

The configuration of the Room database.

Returns
@NonNull SupportSQLiteOpenHelper

A new SupportSQLiteOpenHelper to be used while connecting to the database.

internalInitInvalidationTracker

Added in 2.0.0
protected void internalInitInvalidationTracker(@NonNull SupportSQLiteDatabase db)

Called by the generated code when database is open.

You should never call this method manually.

Parameters
@NonNull SupportSQLiteDatabase db

The database instance.

Extension functions

RoomDatabaseKt.invalidationTrackerFlow

public final @NonNull Flow<@NonNull Set<@NonNull String>> RoomDatabaseKt.invalidationTrackerFlow(
    @NonNull RoomDatabase receiver,
    @NonNull String tables,
    boolean emitInitialState
)

Creates a Flow that listens for changes in the database via the InvalidationTracker and emits sets of the tables that were invalidated.

The Flow will emit at least one value, a set of all the tables registered for observation to kick-start the stream unless emitInitialState is set to false.

If one of the tables to observe does not exist in the database, this Flow throws an IllegalArgumentException during collection.

The returned Flow can be used to create a stream that reacts to changes in the database:

fun getArtistTours(from: Date, to: Date): Flow<Map<Artist, TourState>> {
return db.invalidationTrackerFlow("Artist").map { _ ->
val artists = artistsDao.getAllArtists()
val tours = tourService.fetchStates(artists.map { it.id })
associateTours(artists, tours, from, to)
}
}
Parameters
@NonNull String tables

The name of the tables or views to observe.

boolean emitInitialState

Set to false if no initial emission is desired. Default value is true.