-
-
Notifications
You must be signed in to change notification settings - Fork 471
feat(android-sqlite): Add SentrySQLiteDriver (JAVA-275) #5466
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
4c67ea9
02edd2a
37591e7
e689907
d4ab6b7
f2207a5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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 `SQLiteSpanManager` wrapper live here. | ||
| - **`io.sentry.sqlite`**: Code whose contract depends only on the multiplatform `androidx.sqlite.*` interfaces (e.g., `SQLiteDriver` and `SQLiteConnection`). `SentrySQLiteDriver` and shared span instrumentation via `SQLiteSpanInstrumentation` 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. |
| 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 { it in FILE_NAME_PATH_SEPARATORS } | ||
| 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,85 @@ | ||
| package io.sentry.sqlite | ||
|
|
||
| import io.sentry.IScopes | ||
| import io.sentry.Instrumenter | ||
| import io.sentry.ScopesAdapter | ||
| import io.sentry.SentryDate | ||
| import io.sentry.SentryLongDate | ||
| import io.sentry.SentryStackTraceFactory | ||
| import io.sentry.SpanDataConvention | ||
| import io.sentry.SpanStatus | ||
|
|
||
| private const val SQLITE_TRACE_ORIGIN = "auto.db.sqlite" | ||
|
|
||
| /** Shared span creation and metadata for SQLite instrumentation. */ | ||
| internal class SQLiteSpanInstrumentation( | ||
| private val scopes: IScopes, | ||
| private val dbMetadata: DbMetadata, | ||
| ) { | ||
|
|
||
| private val stackTraceFactory = SentryStackTraceFactory(scopes.options) | ||
|
|
||
| /** | ||
| * 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 from [startTimestamp] to the moment of invocation. */ | ||
| fun recordSpan( | ||
| sql: String, | ||
| startTimestamp: SentryDate, | ||
| status: SpanStatus, | ||
| throwable: Throwable? = null, | ||
| ) { | ||
| recordSpan(sql, startTimestamp, endTimestamp = null, status, throwable) | ||
| } | ||
|
|
||
| /** Records a `db.sql.query` span from [startTimestamp] to [startTimestamp] + [durationNanos]. */ | ||
| fun recordSpan( | ||
| sql: String, | ||
| startTimestamp: SentryDate, | ||
| durationNanos: Long, | ||
| status: SpanStatus, | ||
| throwable: Throwable? = null, | ||
| ) { | ||
| val endTimestamp = SentryLongDate(startTimestamp.nanoTimestamp() + durationNanos) | ||
| recordSpan(sql, startTimestamp, endTimestamp, status, throwable) | ||
| } | ||
|
|
||
| private fun recordSpan( | ||
| sql: String, | ||
| startTimestamp: SentryDate, | ||
| endTimestamp: SentryDate?, | ||
| status: SpanStatus, | ||
| throwable: Throwable?, | ||
| ) { | ||
| scopes.span?.startChild("db.sql.query", sql, startTimestamp, Instrumenter.SENTRY)?.apply { | ||
| spanContext.origin = SQLITE_TRACE_ORIGIN | ||
| throwable?.let { this.throwable = it } | ||
|
|
||
| val isMainThread = scopes.options.threadChecker.isMainThread | ||
| setData(SpanDataConvention.BLOCKED_MAIN_THREAD_KEY, isMainThread) | ||
|
|
||
| if (isMainThread) { | ||
| setData(SpanDataConvention.CALL_STACK_KEY, stackTraceFactory.inAppCallStack) | ||
| } | ||
|
|
||
| dbMetadata.name?.let { setData(SpanDataConvention.DB_NAME_KEY, it) } | ||
| setData(SpanDataConvention.DB_SYSTEM_KEY, dbMetadata.system) | ||
| finish(status, endTimestamp) | ||
| } | ||
| } | ||
|
|
||
| companion object { | ||
|
|
||
| fun fromDatabaseName(databaseName: String?, scopes: IScopes = ScopesAdapter.getInstance()) = | ||
| SQLiteSpanInstrumentation(scopes, dbMetadataFromDatabaseName(databaseName)) | ||
|
|
||
| fun fromFileName(fileName: String, scopes: IScopes = ScopesAdapter.getInstance()) = | ||
| SQLiteSpanInstrumentation(scopes, dbMetadataFromFileName(fileName)) | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| package io.sentry.sqlite | ||
|
|
||
| import androidx.sqlite.SQLiteConnection | ||
| import androidx.sqlite.SQLiteStatement | ||
|
|
||
| internal class SentrySQLiteConnection( | ||
| private val delegate: SQLiteConnection, | ||
| private val spans: SQLiteSpanInstrumentation, | ||
| ) : SQLiteConnection by delegate { | ||
|
|
||
| override fun prepare(sql: String): SQLiteStatement { | ||
| val statement = delegate.prepare(sql) | ||
| return statement as? SentrySQLiteStatement ?: SentrySQLiteStatement(statement, spans, sql) | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| package io.sentry.sqlite | ||
|
|
||
| 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) : | ||
|
0xadam-brown marked this conversation as resolved.
|
||
| SQLiteDriver { | ||
|
|
||
| init { | ||
| SentryIntegrationPackageStorage.getInstance().addIntegration("SQLiteDriver") | ||
|
0xadam-brown marked this conversation as resolved.
|
||
| } | ||
|
|
||
| override val hasConnectionPool: Boolean | ||
| get() = | ||
| try { | ||
| delegate.hasConnectionPool | ||
| } catch (_: LinkageError) { | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I see that this is the only reference to a *** "These sorts of issues" = A
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I see we had a similar one here: #4597 which we just fixed by bumping the version, but apparently we don't account for older versions, so I guess it just breaks there? |
||
| // Delegates on androidx.sqlite < 2.6.0 won't have a hasConnectionPool property. | ||
| false | ||
| } | ||
|
|
||
| @Suppress("TooGenericExceptionCaught") | ||
| override fun open(fileName: String): SQLiteConnection { | ||
| val connection = delegate.open(fileName) | ||
|
|
||
| return try { | ||
| val spans = SQLiteSpanInstrumentation.fromFileName(fileName) | ||
| // create() ensures delegate is unwrapped, so we don't need to protect against double-wrapping | ||
| // the connection. | ||
| SentrySQLiteConnection(connection, spans) | ||
| } catch (t: Throwable) { | ||
| ScopesAdapter.getInstance() | ||
| .options | ||
| .logger | ||
| .log( | ||
| SentryLevel.ERROR, | ||
| "Failed to instrument SQLite connection; returning uninstrumented connection.", | ||
| t, | ||
| ) | ||
| connection | ||
|
0xadam-brown marked this conversation as resolved.
|
||
| } | ||
| } | ||
|
|
||
| public companion object { | ||
|
|
||
| @JvmStatic | ||
| public fun create(delegate: SQLiteDriver): SQLiteDriver = | ||
| delegate as? SentrySQLiteDriver ?: SentrySQLiteDriver(delegate) | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.