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.
usingDapper;usingSystem.Data.Common;usingSystem.Text;namespaceTest;publicsealedclassDatabaseCleaner{readonlyDatabaseConnectionFactorydatabaseConnectionFactory;readonlyIEnumerable<string>ignoredTables=["sqlite_sequence"];publicDatabaseCleaner(DatabaseConnectionFactorydatabaseConnectionFactory,IEnumerable<string>?ignoredTables){this.databaseConnectionFactory=databaseConnectionFactory;if(ignoredTablesis not null)this.ignoredTables=this.ignoredTables.Union(ignoredTables).ToArray();usingDbConnectionconnection=databaseConnectionFactory.Create();Command=GetCommand(connection,this.ignoredTables);staticstringBuildCommand(IList<string>orderedTables){StringBuilderstringBuilder=new();foreach(stringtableinorderedTables)stringBuilder.Append("DELETE FROM ").Append(table).Append(';');returnstringBuilder.ToString();}staticstringGetCommand(DbConnectionconnection,IEnumerable<string>ignoredTables){vartables=GetTables(connection,ignoredTables);varrelationships=GetRelationships(connection);varorderedTables=OrderTables(tables,relationships);returnBuildCommand(orderedTables);}staticIList<(stringPrimaryKeyTable,stringForeignKeyTable)>GetRelationships(DbConnectionconnection){varrelationships=connection.Query<(stringPrimaryKeyTable,stringForeignKeyTable)>("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'");returnrelationships.ToList();}staticIList<string>GetTables(DbConnectionconnection,IEnumerable<string>ignoredTables){vartables=connection.Query<string>("SELECT name FROM sqlite_schema WHERE type = 'table'");returntables.Except(ignoredTables).ToList();}staticIList<string>OrderTables(IList<string>tables,IList<(stringPrimaryKeyTable,stringForeignKeyTable)>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(stringleafinleafs){tables.Remove(leaf);foreach(varrelationshipinrelationships.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: