You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi, I have used the code below to clean up a SQLite database.
I'm posting it here, in case anyone wants to create a new adapter.
using Dapper;using System.Data.Common;using System.Text;namespace Test;publicsealedclassDatabaseCleaner{readonlyDatabaseConnectionFactorydatabaseConnectionFactory;readonlyIEnumerable<string>ignoredTables=["sqlite_sequence"];publicDatabaseCleaner(DatabaseConnectionFactorydatabaseConnectionFactory,IEnumerable<string>?ignoredTables){this.databaseConnectionFactory =databaseConnectionFactory;if(ignoredTables is not null)this.ignoredTables =this.ignoredTables.Union(ignoredTables).ToArray();usingDbConnectionconnection= databaseConnectionFactory.Create();Command= GetCommand(connection,this.ignoredTables);staticstringBuildCommand(IList<string>orderedTables){StringBuilderstringBuilder=new();foreach(string table in orderedTables)
stringBuilder.Append("DELETE FROM ").Append(table).Append(';');return stringBuilder.ToString();}staticstringGetCommand(DbConnectionconnection,IEnumerable<string>ignoredTables){vartables= GetTables(connection, ignoredTables);varrelationships= GetRelationships(connection);varorderedTables= OrderTables(tables, relationships);return BuildCommand(orderedTables);}staticIList<(string PrimaryKeyTable,string ForeignKeyTable)>GetRelationships(DbConnectionconnection){varrelationships= connection.Query<(string PrimaryKeyTable,string ForeignKeyTable)>("SELECT p.'table', s.name FROM sqlite_schema s JOIN pragma_foreign_key_list(s.name) p ON s.name <> p.'table' WHERE s.type = 'table'");return relationships.ToList();}staticIList<string>GetTables(DbConnectionconnection,IEnumerable<string>ignoredTables){vartables= connection.Query<string>("SELECT name FROM sqlite_schema WHERE type = 'table'");return tables.Except(ignoredTables).ToList();}staticIList<string>OrderTables(IList<string>tables,IList<(string PrimaryKeyTable,string ForeignKeyTable)>relationships){List<string>orderedTables=new(tables.Count);while(tables.Count >0){string[]leafs= tables.Except(relationships.Select(r => r.PrimaryKeyTable)).ToArray();
orderedTables.AddRange(leafs);foreach(string leaf in leafs){
tables.Remove(leaf);foreach(var relationship in relationships.Where(r => r.ForeignKeyTable ==leaf).ToArray())
relationships.Remove(relationship);}}returnorderedTables;}}publicstringCommand{get;}publicvoidClear(){if(string.IsNullOrEmpty(Command))return;usingDbConnectionconnection= databaseConnectionFactory.Create();
connection.Execute(Command);}}
The text was updated successfully, but these errors were encountered:
Hi, I have used the code below to clean up a SQLite database.
I'm posting it here, in case anyone wants to create a new adapter.
The text was updated successfully, but these errors were encountered: