2

tl;dr:

How do i close a read-/ write connection to a database in Sqlite.swift?

Background story:

I am using the sqlite.swift framework to manage a .sqlite file (data.sqlite) that is copied from the application bundle (bootstrap.sqlite) on app start (if it doesn't exist yet). This sqlite file from the bundle contains various bootstrap data.

I want the user to "reset all data" and my approach so far is to delete the data.sqlite file and copy the bootstrap.sqlite file again - on runtime

Unfortunately there might still be open connections / running requests that obviously fail / crash / screw up the file.

I tried

dbWriteConnection?.interrupt()
dbReadConnection?.interrupt()
try? fileManager.removeItem(at: localSqlitePathURL)

But this seems to somehow delete the table within the sqlite.

Is there any way to cancel all running requests / guarantee that the connections are idle?

MarkHim
  • 5,686
  • 5
  • 32
  • 64

1 Answers1

2

AFAIK closing a db connection in SQLite.swift can only be implicitly accomplished by deallocating the Connection object(s) you're using. What I've done in similar cases is a) kept the connection as var db: Connection? so that I can assign nil to them, and b) used semaphores/locks to ensure that either a database access or my database switching code is running.

tl;dr

dbWriteConnection = nil
dbReadConnection = nil
Gereon
  • 17,258
  • 4
  • 42
  • 73
  • Thanks, will try it out. I think assigning nil will not be enough though as we can't trust the GC to clean up properly, but using a semaphore sounds good – MarkHim Jan 24 '18 at 09:01
  • There's no GC involved - we have ARC, and that will invoke `deinit` on the Connection objects as soon as the reference count drops to 0. – Gereon Jan 24 '18 at 09:08
  • Works like a charm, thx @Gereon. In hindsight: why didn't i of trying that?! – MarkHim Jan 24 '18 at 09:30