-
-
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
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
4c67ea9
feat(android-sqlite): Add SentrySQLiteDriver (JAVA-275)
0xadam-brown 02edd2a
Use lambda for nanoTimeProvider default
0xadam-brown 37591e7
Address Roman's comments
0xadam-brown e689907
Bump androidx.sqlite to 2.6.2 to pick up new hasConnectionPool method
0xadam-brown d4ab6b7
Merge branch 'main' into feat/support-sqlite-driver
0xadam-brown f2207a5
Guard SQLiteDriver.hasConnectionPool for sqlite 2.5.x delegates
0xadam-brown 2e5f001
Make API internal during development
0xadam-brown 2473d22
Merge remote-tracking branch 'origin/main' into feat/support-sqlite-d…
0xadam-brown 8baa311
Minor doc improvements
0xadam-brown File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| # sentry-android-sqlite | ||
|
|
||
| SQLite instrumentation for AndroidX APIs. | ||
|
|
||
| Two instrumentation paths are supported: | ||
|
|
||
| - **`androidx.sqlite.SQLiteDriver`**: Used by Room 2.7+ and 3.0+. | ||
| - **`androidx.sqlite.db.SupportSQLiteOpenHelper`**: Used by SQLDelight and legacy (pre-2.7) Room. Applied automatically by the Sentry Android Gradle Plugin. | ||
|
|
||
| To avoid duplicate spans, only one path should be used per database file. Most Room and SQLDelight APIs enforce that division. The exception is Room's `SupportSQLiteDriver`: either the `SupportSQLiteOpenHelper` it consumes should be wrapped or the support driver itself, but never both. | ||
|
|
||
| ## Package layout | ||
|
|
||
| The module is organized as two separate packages: | ||
|
|
||
| - **`io.sentry.android.sqlite`**: Android-specific code. Depends on `android.database.*` and/or on `androidx.sqlite.db.*`. | ||
| - **`io.sentry.sqlite`**: No Android-specific code. Depends only on multiplatform `androidx.sqlite.*`. | ||
|
|
||
| The split anticipates future Kotlin Multiplatform support. The `androidx.sqlite.*` interfaces are defined in KMP's `commonMain` source set and are used by Room in non-JVM environments. 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. | ||
|
|
||
| Note that the module artifact itself (`sentry-android-sqlite`) is currently an Android-only AAR regardless of package layout. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
49 changes: 49 additions & 0 deletions
49
sentry-android-sqlite/src/main/java/io/sentry/sqlite/DbMetadata.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| package io.sentry.sqlite | ||
|
|
||
| /** [DB_SYSTEM_KEY][io.sentry.SpanDataConvention.DB_SYSTEM_KEY] value for in-memory databases. */ | ||
| internal const val DB_SYSTEM_IN_MEMORY = "in-memory" | ||
|
|
||
| /** [DB_SYSTEM_KEY][io.sentry.SpanDataConvention.DB_SYSTEM_KEY] value 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 (see docs | ||
| * [here](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) | ||
|
|
||
| /** | ||
| * Returns metadata based on the [fileName] argument passed 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) | ||
| } | ||
|
|
||
| /** | ||
| * Returns metadata based on | ||
| * [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) | ||
| } |
99 changes: 99 additions & 0 deletions
99
sentry-android-sqlite/src/main/java/io/sentry/sqlite/SQLiteSpanInstrumentation.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| 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 instrumentation for SQLite. */ | ||
| 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 { | ||
|
|
||
| /** | ||
| * Returns [SQLiteSpanInstrumentation] based on the [fileName] argument passed to | ||
| * [SQLiteDriver.open][androidx.sqlite.SQLiteDriver.open]. | ||
| */ | ||
| fun fromFileName( | ||
| fileName: String, | ||
| scopes: IScopes = ScopesAdapter.getInstance(), | ||
| ): SQLiteSpanInstrumentation = | ||
| SQLiteSpanInstrumentation(scopes, dbMetadataFromFileName(fileName)) | ||
|
|
||
| /** | ||
| * Returns [SQLiteSpanInstrumentation] based on | ||
| * [SupportSQLiteOpenHelper.databaseName][androidx.sqlite.db.SupportSQLiteOpenHelper.databaseName]. | ||
| */ | ||
| fun fromDatabaseName( | ||
| databaseName: String?, | ||
| scopes: IScopes = ScopesAdapter.getInstance(), | ||
| ): SQLiteSpanInstrumentation = | ||
| SQLiteSpanInstrumentation(scopes, dbMetadataFromDatabaseName(databaseName)) | ||
| } | ||
| } |
15 changes: 15 additions & 0 deletions
15
sentry-android-sqlite/src/main/java/io/sentry/sqlite/SentrySQLiteConnection.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } | ||
| } |
79 changes: 79 additions & 0 deletions
79
sentry-android-sqlite/src/main/java/io/sentry/sqlite/SentrySQLiteDriver.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| 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 and combining them will produce | ||
| * duplicate spans. | ||
| * | ||
| * @param delegate The [SQLiteDriver] instance to delegate calls to. | ||
| */ | ||
| internal class SentrySQLiteDriver private constructor(private val delegate: SQLiteDriver) : | ||
| SQLiteDriver { | ||
|
|
||
| init { | ||
| SentryIntegrationPackageStorage.getInstance().addIntegration("SQLiteDriver") | ||
|
0xadam-brown marked this conversation as resolved.
|
||
| } | ||
|
|
||
| override val hasConnectionPool: Boolean | ||
| get() = | ||
| try { | ||
| delegate.hasConnectionPool | ||
| } catch (_: LinkageError) { | ||
|
0xadam-brown marked this conversation as resolved.
|
||
| // 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.
|
||
| } | ||
| } | ||
|
|
||
| companion object { | ||
|
|
||
| /** | ||
| * Wraps the provided delegate in a [SentrySQLiteDriver]. Returns the delegate as-is if already | ||
| * wrapped. | ||
| */ | ||
| @JvmStatic | ||
| fun create(delegate: SQLiteDriver): SQLiteDriver = | ||
| delegate as? SentrySQLiteDriver ?: SentrySQLiteDriver(delegate) | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.