Resolving NPE issue in SupportSQLiteQueryBuilder.
This issue was caused by the incorrect logic of using `columns?.size != 0` on a nullable `column` to decide whether the contents of `column` can be appended to a statement. The logic was flawed in that the expression would return true even if `columns` itself was null, attempting to append non-existent content. The correct logic to use is `!columns.isNullOrEmpty()` which covers both cases. Same logic has been applied to `StringBuilder.appendClause` to avoid any potential issues with a null `clause`.
Bug: 260625714
Test: SupportSQLiteQueryBuilderTest.kt
Change-Id: Ica8f50febd3648b7539fa94df5f0a0197c94e63d
diff --git a/sqlite/sqlite/src/main/java/androidx/sqlite/db/SupportSQLiteQueryBuilder.kt b/sqlite/sqlite/src/main/java/androidx/sqlite/db/SupportSQLiteQueryBuilder.kt
index ed54ec4..a7afd1d 100644
--- a/sqlite/sqlite/src/main/java/androidx/sqlite/db/SupportSQLiteQueryBuilder.kt
+++ b/sqlite/sqlite/src/main/java/androidx/sqlite/db/SupportSQLiteQueryBuilder.kt
@@ -129,7 +129,7 @@
if (distinct) {
append("DISTINCT ")
}
- if (columns?.size != 0) {
+ if (!columns.isNullOrEmpty()) {
appendColumns(columns!!)
} else {
append("* ")
@@ -146,7 +146,7 @@
}
private fun StringBuilder.appendClause(name: String, clause: String?) {
- if (clause?.isNotEmpty() == true) {
+ if (!clause.isNullOrEmpty()) {
append(name)
append(clause)
}
diff --git a/sqlite/sqlite/src/test/java/androidx/sqlite/db/SupportSQLiteQueryBuilderTest.kt b/sqlite/sqlite/src/test/java/androidx/sqlite/db/SupportSQLiteQueryBuilderTest.kt
index 9d9a173..27d5773 100644
--- a/sqlite/sqlite/src/test/java/androidx/sqlite/db/SupportSQLiteQueryBuilderTest.kt
+++ b/sqlite/sqlite/src/test/java/androidx/sqlite/db/SupportSQLiteQueryBuilderTest.kt
@@ -22,6 +22,16 @@
@RunWith(JUnit4::class)
class SupportSQLiteQueryBuilderTest {
+
+ @Test
+ fun null_columns_should_not_throw_npe() {
+ val query = SupportSQLiteQueryBuilder.builder("Books")
+ .columns(null)
+ .groupBy("pages")
+ .having(">100")
+ .create()
+ assertThat(query.sql).isEqualTo("SELECT * FROM Books GROUP BY pages HAVING >100")
+ }
@Test
fun null_groupBy_and_having_throws_error() {
val error = assertFails {