From a848d8397a1c12e37f59b699f049ce37afcc34a5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Jul 2025 18:43:48 -0500 Subject: add GetDatabaseIndexes --- src/slskd/Core/Data/SchemaInspector.cs | 57 ++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Data/SchemaInspector.cs b/src/slskd/Core/Data/SchemaInspector.cs index 234b9100..d4fadfba 100644 --- a/src/slskd/Core/Data/SchemaInspector.cs +++ b/src/slskd/Core/Data/SchemaInspector.cs @@ -67,6 +67,8 @@ public static class SchemaInspector dict[table] = columns; } + connection.Close(); + return dict; } catch (Exception ex) @@ -75,8 +77,63 @@ public static class SchemaInspector } } + /// + /// Retrieves the index information for the specified SQLite database. + /// + /// The connection string for the database. + /// The index information. + /// Thrown if the database can't be accessed, or something else goes wrong. + public static Dictionary> GetDatabaseIndexes(string connectionString) + { + try + { + using var connection = new SqliteConnection(connectionString); + connection.Open(); + + var dict = new Dictionary>(); + + using var tableCommand = new SqliteCommand("SELECT name FROM sqlite_master WHERE type='table';", connection); + using var tableReader = tableCommand.ExecuteReader(); + + while (tableReader.Read()) + { + var table = tableReader.GetString(0); + + var indexes = new List(); + + using var command = new SqliteCommand($"PRAGMA index_list({table});", connection); + using var cr = command.ExecuteReader(); + + while (cr.Read()) + { + indexes.Add(new IndexInfo( + Seq: cr.GetInt64(cr.GetOrdinal("seq")), + Name: cr.GetString(cr.GetOrdinal("name")), + Unique: cr.GetInt64(cr.GetOrdinal("unique")) > 0, + Origin: cr.GetString(cr.GetOrdinal("origin")), + Partial: cr.GetInt64(cr.GetOrdinal("partial")) > 0)); + } + + dict[table] = indexes; + } + + connection.Close(); + + return dict; + } + catch (Exception ex) + { + throw new SlskdException($"Failed to retrieve index information for database '{connectionString}'. The database might be corrupt or in use by another application; if the problem persists the backing file may need to be deleted", ex); + } + } + /// /// Represents a SQLite database column. /// public record ColumnInfo(long Cid, string Name, string Type, bool NotNull, object DefaultValue, bool PrimaryKey); + + /// + /// Represents a SQLite database index. + /// + public record IndexInfo(long Seq, string Name, bool Unique, string Origin, bool Partial); } \ No newline at end of file -- cgit v1.2.3