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

Builder for RoomDatabase.

abstract class RoomDatabase.Callback

Callback for RoomDatabase

Journal modes for SQLite database.

A container to hold migrations.

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

Callback interface for when SQLite queries are executed.

Public constructors

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

android
Cmn
N

Public functions

open Unit

This function is deprecated. beginTransaction() is deprecated

android
abstract Unit

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

android
Unit

Closes the database.

Cmn
android
N
open SupportSQLiteStatement

Wrapper for SupportSQLiteDatabase.compileStatement.

android
open Unit

This function is deprecated. endTransaction() is deprecated

android
open T?
<T : Any> getTypeConverter(klass: Class<T>)

This function is deprecated. No longer called by generated implementation

android
open Boolean

Returns true if current thread is in a transaction.

android
open Cursor
query(query: String, args: Array<Any?>?)

Convenience method to query the database with arguments.

android
open Cursor

Wrapper for SupportSQLiteDatabase.query.

android
open V
<V : Any?> runInTransaction(body: Callable<V>)

Executes the specified Callable in a database transaction.

android
open Unit

Executes the specified Runnable in a database transaction.

android
open Unit

This function is deprecated. setTransactionSuccessful() is deprecated

android

Protected functions

abstract InvalidationTracker

Creates the invalidation tracker

Cmn
android
N
open SupportSQLiteOpenHelper

This function is deprecated. No longer implemented by generated

android
open Unit

This function is deprecated. No longer called by generated

android

Public properties

InvalidationTracker

The invalidation tracker for this database.

Cmn
android
N
open Boolean

True if database connection is open and initialized.

android
open SupportSQLiteOpenHelper

The SQLite open helper used by this database.

android
open Executor

The Executor in use by this database for async queries.

android
open Executor

The Executor in use by this database for async transactions.

android

Protected properties

volatile SupportSQLiteDatabase?

This property is deprecated. This property is always null and will be removed in a future version.

android

Extension functions

Flow<Set<String>>
RoomDatabase.invalidationTrackerFlow(
    vararg tables: String,
    emitInitialState: Boolean
)

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

android
suspend R
<R : Any?> RoomDatabase.useReaderConnection(block: suspend (Transactor) -> R)

Acquires a READ connection, suspending while waiting if none is available and then calling the block to use the connection once it is acquired.

Cmn
suspend R
<R : Any?> RoomDatabase.useWriterConnection(block: suspend (Transactor) -> R)

Acquires a WRITE connection, suspending while waiting if none is available and then calling the block to use the connection once it is acquired.

Cmn
suspend R
<R : Any?> RoomDatabase.withTransaction(block: suspend () -> R)

Calls the specified suspending block in a database transaction.

android

Public constructors

RoomDatabase

RoomDatabase()

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

RoomDatabase

RoomDatabase()

RoomDatabase

RoomDatabase()

Public functions

beginTransaction

open fun beginTransaction(): Unit

Wrapper for SupportSQLiteDatabase.beginTransaction.

clearAllTables

@WorkerThread
abstract fun clearAllTables(): Unit

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

fun close(): Unit

Closes the database.

Once a RoomDatabase is closed it should no longer be used.

compileStatement

open fun compileStatement(sql: String): SupportSQLiteStatement

Wrapper for SupportSQLiteDatabase.compileStatement.

Parameters
sql: String

The query to compile.

Returns
SupportSQLiteStatement

The compiled query.

endTransaction

open fun endTransaction(): Unit

Wrapper for SupportSQLiteDatabase.endTransaction.

getTypeConverter

open fun <T : Any> getTypeConverter(klass: Class<T>): T?

Gets the instance of the given Type Converter.

Parameters
<T : Any>

The type of the expected Type Converter subclass.

klass: Class<T>

The Type Converter class.

Returns
T?

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

inTransaction

open fun inTransaction(): Boolean

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

query

open fun query(query: String, args: Array<Any?>?): Cursor

Convenience method to query the database with arguments.

Parameters
query: String

The sql query

args: Array<Any?>?

The bind arguments for the placeholders in the query

Returns
Cursor

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

query

open fun query(query: SupportSQLiteQuery, signal: CancellationSignal? = null): Cursor

Wrapper for SupportSQLiteDatabase.query.

Parameters
query: SupportSQLiteQuery

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

signal: CancellationSignal? = null

The cancellation signal to be attached to the query.

Returns
Cursor

Result of the query.

runInTransaction

open fun <V : Any?> runInTransaction(body: Callable<V>): V

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 : Any?>

The type of the return value.

body: Callable<V>

The piece of code to execute.

Returns
V

The value returned from the Callable.

runInTransaction

open fun runInTransaction(body: Runnable): Unit

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
body: Runnable

The piece of code to execute.

setTransactionSuccessful

open fun setTransactionSuccessful(): Unit

Wrapper for SupportSQLiteDatabase.setTransactionSuccessful.

Protected functions

createInvalidationTracker

protected abstract fun createInvalidationTracker(): InvalidationTracker

Creates the invalidation tracker

An implementation of this function is generated by the Room processor. Note that this method is called when the RoomDatabase is initialized.

Returns
InvalidationTracker

A new invalidation tracker.

createOpenHelper

protected open fun createOpenHelper(config: DatabaseConfiguration): SupportSQLiteOpenHelper

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
config: DatabaseConfiguration

The configuration of the Room database.

Returns
SupportSQLiteOpenHelper

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

Throws
kotlin.NotImplementedError

by default

internalInitInvalidationTracker

protected open fun internalInitInvalidationTracker(db: SupportSQLiteDatabase): Unit

Initialize invalidation tracker. Note that this method is called when the RoomDatabase is initialized and opens a database connection.

Parameters
db: SupportSQLiteDatabase

The database instance.

Public properties

invalidationTracker

val invalidationTrackerInvalidationTracker

The invalidation tracker for this database.

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

Returns
InvalidationTracker

The invalidation tracker for the database.

isOpen

open val isOpenBoolean

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.

openHelper

open val openHelperSupportSQLiteOpenHelper

The SQLite open helper used by this database.

queryExecutor

open val queryExecutorExecutor

The Executor in use by this database for async queries.

transactionExecutor

open val transactionExecutorExecutor

The Executor in use by this database for async transactions.

Protected properties

mDatabase

volatile protected var mDatabaseSupportSQLiteDatabase?

Extension functions

invalidationTrackerFlow

fun RoomDatabase.invalidationTrackerFlow(
    vararg tables: String,
    emitInitialState: Boolean = true
): Flow<Set<String>>

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
vararg tables: String

The name of the tables or views to observe.

emitInitialState: Boolean = true

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

useReaderConnection

suspend fun <R : Any?> RoomDatabase.useReaderConnection(block: suspend (Transactor) -> R): R

Acquires a READ connection, suspending while waiting if none is available and then calling the block to use the connection once it is acquired. A RoomDatabase will have one or more READ connections. The connection to use in the block is an instance of Transactor that provides the capabilities for performing nested transactions.

Using the connection after block completes is prohibited.

The connection will be confined to the coroutine on which block executes, attempting to use the connection from a different coroutine will result in an error.

If the current coroutine calling this function already has a confined connection, then that connection is used.

A connection is a limited resource and should not be held for more than it is needed. The best practice in using connections is to avoid executing long-running computations within the block. If a caller has to wait too long to acquire a connection a SQLiteException will be thrown due to a timeout.

Parameters
block: suspend (Transactor) -> R

The code to use the connection.

Throws
androidx.sqlite.SQLiteException

when the database is closed or a thread confined connection needs to be upgraded or there is a timeout acquiring a connection.

useWriterConnection

suspend fun <R : Any?> RoomDatabase.useWriterConnection(block: suspend (Transactor) -> R): R

Acquires a WRITE connection, suspending while waiting if none is available and then calling the block to use the connection once it is acquired. A RoomDatabase will have only one WRITE connection. The connection to use in the block is an instance of Transactor that provides the capabilities for performing nested transactions.

Using the connection after block completes is prohibited.

The connection will be confined to the coroutine on which block executes, attempting to use the connection from a different coroutine will result in an error.

If the current coroutine calling this function already has a confined connection, then that connection is used as long as it isn't required to be upgraded to a writer. If an upgrade is required then a SQLiteException is thrown.

A connection is a limited resource and should not be held for more than it is needed. The best practice in using connections is to avoid executing long-running computations within the block. If a caller has to wait too long to acquire a connection a SQLiteException will be thrown due to a timeout.

Parameters
block: suspend (Transactor) -> R

The code to use the connection.

Throws
androidx.sqlite.SQLiteException

when the database is closed or a thread confined connection needs to be upgraded or there is a timeout acquiring a connection.

withTransaction

suspend fun <R : Any?> RoomDatabase.withTransaction(block: suspend () -> R): R

Calls the specified suspending block in a database transaction. The transaction will be marked as successful unless an exception is thrown in the suspending block or the coroutine is cancelled.

Room will only perform at most one transaction at a time, additional transactions are queued and executed on a first come, first serve order.

Performing blocking database operations is not permitted in a coroutine scope other than the one received by the suspending block. It is recommended that all Dao function invoked within the block be suspending functions.

The internal dispatcher used to execute the given block will block an utilize a thread from Room's transaction executor until the block is complete.