1

Consider the following F# script, which creates a simple SQLite database and table, and then should delete it. However, the SQLite obejct doesn't seem to be disposed of properly and isn't releasing its lock on the file.

#r @"C:\Path\To\System.Data.SQLite.dll"

open System.Data.SQLite

let createTable() = 
    use db = new SQLiteConnection(@"Data Source=test.sqlite")
    db.Open()
    let command = new SQLiteCommand("CREATE TABLE TestItems (ColA ColB)", db)
    command.ExecuteNonQuery() |> ignore
    db.Close()

createTable()

// System.IO.IOException: The process cannot access the file '[...]\test.sqlite' 
// because it is being used by another process.
System.IO.File.Delete("test.sqlite")

I'm pretty poor at F#, but my understanding of use is that the object's resources will be disposed of when it goes out of scope, yet that appears to not be the case in this instance. I've tried calling Dispose() to no avail as well.

Can anyone shed light on how I can properly dispose of SQLite objects in F#?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
user1393477
  • 845
  • 10
  • 13
  • 2
    Doesn't `SQLiteCommand` implement `IDisposable` as well? In that case you should also use the `use` binding instead of `let`. – Honza Brestan Jun 04 '15 at 22:47
  • That was the problem! Assumed it was a F# problem but was rather my ignorance of System.Data.SQLite. If you post an answer I'll gladly mark it as accepted. – user1393477 Jun 04 '15 at 22:55
  • 2
    @user1393477 A useful way I've found of avoiding this is to only use `new` with `use`, if you don't specify `new` for a class that implements `IDisposable` you'll get a warning – Matthew Mcveigh Jun 05 '15 at 10:32

1 Answers1

3

The SQLiteCommand needs to be disposed as well, as it also implements IDisposable according to the docs: https://www.devart.com/dotconnect/sqlite/docs/Devart.Data.SQLite~Devart.Data.SQLite.SQLiteCommand_members.html (via System.ComponentModel.Component

Using use binding instead of let for command should solve the issue.

Honza Brestan
  • 10,637
  • 2
  • 32
  • 43