summary refs log tree commit diff
diff options
context:
space:
mode:
authorAndrew Morgan <andrewm@element.io>2022-08-04 14:54:51 +0100
committerAndrew Morgan <andrewm@element.io>2022-08-04 14:54:55 +0100
commitda7c7f39c403be6ab28b0f6aea86f0c6907988fd (patch)
tree2e81dde252d832f0eef64b73f8611d5f315d4b21
parentRemove unnecessary if condition (diff)
downloadsynapse-da7c7f39c403be6ab28b0f6aea86f0c6907988fd.tar.xz
Add simple_truncate database method.
-rw-r--r--synapse/storage/database.py43
1 files changed, 43 insertions, 0 deletions
diff --git a/synapse/storage/database.py b/synapse/storage/database.py
index 46be3b3876..4b62ffbb5a 100644
--- a/synapse/storage/database.py
+++ b/synapse/storage/database.py
@@ -2200,6 +2200,49 @@ class DatabasePool:
 
         return txn.rowcount
 
+    async def simple_truncate(self, table: str, desc: str) -> int:
+        """Executes a TRUNCATE query on the given table, deleting all rows.
+
+        SQLite does not support TRUNCATE, thus a 'DELETE FROM table_name' will
+        be used instead.
+
+        Args:
+            table: The name of the table to delete all rows from.
+            desc: description of the transaction, for logging and metrics.
+
+        Returns:
+            The number of deleted rows.
+        """
+        return await self.runInteraction(
+            desc, self._simple_truncate_txn, table, db_autocommit=True
+        )
+
+    @staticmethod
+    def _simple_truncate_txn(
+        txn: LoggingTransaction,
+        table: str,
+    ) -> int:
+        """Executes a TRUNCATE query on the given table, deleting all rows.
+
+        SQLite does not support TRUNCATE, thus a 'DELETE FROM table_name' will
+        be used instead.
+
+        Args:
+            txn: Transaction object
+            table: The name of the table to delete all rows from.
+
+        Returns:
+            The number of deleted rows.
+        """
+        if isinstance(txn.database_engine, PostgresEngine):
+            sql = "TRUNCATE %s" % table
+        else:
+            # SQLite does not support the TRUNCATE command
+            sql = "DELETE FROM %s" % table
+
+        txn.execute(sql)
+        return txn.rowcount
+
     def get_cache_dict(
         self,
         db_conn: LoggingDatabaseConnection,