private void OptimizeDatabase()
{
bool needs_analyze = false;
long analyze_threshold = configuration.Get<long> ("Database", "AnalyzeThreshold", 100);
string [] tables_with_indexes = {"CoreTracks", "CoreArtists", "CoreAlbums",
"CorePlaylistEntries", "PodcastItems", "PodcastEnclosures",
"PodcastSyndications", "CoverArtDownloads"};
if (TableExists ("sqlite_stat1")) {
foreach (string table_name in tables_with_indexes) {
if (TableExists (table_name)) {
long count = Query<long> (String.Format ("SELECT COUNT(*) FROM {0}", table_name));
string stat = Query<string> ("SELECT stat FROM sqlite_stat1 WHERE tbl = ? LIMIT 1", table_name);
// stat contains space-separated integers,
// the first is the number of records in the table
long items_indexed = stat != null ? long.Parse (stat.Split (' ')[0]) : 0;
if (Math.Abs (count - items_indexed) > analyze_threshold) {
needs_analyze = true;
break;
}
}
}
} else {
needs_analyze = true;
}
if (needs_analyze) {
Log.DebugFormat ("Running ANALYZE against database to improve performance");
Execute ("ANALYZE");
}
}