Комната

Библиотека Room для обеспечения постоянного доступа к данным предоставляет уровень абстракции поверх SQLite, что позволяет обеспечить более надежный доступ к базе данных, используя при этом все возможности SQLite.
Последнее обновление Стабильный релиз Предварительная версия релиза Бета-версия Альфа-версия
9 сентября 2026 г. 2.8.5 - - -

Объявление зависимостей

Чтобы добавить зависимость от Room, необходимо добавить репозиторий Google Maven в ваш проект. Для получения дополнительной информации ознакомьтесь с информацией в репозитории Google Maven .

В зависимости для Room входят тестовые миграции Room и Room RxJava.

Добавьте зависимости для необходимых артефактов в файл build.gradle вашего приложения или модуля:

Котлин

dependencies {
    val room_version = "2.8.4"

    implementation("androidx.room:room-runtime:$room_version")

    // If this project uses any Kotlin source, use Kotlin Symbol Processing (KSP)
    // See Add the KSP plugin to your project
    ksp("androidx.room:room-compiler:$room_version")

    // If this project only uses Java source, use the Java annotationProcessor
    // No additional plugins are necessary
    annotationProcessor("androidx.room:room-compiler:$room_version")

    // optional - Kotlin Extensions and Coroutines support for Room
    implementation("androidx.room:room-ktx:$room_version")

    // optional - RxJava2 support for Room
    implementation("androidx.room:room-rxjava2:$room_version")

    // optional - RxJava3 support for Room
    implementation("androidx.room:room-rxjava3:$room_version")

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation("androidx.room:room-guava:$room_version")

    // optional - Test helpers
    testImplementation("androidx.room:room-testing:$room_version")

    // optional - Paging 3 Integration
    implementation("androidx.room:room-paging:$room_version")
}

Круто

dependencies {
    def room_version = "2.8.4"

    implementation "androidx.room:room-runtime:$room_version"

    // If this project uses any Kotlin source, use Kotlin Symbol Processing (KSP)
    // See KSP Quickstart to add KSP to your build
    ksp "androidx.room:room-compiler:$room_version"

    // If this project only uses Java source, use the Java annotationProcessor
    // No additional plugins are necessary
    annotationProcessor "androidx.room:room-compiler:$room_version"

    // optional - RxJava2 support for Room
    implementation "androidx.room:room-rxjava2:$room_version"

    // optional - RxJava3 support for Room
    implementation "androidx.room:room-rxjava3:$room_version"

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation "androidx.room:room-guava:$room_version"

    // optional - Test helpers
    testImplementation "androidx.room:room-testing:$room_version"

    // optional - Paging 3 Integration
    implementation "androidx.room:room-paging:$room_version"
}

Для получения информации об использовании плагина KAPT см. документацию KAPT .

Для получения информации об использовании плагина KSP см. документацию по быстрому запуску KSP .

Для получения информации об использовании расширений Kotlin см. документацию ktx .

Для получения дополнительной информации о зависимостях см. раздел «Добавление зависимостей сборки» .

В качестве опции, для библиотек, не относящихся к Android (например, модулей Gradle только для Java или Kotlin), вы можете использовать зависимость androidx.room:room-common для применения аннотаций Room.

Настройка параметров компилятора

В Room доступны следующие параметры обработки аннотаций.

room.schemaLocation directory
Позволяет экспортировать схемы баз данных в файлы JSON в указанном каталоге. Дополнительную информацию см. в разделе «Миграция комнат» .
room.incremental boolean
Включает процессор инкрементальных аннотаций Gradle. Значение по умолчанию — true .
room.generateKotlin boolean
Генерировать исходные файлы Kotlin вместо Java. Требуется KSP. Значение по умолчанию — true , начиная с версии 2.7.0 . Подробнее см. примечания к версии 2.6.0 , когда эта функция была введена.

Используйте плагин Room Gradle.

Начиная с версии Room 2.6.0 и выше, вы можете использовать плагин Room Gradle для настройки параметров компилятора Room. Плагин настраивает проект таким образом, чтобы сгенерированные схемы (которые являются результатом задач компиляции и используются для автоматической миграции) были корректно настроены для обеспечения воспроизводимых и кэшируемых сборок.

Чтобы добавить плагин, в главном файле сборки Gradle укажите плагин и его версию.

Классный

plugins {
    id 'androidx.room' version "$room_version" apply false
}

Котлин

plugins {
    id("androidx.room") version "$room_version" apply false
}

В файле сборки Gradle на уровне модуля примените плагин и используйте расширение room .

Классный

plugins {
    id 'androidx.room'
}

android {
    ...
    room {
        schemaDirectory "$projectDir/schemas"
    }
}

Котлин

plugins {
    id("androidx.room")
}

android {
    ...
    room {
        schemaDirectory("$projectDir/schemas")
    }
}

Для использования плагина Room Gradle необходимо указать schemaDirectory . Это позволит настроить компилятор Room, различные задачи компиляции и их бэкенды (javac, KAPT, KSP) для вывода файлов схем в папки с заданными параметрами, например schemas/flavorOneDebug/com.package.MyDatabase/1.json . Эти файлы следует добавить в репозиторий для использования в целях проверки и автоматической миграции.

Некоторые параметры нельзя настроить во всех версиях плагина Room Gradle, даже если они поддерживаются компилятором Room. В таблице ниже перечислены все параметры и указана версия плагина Room Gradle, в которой добавлена ​​поддержка настройки этих параметров с помощью расширения room . Если ваша версия ниже или если параметр еще не поддерживается, вы можете использовать параметры обработчика аннотаций .

Вариант Начиная с версии
room.schemaLocation (обязательно) 2.6.0
room.incremental -
room.generateKotlin -

Использовать параметры процессора аннотаций

Если вы не используете плагин Room Gradle или если нужная вам опция не поддерживается вашей версией плагина, вы можете настроить Room, используя параметры обработчика аннотаций, как описано в разделе «Добавление зависимостей сборки» . Способ указания параметров аннотаций зависит от того, используете ли вы KSP или KAPT для Room.

Классный

// For KSP
ksp {
    arg("option_name", "option_value")
    // other otions...
}

// For javac and KAPT
android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += [
                    "option_name":"option_value",
                    // other options...
                    ]
            }
        }
    }
}

Котлин

// For KSP
ksp {
    arg("option_name", "option_value")
    // other options...
}

// For javac and KAPT
android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += mapOf(
                    "option_name" to "option_value",
                    // other options...
                )
            }
        }
    }
}

Поскольку room.schemaLocation — это каталог, а не примитивный тип данных, при добавлении этой опции необходимо использовать CommandLineArgumentsProvider , чтобы Gradle знал об этом каталоге при проведении проверок актуальности. В руководстве по миграции базы данных Room представлена ​​полная реализация CommandLineArgumentsProvider , предоставляющая информацию о местоположении схемы.

Обратная связь

Ваши отзывы помогают улучшить Jetpack. Сообщите нам, если вы обнаружите новые проблемы или у вас есть идеи по улучшению этой библиотеки. Пожалуйста, ознакомьтесь с существующими проблемами в этой библиотеке, прежде чем создавать новую. Вы можете проголосовать за существующую проблему, нажав кнопку со звездочкой.

Создать новую задачу

Для получения более подробной информации см. документацию по системе отслеживания ошибок .

Версия 2.8

Версия 2.8.5

9 сентября 2026 г.

Выпущена версия androidx.room:room-*:2.8.5 . Версия 2.8.5 содержит следующие коммиты .

Исправлены ошибки

  • Теперь приостановка запросов в Room и операции отслеживания недействительности будут вызывать исключение IllegalStateException при вызове после закрытия базы данных. ( Ic0166 , b/543076356 )

Версия 2.8.4

19 ноября 2025 г.

Выпущена версия androidx.room:room-*:2.8.4 . Версия 2.8.4 содержит следующие коммиты .

Исправлены ошибки

  • Добавлен кэш подготовленных запросов в пул соединений Room при использовании SQLiteDriver , который не имеет внутреннего пула, например, BundledSQLiteDriver . Это повышает производительность при повторном выполнении одного и того же SQL-запроса. ( 5f43bc , b/319653917 )
  • Исправлена ​​ошибка, из-за которой в фактическом/ожидаемом сообщении об ошибке при проверке схемы отсутствовала необходимая информация. ( 8b23da , b/454531083 )
  • Исправлена ​​ошибка в генерации кода Kotlin в Room, из-за которой отсутствовали функции DAO с @Transaction и переменными типа. ( a8365d , b/251316420 )
  • Повысьте производительность обертки SupportSQLite в Room, избегая переключения потоков, сохраняющих то же блокирующее поведение, что и API SupportSQLiteDatabase . ( fc70e4 )

Версия 2.8.3

22 октября 2025 г.

Выпущена версия androidx.room:room-*:2.8.3 . Версия 2.8.3 содержит следующие коммиты .

Исправлены ошибки

  • Исправлена ​​ошибка производительности в Room SQLite Wrapper, которая приводила к чрезмерному количеству вызовов JNI и значительному снижению производительности при итерации по курсору.

Версия 2.8.2

8 октября 2025 г.

Выпущена версия androidx.room:room-*:2.8.2 . Версия 2.8.2 содержит следующие коммиты .

Исправлены ошибки

  • Исправлена ​​ошибка, из-за которой могла возникнуть взаимоблокировка при повторном открытии автоматически закрытой базы данных из сообщения Flow ( b/446643789 ).

Версия 2.8.1

24 сентября 2025 г.

Выпущена версия androidx.room:room-*:2.8.1 . Версия 2.8.1 содержит следующие коммиты .

Исправлены ошибки

  • Исправлена ​​ошибка, приводящая к сбою процессора при обработке функции DAO с лямбда-функцией, вызывающей приостановку выполнения. ( b/442220723 ).
  • Исправлена ​​ошибка, приводящая к состоянию гонки, из-за которой Flows не получали последние обновления.

Версия 2.8.0

10 сентября 2025 г.

Выпущена версия androidx.room:room-*:2.8.0 . Версия 2.8.0 содержит следующие коммиты .

Важные изменения по сравнению с версией 2.7.0:

  • Добавлен новый артефакт androidx.room:room-sqlite-wrapper , содержащий API для получения обертки SupportSQLiteDatabase из RoomDatabase с настроенным SQLiteDriver . Для получения обертки используйте новую функцию расширения RoomDatabase.getSupportWrapper() . Это артефакт совместимости, позволяющий сохранить использование SupportSQLiteDatabase , обычно получаемого из roomDatabase.openHelper.writableDatabase , даже если база данных Room настроена с SQLiteDriver . Эта обертка полезна для поэтапной миграции кодовых баз, которые хотят использовать API SQLiteDriver, но при этом активно используют API SupportSQLite и хотят воспользоваться преимуществами BundledSQLiteDriver . Для получения дополнительной информации ознакомьтесь с руководством по миграции .
  • Добавлена ​​поддержка целевых операционных систем KMP: Watch OS и TV OS.
  • Обновлен Android minSDK библиотеки с API 21 до API 23.

Версия 2.8.0-rc02

27 августа 2025 г.

Выпущена версия androidx.room:room-*:2.8.0-rc02 . Версия 2.8.0-rc02 содержит следующие коммиты .

Изменения в API

  • Обновите minSDK с API 21 до API 23 ( Ibdfca , b/380448311 , b/435705964 , b/435705223 )
  • Обновите минимальную версию плагина Android Gradle (AGP), совместимую с плагином Room Gradle, с 8.1 до 8.4. ( Ia0d28 )

Исправлены ошибки

  • Исправлена ​​ошибка, из-за которой выполнялась деструктивная миграция, даже если для предварительно подготовленной базы данных был доступен путь миграции ( b/432634197 ).

Версия 2.8.0-rc01

13 августа 2025 г.

Выпущена версия androidx.room:room-*:2.8.0-rc01 . Версия 2.8.0-rc01 содержит следующие коммиты .

Изменения в API

  • Удаление устаревших аннотаций @RequiresApi(21) ( Ic4792 , I9103b )

Исправлены ошибки

  • Исправлена ​​ошибка, из-за которой Room Flows не отправлял последний результат запроса в асинхронной ситуации с множественными запросами/записями. ( Ic9a3c )

Версия 2.8.0-beta01

1 августа 2025 г.

Выпущена версия androidx.room:room-*:2.8.0-beta01 . Версия 2.8.0-beta01 содержит следующие коммиты .

Исправлены ошибки

  • Теперь имена таблиц и представлений корректно экранируются во время деструктивных миграций. ( 9e55f8 , b/427095319 )

Версия 2.8.0-alpha01

16 июля 2025 г.

Выпущена версия androidx.room:room-*:2.8.0-alpha01 . Версия 2.8.0-alpha01 содержит следующие коммиты .

Новые функции

  • Добавлен новый артефакт androidx.room:room-sqlite-wrapper , содержащий API для получения обертки SupportSQLiteDatabase для RoomDatabase с настроенным SQLiteDriver . Для получения обертки используйте новую функцию расширения RoomDatabase.getSupportWrapper() . Это артефакт совместимости, позволяющий сохранить использование SupportSQLiteDatabase , обычно получаемого из RoomDatabase.openHelper.writableDatabase , даже если база данных Room настроена с SQLiteDriver . Эта обертка полезна для поэтапной миграции кодовых баз, которые хотят использовать SQLiteDriver , но активно используют API SupportSQLite , и при этом хотят воспользоваться преимуществами BundledSQLiteDriver . ( Icf6ac )
  • Добавлены цели KMP для Watch OS и TV OS ( I228f6 , b/394238801 )

Исправлены ошибки

  • Исправлена ​​ошибка взаимоблокировки, которая могла периодически возникать при использовании приостановки транзакций и AndroidSQLiteDriver . ( b/415006268 )

Версия 2.7

Версия 2.7.2

18 июня 2025 г.

Выпущена версия androidx.room:room-*:2.7.2 . Версия 2.7.2 содержит следующие коммиты .

Исправлены ошибки

  • Исправлена ​​ошибка, из-за которой значения аннотаций некорректно считывались при обработке исходных файлов с помощью KSP, иногда из-за отсутствия экспортированных схем. ( b/416549580 )
  • Исправлена ​​ошибка, из-за которой вводные комментарии в SQL-запросах приводили к выполнению запросов так, как если бы они не были запросами на чтение. ( b/413061402 )
  • Исправлена ​​ошибка, из-за которой плагин Room для Gradle не мог быть настроен из-за пустого каталога схемы. ( b/417823384 )
  • Теперь при слишком длительном получении соединения не выбрасывается исключение SQLiteException ; вместо этого библиотека будет отправлять сообщение в лог. Использование логов вместо выбрасывания исключения позволяет обойти проблему с приостановкой работы циклов iOS, из-за которой Room неправильно интерпретирует таймаут, возникающий в сопрограмме Kotlin при получении соединения, и, таким образом, предотвращает выбрасывание исключения, когда приложение iOS переводится в фоновый режим, а затем возобновляется в середине операции с базой данных. ( b/422448815 )

Версия 2.7.1

23 апреля 2025 г.

Выпущена версия androidx.room:room-*:2.7.1 . Версия 2.7.1 содержит следующие коммиты .

Исправлены ошибки

  • Исправлена ​​ошибка IndexOutOfBoundsException возникающая при проверке предоставленного преобразователя типов. ( b/409804755 ).
  • Поддержка RoomDatabase.runInTransaction() при настройке SQLiteDriver с использованием Room. ( b/408364828 ).

Версия 2.7.0

9 апреля 2025 г.

Выпущена версия androidx.room:room-*:2.7.0 . Версия 2.7.0 содержит следующие коммиты .

Важные изменения по сравнению с версией 2.6.0

  • Поддержка многоплатформенности Kotlin (KMP): В этом релизе Room был переработан и стал библиотекой для работы с многоплатформенной архитектурой Kotlin (KMP). В настоящее время поддерживаются платформы Android, iOS, JVM (Desktop), нативные приложения для Mac и Linux. Для получения дополнительной информации о том, как начать использовать Room KMP, обратитесь к официальной документации Room KMP . В рамках поддержки KMP Room также может быть настроен с использованием SQLiteDriver . Информацию о том, как перенести существующее приложение на API драйвера и в Room KMP, см. в документации по миграции .
  • Генерация кода Kotlin в KSP включена по умолчанию, если обработка выполняется через KSP. Для проектов KAPT или проектов, использующих только Java, Room по-прежнему будет генерировать исходный код Java.
  • Kotlin 2.0 и KSP2: Room теперь ориентирован на язык Kotlin 2.0 и потребует от проектов компиляции с Kotlin 2.0 и эквивалентной или более высокой версией языка. Также добавлена ​​поддержка KSP2, которая рекомендуется при использовании Room с Kotlin 2.0 или более поздней версии.

Версия 2.7.0-rc03

26 марта 2025 г.

Выпущена версия androidx.room:room-*:2.7.0-rc03 . Версия 2.7.0-rc03 содержит следующие коммиты .

Исправлены ошибки

  • Больше не генерируется исключение InterruptedException при прерывании потока во время выполнения блокирующих API Room, включая блокирующие функции DAO ( b/400584611 ).
  • Для устранения ошибки SQLException: Error code: 5, message: Timed out attempting to acquire a reader connection. и подобных проблем ( b/380088809 ) необходимо повторно реализовать пул соединений Room.

Версия 2.7.0-rc02

12 марта 2025 г.

Выпущена версия androidx.room:room-*:2.7.0-rc02 . Версия 2.7.0-rc02 содержит следующие коммиты .

Исправлены ошибки

  • Исправлена ​​ошибка автоматической миграции, некорректно обрабатывающая новый столбец в таблице FTS. ( b/348227770 , Ic53f3 )
  • Исправлена ​​ошибка компиляции room, приводящая к сбою из- NullPointerException при обработке исходных файлов, не относящихся к JVM, через KSP. ( b/396607230 , I693c9 )
  • Исправлена ​​ошибка, из-за которой Room не аннулировал таблицы по завершении использования соединения записи. ( b/340606803 , I73ef6 )

Версия 2.7.0-rc01

26 февраля 2025 г.

Выпущена версия androidx.room:room-*:2.7.0-rc01 . Версия 2.7.0-rc01 содержит следующие коммиты .

Исправлены ошибки

  • Исправлена ​​ошибка, из-за которой Room не устанавливал busy_timeout при первоначальном подключении к базе данных, что приводило к SQLException: Error code: 5, message: database is locked ( I93208 , b/380088809 ).
  • Исправлена ​​ошибка в компиляторе Room, из-за которой процессор KSP аварийно завершал работу при обработке нативных наборов исходного кода (например, iOS) в Kotlin 2.1.x и KSP1 ( I883b8 , b/396607230 ).

Версия 2.7.0-beta01

12 февраля 2025 г.

Выпущена версия androidx.room:room-*:2.7.0-beta01 . Версия 2.7.0-beta01 содержит следующие коммиты .

Исправлены ошибки

  • Исправлена ​​ошибка, из-за которой метод RoomDatabase.inTransaction() открывал закрытую базу данных, когда этого делать не следовало, и должен был быстро возвращать false, если база данных закрыта ( b/325432967 ).
  • Исправлена ​​ошибка ( IllegalArgumentException: not a valid name ) в компиляторе Room при обработке функций DAO с использованием встроенных классов Kotlin / классов значений ( b/388299754 ).
  • Включите правила Proguard в артефакт JVM среды room-runtime , чтобы конструктор по умолчанию сгенерированной реализации базы данных не удалялся, поскольку он используется при инициализации Room по умолчанию с помощью рефлексии ( b/392657750 ).

Версия 2.7.0-alpha13

29 января 2025 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha13 . Версия 2.7.0-alpha13 содержит следующие коммиты .

Изменения в API

  • Теперь Room ориентирован на язык Kotlin 2.0 и потребует от проектов компиляции с Kotlin 2.0 и эквивалентной или более высокой версией языка. ( I8efb0 , b/315461431 , b/384600605 )

Исправлены ошибки

  • Исправлена ​​ошибка в конструкторе баз данных Room KMP, из-за которой в Android вместо пути использовалось простое имя, и путь к файлу базы данных, полученный в результате разрешения, не находился в каталоге данных приложения. ( I83315 , b/377830104 )
  • Исправлена ​​ошибка в плагине Room Gradle, из-за которой настройка входных и выходных данных схемы вызывала проблемы в проектах Android: property 'inputDirectory' is final and cannot be changed any further. ( 1dbb4c , b/376071291 )
  • Добавлена ​​поддержка KSP2 в плагине Room Gradle, исправлена ​​ошибка, из-за которой плагин некорректно настраивал каталог схемы. ( Iec3c4 , b/379159770 )

Внешний вклад

  • Исправлена ​​ошибка в интеграции постраничной навигации Room из-за которой происходили скачки в пользовательском интерфейсе, когда начальная клавиша обновления находилась слишком близко к концу списка. Спасибо Еве! ( I2abbe , b/389729367 )

Версия 2.7.0-alpha12

11 декабря 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha12 . Версия 2.7.0-alpha12 содержит следующие коммиты .

Изменения в API

  • Добавьте экспериментальный API RoomDatabase.Builder.setInMemoryTrackingMode() для настройки того, будет ли Room использовать таблицу в оперативной памяти для отслеживания инвалидации. ( I2a9b2 , b/185414040 )

Исправлены ошибки

  • Теперь деструктивные миграции удаляют представления, чтобы гарантировать их повторное создание, что приводит к тому, что поведение при включенном параметре allowDestructiveMigrationForAllTables (по умолчанию в KMP) согласуется с существующим поведением при его выключенном параметре. ( 0a3e83 , b/381518941 )

Версия 2.7.0-alpha11

30 октября 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha11 . Версия 2.7.0-alpha11 содержит следующие коммиты .

Изменения в API

  • Пересмотрите сигнатуру недавно добавленного метода convertRows() , чтобы он стал функцией приостановки, принимающей RawRoomQuery для постраничной навигации в комнате. ( Ie57b5 , b/369136627 )

Исправлены ошибки

  • Исправлена ​​ошибка в модуле room-paging, из-за которой генерировался некорректный код при использовании @Relation в сочетании с PagingSource .

Версия 2.7.0-alpha10

16 октября 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha10 . Версия 2.7.0-alpha10 содержит следующие коммиты .

Изменения в API

  • Создайте внутренний класс ByteArrayWrapper для поддержки связей с ByteBuffer на платформах, отличных от Android и JVM. ( I75543 , b/367205685 )
  • Добавьте SQLiteStatement.getColumnType() вместе с различными константами результата SQLITE_DATA_* , чтобы обеспечить возможность получения типа данных столбца. ( I1985c , b/369636251 )

Версия 2.7.0-alpha09

2 октября 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha09 . Версия 2.7.0-alpha09 содержит следующие коммиты .

Исправлены ошибки

  • Исправлена ​​ошибка в реализации KMP для room-paging , которая приводила к Error code: 8, message: attempt to write a readonly database из-за начала транзакции записи в соединении для чтения. ( b/368380988 )

Версия 2.7.0-alpha08

18 сентября 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha08 . Версия 2.7.0-alpha08 содержит следующие коммиты .

Новые функции

  • Артефакты room-paging были перенесены для обеспечения совместимости с KMP. ( Ib8756 , b/339934824 )
  • API invalidationTrackerFlow() был стандартизирован как API от разработчика ( InvalidationTracker.createFlow() и теперь доступен для наборов исходного кода, отличных от Android, в проектах KMP. ( I1fbfa , ( I8fb29 ), b/329291639 , b/329315924 )

Изменения в API

  • Все предупреждения и сообщения об ошибках в Room, содержащие слово Cursor были удалены или заменены, поскольку Cursor больше не является точным общим термином для использования в версии Room для KMP. ( Id8cd9 , b/334087492 )

Исправлены ошибки

  • Исправлена ​​ошибка, из-за которой Room KMP пытался сгенерировать код, используя UUID для платформ, отличных от JVM. ( b/362994709 )
  • Исправлена ​​ошибка в плагине Room Gradle, которая вызывала ошибку типа «Невозможно изменить атрибуты конфигурации… после того, как она была заблокирована для изменения» при использовании в проекте KMP с Compose Multiplatform. ( b/343408758 )

Версия 2.7.0-alpha07

21 августа 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha07 . Версия 2.7.0-alpha07 содержит следующие коммиты .

Новые функции

  • Теперь плагин Room Gradle будет автоматически добавлять экспортированные схемы в источники ресурсов Android Instrumentation Test, чтобы их мог использовать MigrationTestHelper .

Исправлены ошибки

  • Исправлена ​​ошибка, из-за которой сгенерированный объект 'actual' конструктора RoomDatabaseConstructor не имел модификатора 'actual' в функции initialize , если эта функция также переопределена в объявлении 'expect'. ( 359631627 )
  • Исправлена ​​ошибка, из-за которой сгенерированное значение 'actual' конструктора RoomDatabaseConstructor не соответствовало видимости объявления 'expect'. ( 358138953 )

Версия 2.7.0-alpha06

7 августа 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha06 . Версия 2.7.0-alpha06 содержит следующие коммиты .

Изменения в API

  • Измените параметры создания экземпляра RoomDatabase в проекте KMP.

В связи с моделью компиляции Kotlin 2.0 стратегия ссылки на генерируемую функцию с именем instantiateImpl() больше не является жизнеспособной. Введены два новых API, @ConstructedBy и RoomDatabaseConstructor , которые заменяют стратегию instantiateImpl() . Новая стратегия выглядит следующим образом:

  1. Определите объект expect, реализующий интерфейс RoomDatabaseConstructor

      expect object MyDatabaseCtor : RoomDatabaseConstructor<MyDatabase>
    
  2. Свяжите объект с объявлением @Database , используя @ConstructedBy

      @Database(...)
      @ConstructedBy(MyDatabaseCtor::class) // NEW
      abstract class MyDatabase : RoomDatabase
    
  3. Создайте новый экземпляр базы данных, но без передачи аргумента фабрики.

      fun createNewDatabase(path: String) =
        Room.databaseBuilder<AppDatabase>(name = path)
          .setDriver(BundledSQLiteDriver())
          .setQueryCoroutineContext(Dispatchers.IO)
          .build()
    

Исправлены ошибки b/316978491 , b/338446862 и b/342905180.

  • Поддержка аннотации @RawQuery в Room KMP обеспечивается добавлением нового API под названием RoomRawQuery , аналогичного SupportSQLiteQuery в плане хранения необработанной SQL-строки и функции для привязки аргументов к оператору. Функции с аннотацией @RawQuery теперь могут принимать RoomRawQuery в качестве единственного параметра. ( Iea844 , b/330586815 )
  • Добавьте перегрузку метода setQueryCallback() , которая принимает CoroutineContext . ( Id66ff , b/309996304 )
  • Добавлена ​​поддержка многоплатформенных целевых платформ Kotlin linuxArm64 ( I139d3 , b/338268719 )

Исправлены ошибки

  • Исправлена ​​ошибка, из-за которой Room некорректно генерировал вызов recursiveFetchArrayMap в целевых платформах, отличных от Android. ( 710c36 , b/352482325 )
  • Исправлена ​​ошибка, из-за которой Room иногда выдавал исключение «Время ожидания при попытке подключения» в проекте KMP. ( fa72d0 , b/347737870 )
  • Исправлена ​​ошибка в автоматической миграции, из-за которой проверка внешних ключей выполнялась слишком рано, до того, как другие таблицы изменяли свои схемы в соответствии с новыми внешними ключами. ( 7672c0 , b/352085724 )

Версия 2.7.0-alpha05

10 июля 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha05 . Версия 2.7.0-alpha05 содержит следующие коммиты .

Изменения в API

  • Переименование SQLiteKt в SQLite и BundledSQLiteKt в BundledSQLite . ( I8b501 )

Исправлены ошибки

  • Исправлена ​​ошибка, из-за которой RoomDatabase зависал или выдавал ошибку таймаута соединения при использовании AndroidSQLiteDriver .

Версия 2.7.0-alpha04

12 июня 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha04 . Версия 2.7.0-alpha04 содержит следующие коммиты .

Исправлены ошибки

  • Исправлена ​​ошибка в обработчике аннотаций Room, из-за которой генерировался несовместимый код KMP при определении типа возвращаемого значения multi-map в DAO. ( b/340983093 )
  • Исправлена ​​ошибка, из-за которой Room не мог найти сгенерированную реализацию базы данных, если у класса с аннотацией @Database не был указан пакет. ( b/342097292 )
  • Исправлена ​​ошибка, из-за которой включение автоматического закрытия и многоэкземплярной инвалидации иногда приводило к возникновению исключения ConcurrentModificationException при автоматическом закрытии базы данных из-за простоя.

Версия 2.7.0-alpha03

29 мая 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha03 . Версия 2.7.0-alpha03 содержит следующие коммиты .

Исправлены ошибки

  • Исправлены различные проблемы, связанные с Kotlin 2.0 и KSP 2.0. Обратите внимание, что поддержка Kotlin 2.0 с KSP 2 не завершена, и команда работает над различными API и изменениями в поведении нового компилятора. ( b/314151707 )

Версия 2.7.0-alpha02

14 мая 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha02 . Версия 2.7.0-alpha02 содержит следующие коммиты .

Исправлены ошибки

  • Исправлены различные проблемы KSP.

Версия 2.7.0-alpha01

1 мая 2024 г.

Выпущена версия androidx.room:room-*:2.7.0-alpha01 . Версия 2.7.0-alpha01 содержит следующие коммиты .

Новые функции

  • Поддержка многоплатформенности Kotlin (KMP) : В этом релизе Room был переработан и стал библиотекой для работы с многоплатформенными приложениями Kotlin (KMP). Хотя еще предстоит некоторая работа, этот релиз представляет новую версию Room, в которой большая часть функциональности была «общано» (адаптирована для многоплатформенной работы). В настоящее время поддерживаются платформы Android, iOS, JVM (Desktop), нативные Mac и нативные Linux. Любая недостающая функциональность на новых поддерживаемых платформах будет реализована в будущих релизах Room.

Для получения более подробной информации о том, как начать работу с Room KMP, обратитесь к официальной документации Room KMP .

  • Генерация кода Kotlin в KSP включена по умолчанию, если обработка выполняется через KSP. Для проектов KAPT или проектов, использующих только Java, Room по-прежнему будет генерировать исходный код Java.

Изменения в API

  • Добавлена ​​перегрузка метода Room.databaseBuilder() , принимающая лямбда-параметр, предназначенный для использования с функцией, сгенерированной Room, чтобы избежать использования рефлексии при создании экземпляра сгенерированной реализации RoomDatabase . Пример использования:
Room.databaseBuilder<MyDatabase>(
    context = appContext,
    name = dbFilePath,
    factory =  { MyDatabase::class.instantiateImpl() }
)
  • В конструктор добавлен API для настройки Room с использованием CoroutineContext : RoomDatabase.Builder.setQueryCoroutineContext . Обратите внимание, что RoomDatabase можно настроить только с помощью исполнителей, использующих setQueryExecutor , или с помощью контекста Coroutine, но не с обоими одновременно.
  • Добавлен API для настройки Room с использованием драйвера SQLite : RoomDatabase.Builder.setDriver() . Более подробную информацию об API драйвера SQLite см. в документации SQLite KMP.
  • Добавлены API для доступа к базовому объекту SQLiteConnection из API драйвера: RoomDatabase.useReaderConnection и RoomDatabase.useWriterConnection .
  • Теперь для различных функций обратного вызова, связанных с Room, существует перегруженная версия, которая принимает SQLiteConnection вместо SupportSQLiteDatabase . Предполагается, что эти функции будут переопределены при миграции в проект KMP. Для получения дополнительной информации о миграции использования Room в приложении Android в общий модуль KMP см. руководство по миграции . Функции обратного вызова:
    • Migration.migrate(SQLiteConnection)
    • AutoMigrationSpec.onPostMigrate(SQLiteConnection)
    • RoomDatabase.Callback.onCreate(SQLiteConnection)
    • RoomDatabase.Callback.onDestructiveMigration(SQLiteConnection)
    • RoomDatabase.Callback.onOpen(SQLiteConnection)
  • Артефакт KTX androidx.room:room-ktx был объединен с androidx.room:room-runtime вместе со всеми его API, поэтому артефакт теперь пуст. Пожалуйста, удалите его из списка зависимостей.

Версия 2.6

Версия 2.6.1

29 ноября 2023 г.

Выпущена версия androidx.room:room-*:2.6.1 . Версия 2.6.1 содержит следующие коммиты.

Исправлены ошибки

  • Исправлена ​​ошибка в сгенерированном коде, из-за которой значение по умолчанию для столбцов типа Double в EntityCursorConverter устанавливалось равным 0 вместо 0.0. Также включено потенциальное исправление аналогичного случая для столбцов типа Float. ( Id75f5 , b/304584179 )
  • Теперь исключения, возникающие при загрузке данных из PagingSource , будут передаваться как LoadStateUpdate объекта LoadResult.Error , содержащего Throwable. Это состояние ошибки можно отслеживать с помощью PagingDataAdapter.loadStateFlow(Views) или LazyPagingItems.loadState(Compose) . Обратите внимание, что это знаменует собой изменение поведения, тогда как раньше ошибки загрузки всплывали как исключение, выбрасываемое методом DAO, который инициировал загрузку. ( I93887 , b/302708983 )

Версия 2.6.0

18 октября 2023 г.

Выпущена версия androidx.room:room-*:2.6.0 . Версия 2.6.0 содержит следующие коммиты.

Важные изменения по сравнению с версией 2.5.0

  • В Room KSP теперь доступна опция включения генерации кода Kotlin (или «Kotlin CodeGen»). ( 4297ec0 ). Чтобы включить Kotlin CodeGen в Room, добавьте имя параметра room.generateKotlin в параметры обработчика для KSP. Более подробную информацию о передаче параметров обработчика для KSP см. в документации KSP .

Примечание: При использовании Kotlin CodeGen важно учитывать дополнительные ограничения. Абстрактные свойства в виде геттеров DAO или запросов DAO в Kotlin CodeGen запрещены и должны быть переписаны как функции, чтобы избежать ложного представления о том, что значение свойства неизменяемо и имеет фиксированный результат хранения. Еще одно добавленное ограничение заключается в том, что возвращаемые типы коллекций, допускающие значение Null, больше не допускаются в Room for Kotlin CodeGen.

Внимание: при использовании Kotlin CodeGen ваши проекты могут быть более строгими в отношении допустимости значений null. В Kotlin CodeGen допустимость значений null для аргументов типа имеет важное значение, тогда как в Java это в основном игнорируется. Например, предположим, у вас есть `Flow`. `Возвращаемый тип `, и таблица пуста. В Java CodeGen это не вызовет никаких проблем, но в Kotlin CodeGen вы получите ошибку. Чтобы избежать этого, вам нужно будет использовать `Flow`. `, предполагая, что испускается нулевой сигнал.

  • В Room добавлен новый артефакт для плагина Room Gradle с идентификатором androidx.room , который решает различные существующие проблемы в Room, связанные с обработкой входных и выходных данных схем через параметры процессора аннотаций Gradle. Более подробную информацию см. в примечаниях к выпуску Room версии 2.6.0-alpha02 .
  • В KSP теперь поддерживаются классы значений в сущностях помещений. ( 4194095 )
  • В Room теперь поддерживаются вложенные возвращаемые типы Map в функциях DAO. ( I13f48 , 203008711 )

Версия 2.6.0-rc01

20 сентября 2023 г.

Выпущена версия androidx.room:room-*:2.6.0-rc01 . Версия 2.6.0-rc01 содержит следующие коммиты.

Версия 2.6.0-beta01

23 августа 2023 г.

Выпущена версия androidx.room:room-*:2.6.0-beta01 . Версия 2.6.0-beta01 содержит следующие коммиты.

Исправлены ошибки

  • Обработка особого случая исключения SQLite , возникающего при выполнении операции upsert, когда во время upsert генерируется исключение 2067 SQLITE_CONSTRAINT_UNIQUE , позволяет выполнить обновление. ( If2849 , b/243039555 )

Версия 2.6.0-alpha03

9 августа 2023 г.

Выпущена версия androidx.room:room-*:2.6.0-alpha03 . Версия 2.6.0-alpha03 содержит следующие коммиты.

Новые функции

  • В Room теперь поддерживаются вложенные возвращаемые типы Map в функциях DAO. ( I13f48 , 203008711 )

Изменения в API

  • Для замены устаревшей аннотации @MapInfo была создана новая аннотация типа @MapColumn . Для каждого имени столбца ( keyColumnName , valueColumnName или оба), указанного в аннотации @MapInfo , необходимо объявить аннотацию @MapColumn указав только имя columnName , и использовать эту аннотацию для конкретного аргумента типа, на который ссылается аннотация (ключ или значение Map) в возвращаемом типе функции DAO. Это связано с тем, что аннотация @MapColumn используется непосредственно для аргумента типа внутри возвращаемого типа функции DAO, а не для самой функции, как @MapInfo . Для получения дополнительной информации обратитесь к документации по @MapColumn . ( Ib0305 , b/203008711 )
  • Обновлены файлы API для аннотирования подавления совместимости ( I8e87a , b/287516207 )
  • API плагина Room Gradle были обновлены, и теперь для каждого варианта не требуется отдельная конфигурация. Это означает, что плагин может принимать глобальное расположение для всех вариантов без создания нескольких каталогов, что обеспечивает более плавную миграцию, но при этом достаточно гибок для ручной настройки вариантов или схем типов сборки, сохраняя при этом преимущества плагина (воспроизводимые и кэшируемые сборки). ( I09d6f , b/278266663 )

Исправлены ошибки

  • Исправлена ​​потенциальная уязвимость утечки памяти в QueryInterceptorStatement . ( I193d1 )
  • Исправлено некорректное поведение функции QueryInterceptorDatabase execSQL() . ( Iefdc8 )

Версия 2.6.0-alpha02

21 июня 2023 г.

Выпущена версия androidx.room:room-*:2.6.0-alpha02 . Версия 2.6.0-alpha02 содержит следующие коммиты.

Плагин Room Gradle

В этом новом релизе содержится новый артефакт для плагина Room Gradle с идентификатором androidx.room , который решает различные существующие проблемы в Room, связанные с обработкой входных и выходных данных схем через параметры процессора аннотаций Gradle. Плагин Room Gradle настраивает проект таким образом, чтобы сгенерированные схемы, используемые для автоматической миграции и являющиеся результатом задач компиляции, были корректно настроены для обеспечения воспроизводимых и кэшируемых сборок. Плагин предлагает DSL для настройки расположения базовой схемы:

room {
    schemaDirectory("$projectDir/schemas/")
}

Затем плагин настроит компилятор Room и различные задачи компиляции, а также его бэкенды (javac, KAPT, KSP) для вывода файлов схем в папки с выбранными вариантами, например, schemas/flavorOneDebug/com.package.MyDatabase/1.json . Как обычно, эти файлы добавляются в репозиторий для использования в целях валидации и автоматической миграции. При переходе на использование плагина вместо параметров обработки аннотаций существующие файлы схем необходимо скопировать в сгенерированные плагином каталоги с вариантами. Это одноразовая операция миграции, которую необходимо выполнить вручную. Документация по схемам на developers.android.com будет обновлена ​​в будущем по мере учета отзывов и достижения плагином стабильной версии, поэтому, пожалуйста, попробуйте его.

Изменения в API

  • RoomDatabase.QueryCallback определен как функциональный интерфейс, позволяющий использовать преобразование SAM. ( Iab8ea , b/281008549 )

Исправлены ошибки

  • Устранение проблемы, возникшей при создании экземпляра базы данных в Robolectric после миграции исходного кода Room с Java на Kotlin. ( Ic053c , b/274924903 )

Версия 2.6.0-alpha01

22 марта 2023 г.

Выпущена версия androidx.room:room-*:2.6.0-alpha01 . Версия 2.6.0-alpha01 содержит следующие коммиты.

Новые функции

  • Поддержка классов значений в Room для KSP. Room теперь может поддерживать классы значений в сущностях. ( 4194095 )
  • В Room теперь можно включить генерацию кода Kotlin (или «Kotlin CodeGen») ( 4297ec0 ). Чтобы включить Kotlin CodeGen в Room, добавьте имя параметра room.generateKotlin в параметры обработчика для KSP. Более подробную информацию о передаче параметров обработчика для KSP см. в документации KSP .

Примечание: При использовании Kotlin CodeGen важно учитывать дополнительные ограничения. Абстрактные свойства в виде геттеров DAO или запросов DAO в Kotlin CodeGen запрещены и должны быть переписаны как функции, чтобы избежать ложного представления о том, что значение свойства неизменяемо и имеет фиксированный результат хранения. Еще одно добавленное ограничение заключается в том, что возвращаемые типы коллекций, допускающие значение Null, больше не допускаются в Room for Kotlin CodeGen.

Внимание: при использовании Kotlin CodeGen ваши проекты могут быть более строгими в отношении допустимости значений null. В Kotlin CodeGen допустимость значений null для аргументов типа имеет важное значение, тогда как в Java это в основном игнорируется. Например, предположим, у вас есть `Flow`. `Возвращаемый тип `, и таблица пуста. В Java CodeGen это не вызовет никаких проблем, но в Kotlin CodeGen вы получите ошибку. Чтобы избежать этого, вам нужно будет использовать `Flow`. `, предполагая, что испускается нулевой сигнал.

Изменения в API

  • Защита от бессмысленного использования коллекций, допускающих значение NULL, в типах возвращаемых значений методов DAO. ( I777dc , b/253271782 , b/259426907 )
  • Добавить API для создания потока, который генерирует изменения в трекере аннулирования. API полезен для создания потоков, которые должны реагировать на изменения в базе данных. ( I8c790 , b/252899305 )

Исправлены ошибки

  • В Kotlin следует запретить использование абстрактных свойств в качестве геттеров DAO или запросов DAO; вместо этого их следует переписать как функции, чтобы избежать ложного представления о том, что значение свойства является неизменяемым и имеет фиксированный результат хранения. ( If6a13 , b/127483380 , b/257967987 )

Версия 2.5.2

Версия 2.5.2

21 июня 2023 г.

Выпущена версия androidx.room:room-*:2.5.2 . Версия 2.5.2 содержит следующие коммиты.

Исправлены ошибки

  • Исправлена ​​проблема несовместимости с kotlinx-metadata-jvm. ( 386d5c )
  • Исправлена ​​ошибка, из-за которой Room выдавал сообщение об ошибке при использовании в тесте Robolectric. ( f79bea , b/274924903 )

Версия 2.5.1

Версия 2.5.1

22 марта 2023 г.

Выпущена версия androidx.room:room-*:2.5.1 . Версия 2.5.1 содержит следующие коммиты.

Исправлены ошибки

  • Избегайте проверки родительского каталога базы данных в FrameworkSQLiteHelper , если база данных уже открыта. ( 5de86b8 )
  • Используйте проверку isOpenInternal при проверке того, открыта ли база данных уже. ( e91fb35 )
  • Better handling of the reentrant case in acquireTransactionThread() of Room is now available. ( 219f98b ). During a suspending transaction, Room uses a thread from the transaction executor, starts an event loop in it and dispatches suspending database operations to it so they are all encapsulated within the transaction coroutine. It is usually expected that the transaction thread is different from the one starting the transaction, but in some cases they are the same. To handle such reentrant cases the withTransaction() has been refactored to no longer rely on a control job and instead it will execute the suspending transaction block from within the runBlocking in the transaction thread.

Версия 2.5.0

Версия 2.5.0

22 февраля 2023 г.

androidx.room:room-paging-guava:2.5.0 , androidx.room:room-paging-rxjava2:2.5.0 , and androidx.room:room-paging-rxjava3:2.5.0 are released. Version 2.5.0 contains these commits.

Версия 2.5.0

11 января 2023 г.

androidx.room:room-*:2.5.0 is released. Version 2.5.0 contains these commits.

Important changes since 2.4.0

  • All of room-runtime sources has been converted from Java to Kotlin. Note that you may encounter source incompatibility issues if your code is in Kotlin due to the library conversion to Kotlin. For example, a known source incompatible change is that in InvalidationTracker you will now need to declare onInvalidate() in Observer to have a param of type Set and not MutableSet . Moreover, certain getter methods were converted to properties requiring the property access syntax on Kotlin files. Please file a bug if there are any significant incompatibilities.
  • Added a new shortcut annotation, @Upsert , which attempts to insert an entity when there is no uniqueness conflict or update the entity if there is a conflict. ( I7aaab , b/241964353 )
  • New room-paging artifacts room-paging-rxjava2 , room-paging-rxjava3 and room-paging-guava have been added for support in Room Paging.
  • Added APIs for providing key and value tables names for disambiguation in @MapInfo ( Icc4b5 )

Version 2.5.0-rc01

December 7, 2022

androidx.room:room-*:2.5.0-rc01 is released. Version 2.5.0-rc01 contains these commits.

  • This release is identical to 2.5.0-beta02 .

Version 2.5.0-beta02

9 ноября 2022 г.

androidx.room:room-*:2.5.0-beta02 is released. Version 2.5.0-beta02 contains these commits.

Изменения в API

  • Fix various APIs that take query arguments from invariant ( Array<Any?> ) to contravariant ( Array<out Any?> ) to match Java's array behavior. ( b/253531073 )

Version 2.5.0-beta01

5 октября 2022 г.

androidx.room:room-*:2.5.0-beta01 is released. Version 2.5.0-beta01 contains these commits.

Изменения в API

  • Restrict the minimum version that supports @Upsert to be API 16. This is due to the inability to identity a primary key constraint conflict in older APIs. ( I5f67f , b/243039555 )

Исправлены ошибки

  • Fixed an issue where shadow tables where incorrectly exported to the schema .json files, corrupting them. ( I4f83b , b/246751839 )

Version 2.5.0-alpha03

24 августа 2022 г.

androidx.room:room-*:2.5.0-alpha03 is released. Version 2.5.0-alpha03 contains these commits.

Новые функции

  • Added a new shortcut annotation, @Upsert , which attempts to insert an entity when there is no uniqueness conflict or update the entity if there is a conflict. ( I7aaab , b/241964353 )

Исправлены ошибки

  • Room will now throw a SQLiteConstraintException instead of a IllegalStateException during an auto-migration foreign key constraint check. ( I328dd )
  • Fix a Kotlin source incompatible change for getter / properties of getOpenHelper , getQueryExecutor and getTransactionExecutor . ( Iad0ac )

Version 2.5.0-alpha02

1 июня 2022 г.

androidx.room:room-*:2.5.0-alpha02 is released. Version 2.5.0-alpha02 contains these commits.

Новые функции

Изменения в API

  • All of room-runtime has been converted from Java to Kotlin. ( If2069 , b/206859668 ),( Ie4b55 , b/206859668 ), ( I697ee , b/206859668 ), ( I96c25 , b/206859668 )

    Note: You may encounter source incompatibility issues due to the library conversion to Kotlin. If your code was in Kotlin and calling the old version of Room, the new version will need to handle these cases. For example, a known source incompatible change is that in InvalidationTracker you will now need to declare onInvalidate() in Observer to have a param of type Set and not MutableSet .

  • Added APIs for providing key and value tables names for disambiguation in @MapInfo ( Icc4b5 )
  • Fix a source compatibility issue to re-allow @Ignore in property getters. ( Ifc2fb )

Исправлены ошибки

  • Duplicate column resolution heuristic algorithm. Room will now attempt to resolve ambiguous columns in a multimap query. This allows for JOINs with tables containing same-name tables to be correctly mapped to a result data object. ( I4b444 , b/201306012 , b/212279118 )

Version 2.5.0-alpha01

23 февраля 2022 г.

androidx.room:room-*:2.5.0-alpha01 is released. Version 2.5.0-alpha01 contains these commits.

Изменения в API

  • Fixed an issue where Room @IntDef usage were not being enforced in Kotlin sources. ( I75f41 , b/217951311 )
  • Fixed a source compatibility issue to re-allow @Query in property getters. ( I0a09b )
  • Converted room-common from Java to Kotlin. ( I69c48 , b/206858235 )

    Note: You may encounter source incompatibility issues as some properties have been moved into companion objects during the library conversion to Kotlin. If your code was in Kotlin and calling the old version of Room, the new version will need the ".Companion" suffix when accessing these properties.

  • Converted room-migration from Java to Kotlin. ( I2724b , b/206858622 )
  • Converted paging related files in room-runtime from Java to Kotlin. ( I82fc8 , b/206859668 )
  • Added API for multi-process lock and usage at the FrameworkSQLite* level, to protect multi-process 1st time database creation and migrations. ( Ied267 , b/193182592 )

Исправлены ошибки

  • Added support for internal properties in Kotlin sources. This is a slight behavior change in Room where it will use the source name of functions while matching them to properties as getters/setters (previously, it was using JVM name of the function which is different for internal functions/properties). If you are using custom @JvmName annotations to match getters/setters to private properties, please double check the generated code after the update ( If6531 , b/205289020 )

Версия 2.4.3

Версия 2.4.3

27 июля 2022 г.

androidx.room:room-*:2.4.3 is released. Version 2.4.3 contains these commits.

Исправлены ошибки

  • Fixed an issue that would cause Room to not recognize suspend functions in Kotlin 1.7 ( b/236612358 )

Версия 2.4.2

Версия 2.4.2

23 февраля 2022 г.

androidx.room:room-*:2.4.2 is released. Version 2.4.2 contains these commits.

Исправлены ошибки

  • Fix an issue generating code for a Dao @Transaction suspend function with a body that generates a default interface method due to compilation with -Xjvm-default=all or equivalent. ( Ia4ce5 )
  • Resolving a bug where Room generates code for a Array<ByteArray> return type query method. ( If086e , b/213789489 )

Версия 2.4.1

Версия 2.4.1

12 января 2022 г.

androidx.room:room-*:2.4.1 is released. Version 2.4.1 contains these commits.

Исправлены ошибки

  • Added support for internal properties in Kotlin sources. This is a slight behavior change in Room where it will use the source name of functions while matching them to properties as getters/setters (previously, it was using JVM name of the function which is different for internal functions/properties). If you are using custom @JvmName annotations to match getters/setters to private properties, please double check the generated code after the update ( If6531 , b/205289020 )

Version 2.4.0

Version 2.4.0

15 декабря 2021 г.

androidx.room:room-*:2.4.0 is released. Version 2.4.0 contains these commits.

Important changes since 2.3.0

  • Auto Migrations : Room now offers an API for automatically generating migrations as long as schemas are exported. To let Room know that it should generate an auto-migration a new property @Database#autoMigrations can be used to declare the versions to auto-migrate from and to. When Room needs additional information regarding tables and column renames or deletes, then the @AutoMigration annotation can declare a specification class containing such inputs. See the @AutoMigration documentation for more details.
  • Dependency Injection in Auto Migrations : @ProvidedAutoMigrationSpec is a new API for declaring that an AutoMigrationSpec will be provided at runtime via RoomDatabase.Builder#addAutoMigrationSpec() . This allows for a dependency injection framework to provide such specs when they need complex dependencies.
  • Migration Test Helper Support for Auto Migrations : Room's MigrationTestHelper was updated to support auto migrations by providing a new constructor API that receives the database class under test. This allows the helper to automatically add auto migrations the same way during runMigrationsAndValidate .
  • Room-Paging Support : androidx.room:room-paging is released, providing native Paging 3.0 support for Room queries returning androidx.paging.PagingSource .
  • Relational Query Methods : Room now supports multimap return types @Dao methods, useful for JOIN statements. The supported types of multimaps are Map , SparseArray , LongSparseArray , along with Guava's ImmutableMap , ImmutableSetMultimap and ImmutableListMultimap .

Version 2.4.0-rc01

1 декабря 2021 г.

androidx.room:room-*:2.4.0-rc01 is released. Version 2.4.0-rc01 contains these commits.

Новые функции

  • Update Room's dependency on KSP to 1.6.0-1.0.1 to support Kotlin 1.6

Version 2.4.0-beta02

17 ноября 2021 г.

androidx.room:room-*:2.4.0-beta02 is released. Version 2.4.0-beta02 contains these commits.

Новые функции

  • We've added support for SparseArray and LongSparseArray in @MapInfo. ( Ic91a2 b/138910317 )

Исправлены ошибки

  • We've added a new TypeConverter analyzer that takes nullability information in types into account. As this information is only available in KSP, it is turned on by default only in KSP. If it causes any issues, you can turn it off by passing room.useNullAwareTypeAnalysis=false to the annotation processor. If that happens, please a file bug as this flag will be removed in the future. With this new TypeConverter analyzer, it is suggested to only provide non-null receiving TypeConverters as the new analyzer has the ability to wrap them with a null check. Note that this has no impact for users using KAPT or Java as the annotation processors (unlike KSP), don't have nullability information in types. ( Ia88f9 , b/193437407 )
  • Fix a bug where Room would fail to compile with a SQL error when an FTS entity declared to use the ICU tokenizer. ( I00db9 , b/201753224 )
  • Resolved issue in auto migrations regarding a new column added to an embedded Entity between versions. ( I5fcb1 b/193798291 )
  • We have resolved an issue regarding the relational query method return types in LEFT JOIN queries. With these changes, in the case where a 1-many mapping is present, the collection returned for a key will not include the invalid value object if it is not found in the cursor. If no valid values are found, then a key will be mapped to an empty collection. ( Id5552 b/201946438 )
  • Resolved the auto migration issue where SQLite keywords failed to be escaped in column names. ( Idbed4 b/197133152 )

Version 2.4.0-beta01

13 октября 2021 г.

androidx.room:room-*:2.4.0-beta01 is released. Version 2.4.0-beta01 contains these commits.

Исправлены ошибки

  • Fixed an issue with auto-migrations not adding new columns when another table in the same auto-migration also had a new column with the same name. ( Ia5db5 , b/200818663 )
  • The PagingSource implementation generated by room-paging now uses the queryExecutor passed through RoomDatabase.Builder , so it can be overridden, instead of Dispatchers.IO previously. ( Iae259 )

Version 2.4.0-alpha05

29 сентября 2021 г.

androidx.room:room-*:2.4.0-alpha05 is released. Version 2.4.0-alpha05 contains these commits.

Новые функции

Изменения в API

  • Added a new property to the TypeConverters annotation to let developers disable built-in Enum and UUID converters. By default, these converters are on but you can disable them for a certain scope, or for the whole database. See TypeConverters documentation for details. ( 36ae9e , b/195413406 )

  • Supporting non-POJO keys/values for Multimap return types in DAOs via the @MapInfo annotation. ( I4d704 )

@MapInfo will be required when the key or value column of the map are from a single column. See example:

@MapInfo(valueColumn = "songCount")
@Query("""
       SELECT *, COUNT(mSongId) as songCount
       FROM Artist JOIN Song ON Artist.artistName = Song.artist
       GROUP BY artistName
       """)
fun getArtistAndSongCounts(): Map<Artist, Integer>
  • Make room-paging a required artifact when using Paging3 with Room. ( Ieaffe )

Исправлены ошибки

  • Fix an issue where multimap queries results were not correctly ordered when the query contained an ORDER BY clause of a column from the map's key. ( I6b887 )

Внешний вклад

  • Added new API to specify index order in @Index. Thanks to Nikita Zhelonkin. ( I033fc )

Version 2.4.0-alpha04

21 июля 2021 г.

androidx.room:room-*:2.4.0-alpha04 is released. Version 2.4.0-alpha04 contains these commits.

Новые функции

  • Room now supports multimap return types @Dao methods, useful for JOIN statements. The supported types of multimaps are Map along with Guava's ImmutableMap , ImmutableSetMultimap and ImmutableListMultimap .

    The following are examples of multimap queries:

    One-to-One Relation Map

    @Query("SELECT * FROM Song JOIN Artist ON Song.artistId = Artist.artistId")
    fun getSongAndArtist(): Map<Song, Artist>
    

    One-to-Many Relation Map (Standard multimap)

    @Query("SELECT * FROM Artist JOIN Album ON Artist.id = Album.artistId")
    fun getArtistAndAlbums(): Map<Artist, List<Album>>
    

    The multimap result can also be wrapped in the supported async return types, such as LiveData , Rx's Observable , or coroutines Flow .

Room-Paging

  • androidx.room:room-paging is released, providing native Paging 3.0 support for Room queries returning androidx.paging.PagingSource .

    @Dao
    interface UserDao {
      @Query("SELECT * FROM users ORDER BY id ASC")
      fun loadUsers(): PagingSource<Int, User>
    }
    
  • This artifact replaces the androidx.paging.PagingSource implementation generated by Room with one built on top of Paging 3.0 APIs. The new PagingSource implementation parses keys differently, so any key manually supplied to Room's PagingSource would need to account for this behavior change, including the initialKey passed via Pager's constructor. Pages will start loading from the Key with Key being the first loaded item. This deviates from existing behavior where LoadParams.Refresh.Key is treated as the user's scroll position and items are loaded both before and after the key.

  • The artifact is optional and opting out will fallback to existing support for Paging 3.0 that was introduced in Room 2.3. However, this artifact will become non-optional in future release for those using Room with Paging 3.0. To opt-in, add the new room-paging artifact to your classpath. If you are using Gradle, you can add the following snippet to your build.gradle:

    dependency {
      implementation("androidx.room:room-paging:2.4.0-alpha04")
    }
    

Исправлены ошибки

  • Fix an issue in auto migrations regarding handling foreign key violations. ( b/190113935 )

Version 2.4.0-alpha03

16 июня 2021 г.

androidx.room:room-*:2.4.0-alpha03 is released. Version 2.4.0-alpha03 contains these commits.

Изменения в API

  • Update Room's MigrationTestHelper to support auto migrations by providing a new constructor API that receives the database class under test. This allows the helper to automatically add auto migrations the same way during runMigrationsAndValidate .

Исправлены ошибки

  • Fixed an issue with Room's SQLite native library to support Apple's M1 chips. ( b/174695268

  • Fixed an issue where Room would not error out when the return type of a @Transaction function was a Flow ( I56ddd , b/190075899 )

  • Fix an issue in auto migrations regarding indices. b/177673291

Обновления зависимостей

  • Room's KSP support now depends on KSP 1.5.10-1.0.0-beta01 . ( 1ecb11 , b/160322705 )

Version 2.4.0-alpha02

5 мая 2021 г.

androidx.room:room-*:2.4.0-alpha02 is released. Version 2.4.0-alpha02 contains these commits.

Изменения в API

  • @ProvidedAutoMigrationSpec is a new API for declaring that an AutoMigrationSpec will be provided at runtime via RoomDatabase.Builder#addAutoMigrationSpec() . This allows for a dependency injection framework to provide such specs when they need complex dependencies.

Исправлены ошибки

  • Fix an issue with auto migrations where @DatabaseView s where not being properly re-created.

Внешний вклад

  • Fix an issue in Room's JournalMode.TRUNCATE where the InvalidationTracker callback was sometimes being invoked invalidly, too late, or not at all. Thanks to Uli Bubenheimer | bubenheimer@users.noreply.github.com ( b/154040286 )

Version 2.4.0-alpha01

21 апреля 2021 г.

androidx.room:room-*:2.4.0-alpha01 is released. Version 2.4.0-alpha01 contains these commits.

Новые функции

  • Auto Migrations : Room now offers an API for automatically generating migrations as long as schemas are exported. To let Room know that it should generate an auto-migration a new property @Database#autoMigrations can be used to declare the versions to auto-migrate from and to. When Room needs additional information regarding tables and column renames or deletes, then the @AutoMigration annotation can declare a specification class containing such inputs. See the @AutoMigration documentation for more details.

Исправлены ошибки

  • Fix an issue where defaultValue with extra parenthesis were being incorrectly validated by Room's schema validation. b/182284899

Версия 2.3.0

Версия 2.3.0

21 апреля 2021 г.

androidx.room:room-*:2.3.0 is released. Version 2.3.0 contains these commits.

Important changes since 2.2.0

  • Built-in Enum Support : Room will now default to using an Enum to String and vice versa type converter if none is provided. If a type converter for an enum already exists, Room will prioritize using it over the default one.
  • Query Callback : Room now offers a general callback API RoomDatabase.QueryCallback, for when queries are about to execute, which can be useful for logging in debug builds. The callback can be set via RoomDatabase.Builder#setQueryCallback() .
  • Pre-packaged Improvement : Room now has APIs for creating a database using a pre-packaged database read from an input stream. This allows for cases such as when the pre-package database is gzipped.
  • Provided Type Converters : Room now has APIs for providing instances of type converters such that the app can control their initialization. To mark a type converter that will be provided to Room use the new annotation @ProvidedTypeConverter.
  • RxJava3 Support : Room now supports RxJava3 types. Similar to RxJava2 you can declare DAO methods whose return type are Flowable, Single, Maybe and Completable. Additionally a new artifact androidx.room:room-rxjava3 is available to support RxJava3.
  • Paging 3.0 Support : Room will now support generating implementations for @Query annotated methods whose return type is androidx.paging.PagingSource .

Version 2.3.0-rc01

March 24, 2021

androidx.room:room-*:2.3.0-rc01 is released. Version 2.3.0-rc01 contains these commits.

Исправлены ошибки

  • Fix an issue that prevented Coroutine Flow queries created by Room to be consumed in a suspending withTransaction block. ( I797bf )

Version 2.3.0-beta03

10 марта 2021 г.

androidx.room:room-*:2.3.0-beta03 is released. Version 2.3.0-beta03 contains these commits.

Новые функции

Исправлены ошибки

  • Fixed a bug where creating PagingSource on the main thread could trigger an ANR. ( I42b74 , b/181221318 )
  • Fixed @ExperimentalRoomApi visibility to be public instead of package private. ( b/181356119 )

Внешний вклад

  • Allow Room to accept a POJO return type in a @Query annotated DAO method when it is also annotated with @SkipQueryVerification . Room will do a best-effort to convert the result of the query to the POJO return type the same way it is done for a @RawQuery annotated DAO method. Thanks to 'Markus Riegel | hey@marcorei.com'. ( I45acb )

Version 2.3.0-beta02

18 февраля 2021 г.

androidx.room:room-*:2.3.0-beta02 is released. Version 2.3.0-beta02 contains these commits.

Новые функции

  • Room now has experimental support for Kotlin Symbol Processing KSP .

    KSP is a replacement for KAPT to run annotation processors natively on the Kotlin compiler, significantly reducing build times.

    To use Room with KSP, you can apply the KSP Gradle plugin and replace the kapt configuration in your build file with ksp . For example, instead of kapt 'androidx.room:room-compiler:2.3.0-beta02' use ksp 'androidx.room:room-compiler:2.3.0-beta02' . See the KSP documentation for more details.

    Note that since KSP is experimental, it is recommended to still use KAPT for production code. The reduction of build times is only applicable if there are no other processors that use KAPT. See b/160322705 for known issues.

Version 2.3.0-beta01

27 января 2021 г.

androidx.room:room-*:2.3.0-beta01 is released. Version 2.3.0-beta01 contains these commits.

Новые функции

  • Auto Closable Databases : Room now has the ability to close databases that are not accessed after a given amount of time. This is an experimental feature and can be enabled by calling RoomDatabase.Builder#setAutoCloseTimeout() . This feature is useful for applications with multiple databases.

Исправлены ошибки

  • Fix an issue where Dao methods with multiple @Update or @Delete methods with different conflict strategies would generate code with only one of the strategies, effectively ignoring the defined one. ( /I0b90d , b/176138543 )

Version 2.3.0-alpha04

16 декабря 2020 г.

androidx.room:room-*:2.3.0-alpha04 is released. Version 2.3.0-alpha04 contains these commits.

Новые функции

  • Room now offers a general callback API RoomDatabase.QueryCallback , for when queries are about to execute, which can be useful for logging in debug builds. The callback can be set via RoomDatabase.Builder#setQueryCallback() . ( Iaa513 , b/174478034 , b/74877608 )
  • Room will now default to using an Enum to String and vice versa type converter if none is provided. If a type converter for an enum already exists, Room will prioritize using it over the default one. ( b/73132006 )

Известная проблема

  • If a one-way type converter for reading already exists for the Enum, Room might accidentally use the built-in String to Enum converter which might not be desired. This is a known issue and can be fixed by making it a two-way converter. See: b/175707691

Исправлены ошибки

  • Fixed an issue where Room would incorrectly disabled incremental annotation processing in newer JDK versions. ( b/171387388 )
  • Fixed an issue with Room finding the generated class when multiple class loaders are used. Thanks for the fix 'Serendipity | 892449346@qq.com'! ( b/170141113 )
  • Fixed an issue where Room would generate incorrect code when a Kotlin @Dao had a base class whose generics are primitives in the JVM. ( b/160258066 )

Внешний вклад

  • Room will now default to using beginTransactionNonExclusive if WAL mode is enabled and API is 16 or more. Thanks to 'Ahmed I. Khalil | ahmedibrahimkhali@gmail.com'! ( b/126258791 )

Version 2.3.0-alpha03

October 14, 2020

androidx.room:room-*:2.3.0-alpha03 is released. Version 2.3.0-alpha03 contains these commits.

Новые функции

  • Room now has APIs for providing instances of type converters such that the app can control their initialization. To mark a type converter that will be provided to Room use the new annotation @ProvidedTypeConverter . Thanks to 'mzgreen yairobbe@gmail.com '. ( Ie4fa5 , b/121067210 )

  • Room now has APIs for creating a database using a pre-packaged database read from an input stream. This allows for cases such as when the pre-package database is gzipped. Thanks to 'Ahmed El-Helw ahmedre@gmail.com ' ( 3e6792 , b/146911060 )

Изменения в API

  • Added missing target to @ForeignKey annotation preventing its usage outside of the @Entity annotation. ( Iced1e )

  • The field mCallbacks in RoomDatabase.java is now hidden. ( d576cb , b/76109329 )

Исправлены ошибки

  • Update to TypeConverters documentation to clarify that TypeConverters can only be used to convert columns / fields and not rows. ( I07c56 , b/77307836 )

  • Update to the DaoProcessor to fix compiler error on Dao with a generic super type with Kotlin "primitives". ( Ice6bb , b/160258066 )

  • Update add/remove observer methods documentation to clarify threading ( Ifd1d9 , b/153948821 )

  • Fix an issue with Room incorrectly validating FTS tables that declared their rowid column. ( d62ebc , b/145858914 )

External Contributions

  • Fix upper/lowercase locale issues related to Turkish ( 5746e3 ), b/68159494

  • Replace the ConcurrentHashMap inside RoomDatabase with Collections.synchronizedMap() to avoid issues on Android Lollipop ( d1cfc7 , b/162431855 )

  • Add a onOpenPrepackagedDatabase callback for when a prepackaged DB is copied. ( I1ba74 , b/148934423 )

Version 2.3.0-alpha02

22 июля 2020 г.

androidx.room:room-*:2.3.0-alpha02 is released. Version 2.3.0-alpha02 contains these commits.

Новые функции

  • RxJava3 Support : Room now supports RxJava3 types. Similar to RxJava2 you can declare DAO methods whose return type are Flowable, Single, Maybe and Completable. Additionally a new artifact androidx.room:room-rxjava3 is available to support RxJava3. ( b/152427884 )

Изменения в API

  • Declaring a @TypeConverter in Kotlin Object class is now supported. ( b/151110764 )
  • Room incremental annotation processing option is now ON by default. ( b/112110217 )

Version 2.3.0-alpha01

10 июня 2020 г.

androidx.room:room-*:2.3.0-alpha01 is released. Version 2.3.0-alpha01 contains these commits.

Новые функции

  • Paging 3.0 Support : Room will now support generating implementations for @Query annotated methods whose return type is androidx.paging.PagingSource .

    @Dao
    interface UserDao {
      @Query("SELECT * FROM users ORDER BY id ASC")
      fun pagingSource(): PagingSource<Int, User>
    }
    

Изменения в API

  • @RewriteQueriesToDropUnusedColumns is a new convenient annotation that makes Room rewrite the '*' projection in a query such that unused columns in the result are removed.
  • The processor option room.expandProjection is now deprecated. Use @RewriteQueriesToDropUnusedColumns as a replacement for Room optimizing queries with star projections. Note that @RewriteQueriesToDropUnusedColumns does not replace the column conflict solution room.expandProjection offered with regards to return types that contained @Embedded fields.

Исправлены ошибки

  • Fixed a bug where Room would not correctly detect the JDK version used to enable incremental annotation processor. Thanks to Blaz Solar (me@blaz.solar) ( b/155215201 )
  • Room now embeds its ANTLR dependency with the annotation processor to avoid version conflicts with other processors that also use ANTLR. ( b/150106190 )

Version 2.2.6

Version 2.2.6

16 декабря 2020 г.

androidx.room:room-*:2.2.6 is released. Version 2.2.6 contains these commits.

Исправлены ошибки

  • Fixed an issue where Room would incorrectly disabled incremental annotation processing in newer JDK versions. ( b/171387388 )

Версия 2.2.5

Версия 2.2.5

18 марта 2020 г.

androidx.room:room-*:2.2.5 is released. Version 2.2.5 contains these commits.

Исправлены ошибки

  • Make MultiInstanceInvalidationService directBootAware. Thanks to 'Mygod contact-git@mygod.be ' ( b/148240967 )
  • Fixed a bug that would cause a crash when multi-instance invalidation was enabled and the database contained a FTS entity. ( b/148969394 )
  • Fixed an issue when loading the SQLite native libraries in the Room annotation processor that would cause the compiler to crash due to parallel compilations. ( b/146217083 )

Version 2.2.4

Version 2.2.4

19 февраля 2020 г.

androidx.room:room-common:2.2.4 , androidx.room:room-compiler:2.2.4 , androidx.room:room-guava:2.2.4 , androidx.room:room-ktx:2.2.4 , androidx.room:room-migration:2.2.4 , androidx.room:room-runtime:2.2.4 , androidx.room:room-rxjava2:2.2.4 , and androidx.room:room-testing:2.2.4 are released. Version 2.2.4 contains these commits.

Исправлены ошибки

  • Fixed an issue with suspending transactions where they would deadlock if the coroutine was canceled quickly before the transaction actually started. ( b/148181325 )
  • Fixed an issue with the @Generated being wrongly used when building with JDK 9. ( b/146538330 )
  • Fixed an issue where Room would generate incorrect code when a DAO interface in Kotlin had a concrete function. ( b/146825845 )

Version 2.2.3

Version 2.2.3

18 декабря 2019 г.

androidx.room:room-*:2.2.3 is released. Version 2.2.3 contains these commits .

Исправлены ошибки

  • Fixed a bug where Room would fail to validate a database that had not gone through any migration and contained a legacy hash with indices in its schema. ( b/139306173 )

Версия 2.2.2

Версия 2.2.2

20 ноября 2019 г.

androidx.room:room-*:2.2.2 is released. Version 2.2.2 contains these commits .

Исправлены ошибки

  • Fixed a bug where collecting a one-to-one relationship with more than 999 rows would cause Room to return null relating items. ( b/143105450 )

Version 2.2.1

Version 2.2.1

23 октября 2019 г.

androidx.room:room-*:2.2.1 is released. Version 2.2.1 contains these commits .

Исправлены ошибки

  • Fixed a bug where Room would incorrectly warn about CURSOR_MISMATCH with the compiler option expandProjection turned ON. ( b/140759491 )
  • Added a retry mechanism for handling the missing native library used for verifying queries during compile time.

Version 2.2.0

Version 2.2.0

October 9, 2019

androidx.room:room-*:2.2.0 is released. Version 2.2.0 contains these commits .

Important changes since version 2.1.0

  • Pre-packaged Database : Two new APIs in RoomDatabase.Builder are now available for creating a RoomDatabase given an already populated database file. createFromAsset() is for when the pre-populated database file is in the assets folder of the APK, while createFromFile() is for when the file is in an arbitrary location. The usages of these API change the behaviour of destructive migrations such that during a fallback migration, Room will try to re-copy the pre-populated database if available, otherwise it fallbacks to just dropping and re-creating all tables. b/62185732
  • Schema Default Values : @ColumnInfo now has a new property defaultValue that can be used to specify the default value of a column. Default values are part of a database schema and will be validated during migrations if specified. b/64088772
  • Many-to-Many Relations : @Relation now has a new property associateBy , that takes in a new annotation @Junction , used to declare a relation that needs to be satisfied via a junction table (also known as a join table). b/69201917
  • One-to-One Relations : The restriction in POJO fields annotated with @Relation to be of type List or Set has been lifted, effectively allowing single-value relations to be represented. b/62905145
  • Target Entity : The DAO annnotations @Insert , @Update and @Delete now has a new property targetEntity , that allows specifying the target table the DAO method is meant to act on. This allows for the parameters of those DAO methods to be arbitrary POJOs which will be interpreted as partial entities. In practice, this allows partial inserts, deletes and updates. b/127549506
  • Coroutines Flow : @Query DAO methods can now be of return type Flow<T> . The returned Flow will re-emit a new set of values if the observing tables in the query are invalidated. Declaring a DAO function with a Channel<T> return type is an error, Room instead encourages you to use Flow and then use the neighboring functions to convert the Flow into a Channel . b/130428884
  • Gradle Incremental Annotation Processor : Room is now a Gradle isolating annotation processor and incrementability can be enabled via the processor option room.incremental . See Room Compiler Options for more information. If you encounter any issues please file a bug here . We plan to enable incrementability by default in a future, stable version. b/112110217
  • Expanding Projections : A new experimental compiler option room.expandProjection was added that causes Room to rewrite a query with a star projection to only contain the columns in the returning type POJO. For example, for a DAO method with @Query("SELECT * FROM Song") that returns a POJO named SongIdAndTitle with only two fields. Then Room will rewrite the query to SELECT id, title FROM Song such that the minimum set of columns to satisfy the return type are fetched. This essentially eliminates the CURSOR_MISMATCH warning that is presented when the query returns extra columns that do not match any field in the returning POJO type.

Version 2.2.0-rc01

5 сентября 2019 г.

androidx.room:room:2.2.0-rc01 is released. The commits included in this version can be found here .

No public changes since Room 2.2.0-beta01 .

Version 2.2.0-beta01

August 22, 2019

androidx.room:room-*:2.2.0-beta01 is released. The commits included in this version can be found here .

Исправлены ошибки

  • Fixed a bug where a Coroutine Flow query would stop reemitting new values after a certain time. ( b/139175786 )
  • Fixed a bug where Room would not accept a legacy schema hash code while opening a database that had not gone a migration since Room 1.0, causing a runtime crash due to invalid schema. ( b/139306173 )

Version 2.2.0-alpha02

7 августа 2019 г.

androidx.room:room-*:2.2.0-alpha02 is released. The commits included in this version can be found here .

Новые функции

  • Coroutines Flow : @Query DAO methods can now be of return type Flow<T> . The returned Flow will re-emit a new set of values if the observing tables in the query are invalidated. Declaring a DAO function with a Channel<T> return type is an error, Room instead encourages you to use Flow and then use the neighboring functions to convert the Flow into a Channel . b/130428884
  • Expanding Projections : A new experimental compiler option room.expandProjection was added that causes Room to rewrite a query with a star projection to only contain the columns in the returning type POJO. For example, for a DAO method with @Query("SELECT * FROM Song") that returns a POJO named SongIdAndTitle with only two fields. Then Room will rewrite the query to SELECT id, title FROM Song such that the minimum set of columns to satisfy the return type are fetched. This essentially eliminates the CURSOR_MISMATCH warning that is presented when the query returns extra columns that do not match any field in the returning POJO type.
  • onDestructiveMigrate is a new callback API added to RoomDatabase.Callback for when Room destructively migrates a database. b/79962330

Исправлены ошибки

  • Fixed a bug where Room would generate incorrect code using a method as field setter when the field is protected. b/136194628
  • Fixed a bug that caused the InvalidationTracker to throw a NPE in a second process when multi-instance invalidation was enabled and the invalidation Service was killed. b/137454915
  • Fixed a bug where Room would not correctly identify the return type of an inherited suspend function annotated with @RawQuery . b/137878827
  • Updated the generated code for @Relation when the relating key is of type BLOB to use a ByteBuffer that is comparable. b/137881998
  • Fixed a bug where Room would complain about missing setters on POJOs used as partial entity parameters of @Insert , @Update and @Delete . b/138664463
  • Fixed a bug where Room would complain about missing getters & setters for an ignored column via @Entity when the entity class was used in certain DAO methods. b/138238182
  • Fixed a bug where Room would not correctly convert named binding args to positional args causing a runtime exception when executing a query with re-used parameters. b/137254857

Version 2.2.0-alpha01

10 июля 2019 г.

Новые функции

  • Pre-packaged Database : Two new APIs in RoomDatabase.Builder are now available for creating a RoomDatabase given an already populated database file. createFromAsset() is for when the pre-populated database file is in the assets folder of the APK, while createFromFile() is for when the file is in an arbitrary location. The usages of these API change the behaviour of destructive migrations such that during a fallback migration, Room will try to re-copy the pre-populated database if available, otherwise it fallbacks to just dropping and re-creating all tables. b/62185732
  • Schema Default Values : @ColumnInfo now has a new property defaultValue that can be used to specify the default value of a column. Default values are part of a database schema and will be validated during migrations if specified. b/64088772

    Note: If your database schema already has default values, such as those added via ALTER TABLE x ADD COLUMN y INTEGER NOTNULL DEFAULT z , and you decide to define default values via @ColumnInfo to the same columns, then you might need to provide a migration to validate the unaccounted default values. See Room Migrations for more information.

  • Many-to-Many Relations : @Relation now has a new property associateBy , that takes in a new annotation @Junction , used to declare a relation that needs to be satisfied via a junction table (also known as a join table). b/69201917
  • One-to-One Relations : The restriction in POJO fields annotated with @Relation to be of type List or Set has been lifted, effectively allowing single-value relations to be represented. b/62905145
  • Target Entity : The DAO annnotations @Insert , @Update and @Delete now has a new property targetEntity , that allows specifying the target table the DAO method is meant to act on. This allows for the parameters of those DAO methods to be arbitrary POJOs which will be interpreted as partial entities. In practice, this allows partial inserts, deletes and updates. b/127549506
  • Gradle Incremental Annotation Processor : Room is now a Gradle isolating annotation processor and incrementability can be enabled via the processor option room.incremental . See Room Compiler Options for more information. If you encounter any issues please file a bug here . We plan to enable incrementability by default in a future, stable version. b/112110217

Исправлены ошибки

  • Room will no longer propagate the EmptySetResultException to the global error handler when the Rx stream of a query has been disposed before the query is complete. b/130257475
  • Fixed a bug where Room would show an incorrect error message when a suspend DAO function annotated with @RawQuery didn't have a return type. b/134303897
  • Room will no longer generate DAO adapters with raw types. b/135747255

Версия 2.1.0

Версия 2.1.0

13 июня 2019 г.

Room 2.1.0 is released with no changes from 2.1.0-rc01 . The commits included in the version can be found here .

Important changes since 2.0.0

  • FTS : Room now supports entities with a mapping FTS3 or FTS4 table. Classes annotated with @Entity can now be additionally annotated with @Fts3 or @Fts4 to declare a class with a mapping full-text search table. FTS options for further customization are available via the annotation's methods.
  • Views : Room now supports declaring a class as a stored query, also known as a view , using the @DatabaseView annotation.
  • Couroutines : DAO methods can now be suspend functions. Include room-ktx in your dependencies to take advantage of this functionality. The ktx artifact also provides the extension function RoomDatabase.withTransaction for performing database transactions within a coroutine.
  • Auto Value : Room now supports declaring AutoValue annotated classes as entities and POJOs. The Room annotations @PrimaryKey , @ColumnInfo , @Embedded and @Relation can now be declared in an auto value annotated class's abstract methods. Note that these annotation must also be accompanied by @CopyAnnotations for Room to properly understand them.
  • Additional Async Support : DAO methods annotated with @Insert , @Delete or @Update , along with @Query containing INSERT , DELETE or UPDATE statements, now support Rx return types Completable , Single , Maybe , and Guava's return type ListenableFuture , and they can also be suspend functions.
  • enableMultiInstanceInvalidation is a new API in RoomDatabase.Builder to enable invalidation across multiple instances of RoomDatabase using the same database file.
  • fallbackToDestructiveMigrationOnDowngrade is a new API in RoomDatabase.Builder to automatically re-create the database if a downgrade happens.
  • ignoredColumns is a new API in the @Entity annotation that can be used to list ignored fields by name.
  • Room will now properly use Kotlin's primary constructor in data classes avoiding the need to declare the properties as vars .

Version 2.1.0-rc01

29 мая 2019 г.

Исправлены ошибки

  • Fixed a Room initialization error that might occur due to an already setup temp_store configuration. b/132602198
  • Fixed a double quote usage warning for users with SQLite 3.27.0 and above. b/131712640
  • Fixed a bug where the InvalidationTracker would cause a crash when multiple invalidation checks would occur in parallel. b/133457594

Version 2.1.0-beta01

7 мая 2019 г.

androidx.room 2.1.0-beta01 is released with no changes from 2.1.0-alpha07. The commits included in this version can be found here .

Version 2.1.0-alpha07

25 апреля 2019 г.

API / Behavior Changes

  • The extension function RoomDatabase.withTransaction has been changed to no longer take a function block with a CoroutineScope as receiver. This prevents skipping the additional coroutineScope { } wrapper required to run things in the transaction block concurrently.

Исправлены ошибки

  • Fixed a bug where Room would fail to match a TypeConverter for a Kotlin DAO function containing a parameter of Collection type. b/122066791

Version 2.1.0-alpha06

22 марта 2019 г.

API / Behavior Changes

  • Async transaction queries are now serialized such that Room will not use more than one thread for executing database transactions. RoomDatabase.Builder.setTransactionExecutor(Executor) was added to allow configuring the executor to be used for transactions.
  • RoomDatabase.runInTransaction(Callable) will no longer wrap checked exceptions into RuntimeExceptions. b/128623748

Исправлены ошибки

  • Fixed a bug where the invalidation tracker would stop observing a content table if observers for both the content table and an external content FTS table were added. b/128508917
  • Updated Room SQLite grammar to match SQLite 3.24.0. b/110883668

Version 2.1.0-alpha05

13 марта 2019 г.

Новые функции

  • The extension function RoomDatabase.withTransaction allows you to safely perform database transactions within a coroutine. Room extensions functions along with coroutines support are available in the room-ktx artifact.
  • Non-abstract DAO methods annotated with @Transaction can now be suspend functions. b/120241587

API / Behavior Changes

  • The artifact room-coroutines has been renamed to room-ktx following the same naming as other androidx artifacts.
  • beginTransaction , setTransactionSuccessful and endTransaction in RoomDatabase have been deprecated in favor of runInTransaction and the room-ktx extension function withTransaction .

Исправлены ошибки

  • Fixed a bug where tokenizer arguments were being dropped if the tokenizer used was SIMPLE. b/125427014
  • Fixed a bug where Room would fail to correctly identify suspending functions with parameters whos type were an inner class. b/123767877
  • Fixed a bug where deferred @Query DAO method with INSERT , UPDATE or DELETE statements were eagerly preparing the query in the main thread. b/123695593
  • Fixed various bugs where Room would generate incorrect code for certain suspend functions. b/123466702 and b/123457323
  • Fixed a bug where deprecated usage of methods were not being correctly suppressed in generated code. b/117602586
  • Updated Room dependency of androidx.sqlite to 1.0.2 which contain fixes for correctly handling corrupted databases. b/124476912

Известные проблемы

  • Room 2.1.0-alpha05 depends on the kotlinx-metadata-jvm artifact which is not currently available in Maven Central ( KT-27991 ). This dependency can be resolved by adding maven { url "https://kotlin.bintray.com/kotlinx/" } to your project repositories.

Version 2.1.0-alpha04

25 января 2019 г.

Новые функции

  • DAO methods annotated with @Query containing INSERT , UPDATE or DELETE statements can now return async types Single , Mayble , Completable and ListenableFuture . Additionally they can also be suspend functions. b/120227284

API / Behavior Changes

  • Room will now throw an error if a non-abstract DAO method annotated with @Transaction returns an async type such as Single , Mayble , Completable , LiveData or ListenableFuture . Since transactions are thread confined it is currently impossible for Room to begin and end a transaction around a function that may peform queries in different threads. b/120109336
  • OnConflictStrategy.FAIL and OnConflictStrategy.ROLLBACK have been @Deprecated since they do not behave as intended with Android's current SQLite bindings. b/117266738

Исправлены ошибки

  • Fixed a bug where Room wouldn't correctly use the TypeConverter of a return type if the DAO method was a suspend function. b/122988159
  • Fixed a bug where Room would incorrectly identify inherited suspend functions as non-suspending. b/122902595
  • Fixed a bug where Room would generate incorrect code when an @Embedded field was in a parent class and used in multiple child classes. b/121099048
  • Fixed an issue where the database would deadlock when invoking DAO suspend functions between a beginTransaction() and endTransaction() . b/120854786

Version 2.1.0-alpha03

4 декабря 2018 г.

Изменения в API

  • The FTS tokenizer in @Fts3 / @Fts4 now takes a String instead of an Enum. This allows custom tokenizers to be used by Room. Built-in tokenizers are still defined in FtsOptions as string constants. b/119234881

Новые функции

  • Couroutines : DAO methods can now be suspend functions. To support suspend functions in Room a new artifact has been released, room-coroutines . b/69474692
  • DAO methods annotated with @Insert , @Delete or @Update now support ListenableFuture as return type. b/119418331

Исправлены ошибки

  • Fixed a bug where Room would incorrectly attempt to find a constructor with columns in the ignoredColumns property of @Entity . b/119830714
  • Fixed a bug where Room would not mark DAO method parameters as final in their generated implementation. b/118015483
  • Fixed a bug where Room processor would crash when reporting an error on a query with special symbols. b/119520136
  • Fixed a bug where Room would decline other various Collection implementations as arguments of an IN expression. b/119884035
  • Fixed a bug where LiveData returned from Room would get garbage collected when observed forever causing it to no longer emit new data. b/74477406
  • Updated RoomDatabase 's close lock to reduce lock contention. b/117900450

Version 2.1.0-alpha02

30 октября 2018 г.

Новые функции

  • Added support for referencing a @DatabaseView in a @Relation . b/117680932

Исправлены ошибки

  • Fixed a bug where Room would perform disk I/O in the main thread when subscribing and disposing from an Rx return type. b/117201279
  • Fixed a bug where Room would fail to find an appropriate type converter for a field in a Kotlin entity class. b/111404868
  • Fixed a bug where Room would generate incorrect code for a DAO interface implementation containing a Kotlin default method that has no arguments. b/117527454
  • Updated Room SQLite grammar parser, fixing a performance issue that would cause long build times. b/117401230

Version 2.1.0-alpha01

8 октября 2018 г.

Новые функции

  • FTS : Room now supports entities with a mapping FTS3 or FTS4 table. Classes annotated with @Entity can now be additionally annotated with @Fts3 or @Fts4 to declare a class with a mapping full-text search table. FTS options for further customization are available via the annotation's methods. b/62356416
  • Views : Room now supports declaring a class as a stored query, also known as a view using the @DatabaseView annotation. b/67033276
  • Auto Value : Room now supports declaring AutoValue annotated classes as entities and POJOs. The Room annotations @PrimaryKey , @ColumnInfo , @Embedded and @Relation can now be declared in an auto value annotated class' abstract methods. Note that these annotation must also be accompanied by @CopyAnnotations for Room to properly understand them. b/62408420
  • Additional Rx Return Types Support : DAO methods annotated with @Insert , @Delete or @Update now support Rx return types Completable , Single<T> and Maybe<T> . b/63317956
  • Immutable Types with @Relation : Room previously required @Relation annotated fields to be settable but now they can be constructor parameters.
  • enableMultiInstanceInvalidation : Is a new API in RoomDatabase.Builder to enable invalidation across multiple instances of RoomDatabase using the same database file. This multi-instance invalidation mechanism also works across multiple processes. b/62334005
  • fallbackToDestructiveMigrationOnDowngrade : Is a new API in RoomDatabase.Builder to automatically re-create the database if a downgrade happens. b/110416954
  • ignoredColumns : Is a new API in the @Entity annotation that can be used to list ignored fields by name. Useful for ignoring inherited fields on an entity. b/63522075

API / Behavior Changes

  • mCallback and mDatabase in RoomDatabase are now @Deprecated and will be removed in the next major version of Room. b/76109329

Исправлены ошибки

  • Fixed two issues where Room wouldn't properly recover from a corrupted database or a bad migration during initialization. b/111504749 and b/111519144
  • Room will now properly use Kotlin's primary constructor in data classes avoiding the need to declare the fields as vars . b/105769985

Версия 2.0.0

Версия 2.0.0

1 октября 2018 г.

androidx.room 2.0.0 is released with no changes from 2.0.0-rc01.

Version 2.0.0-rc01

20 сентября 2018 г.

androidx.room 2.0.0-rc01 is released with no changes from 2.0.0-beta01.

Version 2.0.0-beta01

2 июля 2018 г.

API / Behavior Changes

  • Added RoomDatabase.Builder.setQueryExecutor() to allow customization of where queries are run
  • Added RxJava2 Observable support
  • Generated DAO and Database implementations are now final

Исправлены ошибки

  • Specify class/field name in "cannot find getter for field" error b/73334503
  • Fixed RoomOpenHelper backwards compatibility with older versions of Room b/110197391

Pre-AndroidX Dependencies

For the pre-AndroidX versions of Room, include these dependencies:

dependencies {
    def room_version = "1.1.1"

    implementation "android.arch.persistence.room:runtime:$room_version"
    annotationProcessor "android.arch.persistence.room:compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor

    // optional - RxJava support for Room
    implementation "android.arch.persistence.room:rxjava2:$room_version"

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation "android.arch.persistence.room:guava:$room_version"

    // Test helpers
    testImplementation "android.arch.persistence.room:testing:$room_version"
}

Версия 1.1.1

Версия 1.1.1

19 июня 2018 г.

Room 1.1.1 is identical to Room 1.1.1-rc1 .

Version 1.1.1-rc1

May 16, 2018 We highly recommend using Room 1.1.1-rc1 instead of 1.1.0 if you are using migrations.

Fixed a bug where Room would not handle post migration initialization properly b/79362399

Версия 1.1.0

Version 1.1.0-beta3

19 апреля 2018 г.

Исправлены ошибки

  • Fix compilation error when a Kotlin POJO references a relation entity that was defined in Java b/78199923

Version 1.1.0-beta2

5 апреля 2018 г.

Исправлены ошибки

  • Fixed a critical bug in Room Rx Single and Maybe implementations where it would recycle the query ahead of time, causing problems if you add more than 1 observer to the returned Single or Maybe instances. b/76031240

  • [RoomDatabase.clearAllTables][ref-clearAllTables] will not VACUUM the database if it is called inside a transaction. b/77235565

Version 1.1.0-beta1

21 марта 2018 г.

Изменения в API

  • Based on API Review feedback, @RawQuery does not accept passing a String as the query parameter anymore. You need to use [SupportSQLiteQuery][ref-SupportSQLiteQuery]. (see [SimpleSQLiteQuery][ref-SimpleSQLiteQuery] to easily create an instance of [SupportSQLiteQuery][ref-SupportSQLiteQuery] with argument support).
  • RoomDatabase.Builder's [fallbackToDestructiveMigrationFrom][ref-fallbackToDestructiveMigrationFrom] method now accepts vararg int instead of vararg Integer .

Исправлены ошибки

  • [RoomDatabase.clearAllTables][ref-clearAllTables] now tries to return space back to the operating system by setting a WAL checkpoint and VACUUM ing the database.
  • [ @RawQuery ][ref-RawQuery] now accepts any Pojo for the observedEntities property as long as the Pojo references to one or more entities via its Embedded fields or Relation s. b/74041772
  • Paging: Room's DataSource implementation now correctly handles multi-table dependencies (such as relations, and joins). Previously these would fail to trigger new results, or could fail to compile. b/74128314

Version 1.1.0-alpha1

22 января 2018 г.

Новые функции

  • RawQuery : This new API allows @Dao methods to receive the SQL as a query parameter b/62103290 , b/71458963
  • fallBackToDestructiveMigrationsFrom : This new API in RoomDatabase.Builder allows for finer grained control over from which starting schema versions destructive migrations are allowed (as compared to fallbackToDestructiveMigration) b/64989640
  • Room now only supports newer Paging APIs (alpha-4+), dropping support for the deprecated LivePagedListProvider . To use the new Room alpha, you'll need to use paging alpha-4 or higher, and switch from LivePagedListProvider to LivePagedListBuilder if you haven't already.

Исправлены ошибки

  • Improved support for Kotlin Kapt types. b/69164099
  • Order of fields do not invalidate schema anymore. b/64290754