RoomDatabase

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

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.

Public functions

open Unit

This function is deprecated. beginTransaction() is deprecated

abstract Unit

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

open Unit

Closes the database if it is already open.

open SupportSQLiteStatement

Wrapper for SupportSQLiteDatabase.compileStatement.

open Unit

This function is deprecated. endTransaction() is deprecated

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

Gets the instance of the given Type Converter.

open Boolean

Returns true if current thread is in a transaction.

open Unit

Called by Room when it is initialized.

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

Convenience method to query the database with arguments.

open Cursor

Wrapper for SupportSQLiteDatabase.query.

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

Executes the specified Callable in a database transaction.

open Unit

Executes the specified Runnable in a database transaction.

open Unit

This function is deprecated. setTransactionSuccessful() is deprecated

Protected functions

abstract InvalidationTracker

Called when the RoomDatabase is created.

abstract SupportSQLiteOpenHelper

Creates the open helper to access the database.

open Unit

Called by the generated code when database is open.

Public properties

open InvalidationTracker

The invalidation tracker for this database.

open Boolean

True if database connection is open and initialized.

open SupportSQLiteOpenHelper

The SQLite open helper used by this database.

open Executor

The Executor in use by this database for async queries.

open Executor

The Executor in use by this database for async transactions.

Protected properties

volatile SupportSQLiteDatabase?

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

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.

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

Calls the specified suspending block in a database transaction.

Public constructors

RoomDatabase

Added in 2.0.0
RoomDatabase()

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

Public functions

beginTransaction

Added in 2.0.0
Deprecated in 2.1.0
open fun beginTransaction(): Unit

Wrapper for SupportSQLiteDatabase.beginTransaction.

clearAllTables

Added in 2.0.0
@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

Added in 2.0.0
open fun close(): Unit

Closes the database if it is already open.

compileStatement

Added in 2.0.0
open fun compileStatement(sql: String): SupportSQLiteStatement

Wrapper for SupportSQLiteDatabase.compileStatement.

Parameters
sql: String

The query to compile.

Returns
SupportSQLiteStatement

The compiled query.

endTransaction

Added in 2.0.0
Deprecated in 2.1.0
open fun endTransaction(): Unit

Wrapper for SupportSQLiteDatabase.endTransaction.

getTypeConverter

Added in 2.3.0
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

Added in 2.0.0
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

init

Added in 2.0.0
@CallSuper
open fun init(configuration: DatabaseConfiguration): Unit

Called by Room when it is initialized.

Parameters
configuration: DatabaseConfiguration

The database configuration.

Throws
kotlin.IllegalArgumentException

if initialization fails.

query

Added in 2.0.0
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

Added in 2.2.0
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

Added in 2.0.0
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

Added in 2.0.0
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

Added in 2.0.0
Deprecated in 2.1.0
open fun setTransactionSuccessful(): Unit

Wrapper for SupportSQLiteDatabase.setTransactionSuccessful.

Protected functions

createInvalidationTracker

Added in 2.0.0
protected abstract fun createInvalidationTracker(): InvalidationTracker

Called when the RoomDatabase is created.

This is already implemented by the generated code.

Returns
InvalidationTracker

Creates a new InvalidationTracker.

createOpenHelper

Added in 2.0.0
protected abstract 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.

internalInitInvalidationTracker

Added in 2.0.0
protected open fun internalInitInvalidationTracker(db: SupportSQLiteDatabase): Unit

Called by the generated code when database is open.

You should never call this method manually.

Parameters
db: SupportSQLiteDatabase

The database instance.

Public properties

invalidationTracker

Added in 2.0.0
open 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

Added in 2.0.0
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

Added in 2.0.0
open val openHelperSupportSQLiteOpenHelper

The SQLite open helper used by this database.

queryExecutor

Added in 2.0.0
open val queryExecutorExecutor

The Executor in use by this database for async queries.

transactionExecutor

Added in 2.1.0
open val transactionExecutorExecutor

The Executor in use by this database for async transactions.

Protected properties

mDatabase

Added in 2.0.0
Deprecated in 2.1.0
volatile protected var mDatabaseSupportSQLiteDatabase?

Set by the generated open helper.

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.

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.