Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# Changelog

## Unreleased

### Features

- Add `SentrySQLiteDriver` to `sentry-android-sqlite` for instrumenting AndroidX's `SQLiteDriver` ([#5466](https://github.com/getsentry/sentry-java/pull/5466))
- Automatically generates spans for all SQLite statements
- To use it, pass your `SQLiteDriver` to `SentrySQLiteDriver.create(...)`
- See https://docs.sentry.io/platforms/android/integrations/room-and-sqlite/ for more details, including info about migrating from `SentrySupportSQLiteOpenHelper`

## 8.43.0

### Features
Expand Down
21 changes: 21 additions & 0 deletions sentry-android-sqlite/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# sentry-android-sqlite

This module provides automatic SQLite query instrumentation for Android.

Two instrumentation paths are supported, matching the two SQLite APIs offered by AndroidX:

- **`androidx.sqlite.SQLiteDriver`** โ€” used by Room 2.7+ via `Room.databaseBuilder(...).setDriver(...)` and by SQLDelight via its AndroidX SQLite driver.
- **`androidx.sqlite.db.SupportSQLiteOpenHelper`** โ€” used by legacy Room via `Room.databaseBuilder(...).openHelperFactory(...)`, or applied automatically by the Sentry Android Gradle plugin.

Please consult the [Sentry Docs](https://docs.sentry.io/platforms/android/integrations/room-and-sqlite/) for usage and migration guidance, as well as how to avoid duplicate spans when using Room's `SupportSQLiteDriver` adapter.

## Package layout

This module is organized as two separate packages:

- **`io.sentry.android.sqlite`**: Android-specific code. Classes here depend on `android.database.*` (e.g., `CrossProcessCursor`, `SQLException`) and/or on `androidx.sqlite.db.*`, the Android-only compatibility layer over the platform's SQLite. The `SentrySupportSQLiteOpenHelper` path and its span helper `SQLiteSpanManager` live here.
- **`io.sentry.sqlite`**: Code whose contract depends only on the multiplatform `androidx.sqlite.*` interfaces (e.g., `SQLiteDriver` and `SQLiteConnection`). `SentrySQLiteDriver` and its span helper `SQLiteSpanRecorder` live here.

The split anticipates the possibility of future Kotlin Multiplatform support. The `androidx.sqlite.*` driver interfaces are defined in the library's `commonMain` source set and are reused by Room across Android, JVM, and native targets. Classes in `io.sentry.sqlite` are written against those portable interfaces and are intended to lift cleanly into a KMP `commonMain` source set if/when the `sentry` core gains multiplatform targets. Classes in `io.sentry.android.sqlite` are Android-only by construction and will stay where they are.

Note that the module artifact itself (`sentry-android-sqlite`) is currently an Android-only AAR regardless of package layout.
11 changes: 11 additions & 0 deletions sentry-android-sqlite/api/sentry-android-sqlite.api
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,14 @@ public final class io/sentry/android/sqlite/SentrySupportSQLiteOpenHelper$Compan
public final fun create (Landroidx/sqlite/db/SupportSQLiteOpenHelper;)Landroidx/sqlite/db/SupportSQLiteOpenHelper;
}

public final class io/sentry/sqlite/SentrySQLiteDriver : androidx/sqlite/SQLiteDriver {
public static final field Companion Lio/sentry/sqlite/SentrySQLiteDriver$Companion;
public synthetic fun <init> (Landroidx/sqlite/SQLiteDriver;Lkotlin/jvm/internal/DefaultConstructorMarker;)V
public static final fun create (Landroidx/sqlite/SQLiteDriver;)Landroidx/sqlite/SQLiteDriver;
public fun open (Ljava/lang/String;)Landroidx/sqlite/SQLiteConnection;
}

public final class io/sentry/sqlite/SentrySQLiteDriver$Companion {
public final fun create (Landroidx/sqlite/SQLiteDriver;)Landroidx/sqlite/SQLiteDriver;
}

Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,18 @@ import android.database.CrossProcessCursor
import android.database.SQLException
import io.sentry.IScopes
import io.sentry.ISpan
import io.sentry.Instrumenter
import io.sentry.ScopesAdapter
import io.sentry.SentryIntegrationPackageStorage
import io.sentry.SentryStackTraceFactory
import io.sentry.SpanDataConvention
import io.sentry.SpanStatus

private const val TRACE_ORIGIN = "auto.db.sqlite"
import io.sentry.sqlite.SQLiteSpanHelper
import io.sentry.sqlite.dbMetadataFromDatabaseName

internal class SQLiteSpanManager(
private val scopes: IScopes = ScopesAdapter.getInstance(),
private val databaseName: String? = null,
databaseName: String? = null,
) {
private val stackTraceFactory = SentryStackTraceFactory(scopes.options)

private val spanHelper = SQLiteSpanHelper(scopes, dbMetadataFromDatabaseName(databaseName))
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Helper lets us share span population logic between the old and new worlds. Behavior on the legacy path is unchanged.


init {
SentryIntegrationPackageStorage.getInstance().addIntegration("SQLite")
Expand Down Expand Up @@ -45,33 +43,18 @@ internal class SQLiteSpanManager(
if (result is CrossProcessCursor) {
return SentryCrossProcessCursor(result, this, sql) as T
}
span = scopes.span?.startChild("db.sql.query", sql, startTimestamp, Instrumenter.SENTRY)
span?.spanContext?.origin = TRACE_ORIGIN
span = spanHelper.startSpan(sql, startTimestamp)
span?.status = SpanStatus.OK
result
} catch (e: Throwable) {
span = scopes.span?.startChild("db.sql.query", sql, startTimestamp, Instrumenter.SENTRY)
span?.spanContext?.origin = TRACE_ORIGIN
span = spanHelper.startSpan(sql, startTimestamp)
span?.status = SpanStatus.INTERNAL_ERROR
span?.throwable = e
throw e
} finally {
span?.apply {
val isMainThread: Boolean = scopes.options.threadChecker.isMainThread
setData(SpanDataConvention.BLOCKED_MAIN_THREAD_KEY, isMainThread)
if (isMainThread) {
setData(SpanDataConvention.CALL_STACK_KEY, stackTraceFactory.inAppCallStack)
}
// if db name is null, then it's an in-memory database as per
// https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:sqlite/sqlite/src/main/java/androidx/sqlite/db/SupportSQLiteOpenHelper.kt;l=38-42
if (databaseName != null) {
setData(SpanDataConvention.DB_SYSTEM_KEY, "sqlite")
setData(SpanDataConvention.DB_NAME_KEY, databaseName)
} else {
setData(SpanDataConvention.DB_SYSTEM_KEY, "in-memory")
}

finish()
span?.let {
spanHelper.applyDataToSpan(it)
it.finish()
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package io.sentry.sqlite

/**
* Value associated with [DB_SYSTEM_KEY][io.sentry.SpanDataConvention.DB_SYSTEM_KEY] for in-memory
* databases.
*/
internal const val DB_SYSTEM_IN_MEMORY = "in-memory"

/**
* Value associated with [DB_SYSTEM_KEY][io.sentry.SpanDataConvention.DB_SYSTEM_KEY] for SQLite
* databases.
*/
internal const val DB_SYSTEM_SQLITE = "sqlite"

/**
* Sentinel file name that [SQLiteDriver.open][androidx.sqlite.SQLiteDriver.open] interprets as an
* in-memory database:
* https://developer.android.com/reference/androidx/sqlite/driver/AndroidSQLiteDriver.
*/
private const val IN_MEMORY_DB_FILENAME = ":memory:"

/** Path separators matching [File.separatorChar][java.io.File.separatorChar]. */
private val FILE_NAME_PATH_SEPARATORS = charArrayOf('/', '\\')

internal data class DbMetadata(val name: String?, val system: String)

/**
* Resolves metadata from the [fileName] argument to
* [SQLiteDriver.open][androidx.sqlite.SQLiteDriver.open].
*/
internal fun dbMetadataFromFileName(fileName: String): DbMetadata {
if (fileName == IN_MEMORY_DB_FILENAME) {
return DbMetadata(name = null, system = DB_SYSTEM_IN_MEMORY)
}

val trimmed = fileName.trimEnd('/', '\\')
if (trimmed.isEmpty()) {
return DbMetadata(name = null, system = DB_SYSTEM_SQLITE)
}

val index = trimmed.lastIndexOfAny(FILE_NAME_PATH_SEPARATORS)
val basename = if (index >= 0) trimmed.substring(index + 1) else trimmed
return DbMetadata(name = basename.ifEmpty { null }, system = DB_SYSTEM_SQLITE)
}

/**
* Resolves metadata from
* [SupportSQLiteOpenHelper.databaseName][androidx.sqlite.db.SupportSQLiteOpenHelper.databaseName].
*/
internal fun dbMetadataFromDatabaseName(databaseName: String?): DbMetadata =
if (databaseName == null) {
DbMetadata(name = null, system = DB_SYSTEM_IN_MEMORY)
} else {
DbMetadata(name = databaseName, system = DB_SYSTEM_SQLITE)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package io.sentry.sqlite

import io.sentry.IScopes
import io.sentry.ISpan
import io.sentry.Instrumenter
import io.sentry.SentryDate
import io.sentry.SentryStackTraceFactory
import io.sentry.SpanDataConvention

private const val SQLITE_TRACE_ORIGIN = "auto.db.sqlite"

/** Shared span creation and metadata for SQLite instrumentation. */
internal class SQLiteSpanHelper(private val scopes: IScopes, private val dbMetadata: DbMetadata) {

private val stackTraceFactory = SentryStackTraceFactory(scopes.options)

fun startSpan(sql: String, startTimestamp: SentryDate): ISpan? =
scopes.span?.startChild("db.sql.query", sql, startTimestamp, Instrumenter.SENTRY)?.apply {
spanContext.origin = SQLITE_TRACE_ORIGIN
}

fun applyDataToSpan(span: ISpan) {
val isMainThread = scopes.options.threadChecker.isMainThread
span.setData(SpanDataConvention.BLOCKED_MAIN_THREAD_KEY, isMainThread)

if (isMainThread) {
span.setData(SpanDataConvention.CALL_STACK_KEY, stackTraceFactory.inAppCallStack)
}

dbMetadata.name?.let { span.setData(SpanDataConvention.DB_NAME_KEY, it) }
span.setData(SpanDataConvention.DB_SYSTEM_KEY, dbMetadata.system)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package io.sentry.sqlite

import io.sentry.IScopes
import io.sentry.ScopesAdapter
import io.sentry.SentryDate
import io.sentry.SentryLevel
import io.sentry.SentryLongDate
import io.sentry.SpanStatus

internal class SQLiteSpanRecorder(
fileName: String,
private val scopes: IScopes = ScopesAdapter.getInstance(),
) {

private val spanHelper = SQLiteSpanHelper(scopes, dbMetadataFromFileName(fileName))

/**
* Returns a start timestamp for a db.sql.query span.
*
* Exposed so callers can capture a wall-clock start before accumulating database time.
* Internalizing the start time in [recordSpan] would shift spans to end-of-work on the trace
* timeline, which is less desirable.
*/
fun startTimestamp(): SentryDate = scopes.options.dateProvider.now()

/** Records a db.sql.query span. */
@Suppress("TooGenericExceptionCaught")
fun recordSpan(
sql: String,
startTimestamp: SentryDate,
durationNanos: Long,
status: SpanStatus,
throwable: Throwable? = null,
) {
try {
val span = spanHelper.startSpan(sql, startTimestamp) ?: return
throwable?.let { span.throwable = it }
spanHelper.applyDataToSpan(span)
val endTimestamp = SentryLongDate(startTimestamp.nanoTimestamp() + durationNanos)
span.finish(status, endTimestamp)
} catch (t: Throwable) {
scopes.options.logger.log(SentryLevel.ERROR, "Failed to record SQLite span.", t)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package io.sentry.sqlite

import androidx.sqlite.SQLiteConnection
import androidx.sqlite.SQLiteStatement

internal class SentrySQLiteConnection(
private val delegate: SQLiteConnection,
private val spanRecorder: SQLiteSpanRecorder,
) : SQLiteConnection by delegate {

override fun prepare(sql: String): SQLiteStatement {
val statement = delegate.prepare(sql)
return statement as? SentrySQLiteStatement
?: SentrySQLiteStatement(statement, spanRecorder, sql)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package io.sentry.sqlite
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As mentioned in the PR description, I've created a separate package for the wrapper without an .android. infix and scrubbed the package of any Android dependencies.

The point of Google's introducing the new driver was to support KMP, so I suspect we may want to lift the wrapper to sentry-kotlin-multiplatform at some point.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

...a new README captures the policy.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

๐Ÿ’ฏ , smart choice!


import androidx.sqlite.SQLiteConnection
import androidx.sqlite.SQLiteDriver
import io.sentry.ScopesAdapter
import io.sentry.SentryIntegrationPackageStorage
import io.sentry.SentryLevel

/**
* Wraps a [SQLiteDriver] and automatically adds spans for each SQL statement it executes.
*
* Example usage:
* ```
* val driver = SentrySQLiteDriver.create(AndroidSQLiteDriver())
* ```
*
* If you use Room:
* ```
* val database = Room.databaseBuilder(context, MyDatabase::class.java, "dbName")
* .setDriver(SentrySQLiteDriver.create(AndroidSQLiteDriver()))
* .build()
* ```
*
* **Warning:** Do not use [SentrySQLiteDriver] together with
* [SentrySupportSQLiteOpenHelper][io.sentry.android.sqlite.SentrySupportSQLiteOpenHelper] on the
* same database file. Both wrappers instrument at different layers, so combining them will produce
* duplicate spans for every SQL statement.
*
* @param delegate The [SQLiteDriver] instance to delegate calls to.
*/
public class SentrySQLiteDriver private constructor(private val delegate: SQLiteDriver) :
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once we lift this up for kmp, we'll probably need to extend this, like e.g. passing a scope / options / logger instance, instead of relying on ScopesAdapter.getInstance() like we do below. But IMHO that's fine for now and won't cause a breaking change.

SQLiteDriver {

init {
SentryIntegrationPackageStorage.getInstance().addIntegration("SQLiteDriver")
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

โš ๏ธ Note that the integration name differs from what we use with the support open helper ("SQLite"). I presume that's what developers would expect and it follows the pattern of ANR vs ANR2, but let me know if you think otherwise.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whilst we surface this information to developers on the issue details page, the main use case is for us (sentry) to get an idea of which integrations are used and to track adoption.
So using a different name here is actually preferred.

}

@Suppress("TooGenericExceptionCaught")
override fun open(fileName: String): SQLiteConnection {
val connection = delegate.open(fileName)

return try {
val spanRecorder = SQLiteSpanRecorder(fileName)
// create() ensures delegate is unwrapped, so we don't protect against double-wrapping the
// connection.
SentrySQLiteConnection(connection, spanRecorder)
} catch (t: Throwable) {
ScopesAdapter.getInstance()
.options
.logger
.log(
SentryLevel.ERROR,
"Failed to instrument SQLite connection; returning uninstrumented connection.",
t,
)
connection
}
}

public companion object {

@JvmStatic
public fun create(delegate: SQLiteDriver): SQLiteDriver =
delegate as? SentrySQLiteDriver ?: SentrySQLiteDriver(delegate)
}
}
Loading
Loading