-1

is there a way to detect when SQLite connection closes? I am trying to integrate SQLCipher and this is the initialization method:

fun initialize(passphrase: String): Boolean {
    this.passphrase = SQLiteDatabase.getBytes(passphrase.toCharArray())
    this.factory = SupportFactory(this.passphrase, PasswordValidationHook(), false)

    return try {
        myDatabase = Room.databaseBuilder(
            context.applicationContext,
            MyDatabase::class.java,
            DATABASE_NAME
        )
            .openHelperFactory(factory)
            .build()

        myDatabase.query("SELECT 1", emptyArray())

        true
    } catch (e: Exception) {
        false
    }
}

Now if the connection gets opened I know after the line myDatabase.query("SELECT 1", emptyArray()). However, I cannot find a proper way to detect when the database closes connection, since I have a notification service which displays whether the database is open or not.

I could close the connection manually on onDestroy method and have a listener attached, however, it's not recommended, since this method is not always called.

Captain Jacky
  • 888
  • 1
  • 12
  • 26

1 Answers1

0

There is no connection in SQLite. This isn't a traditional DB where it's another process. It's a library, and it does direct file IO in the process that's currently running. Thus no connection, no IPC to another process, and no closing or opening of a connection. The helper there with DATABASE_NAME "opening" it is just telling it what DB file to use for that object

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Thanks for the answer. But the connection can still be referred to as act of opening my database file within my app's process? I also can `setAutoCloseTimeout()` functions which would call `close()` in which my database object becomes invalid. Is there any way to detect when this DB file becomes invalid to read from via trigger or anyhow in my Service class? Because I would not know when the database would call close(). Thanks. – Captain Jacky Jun 28 '23 at 08:15
  • What makes you think it ever gets closed? Or that it doesn't close after every read/write? All of those would be implementation details of the specific version of the library you shouldn't rely on. Since there's no connection to an external process, there's no value in considering the concept of a closed connection. Close is there for if you're doing something really wacky, like deleting the db file entirely and you need to close open file handles to it. You don't normally ever use it. – Gabe Sechan Jun 28 '23 at 13:24