feat: estimate table size

This commit is contained in:
Ankush Menat 2025-01-31 20:24:28 +05:30
parent 2d4d3c18f5
commit 4406116f86
4 changed files with 24 additions and 0 deletions

View file

@ -1250,6 +1250,10 @@ class Database:
frappe.cache.set_value(f"doctype:count:{dt}", count, expires_in_sec=86400)
return count
def estimate_count(self, doctype: str) -> int:
"""Get estimated count of total rows in a table."""
raise NotImplementedError
@staticmethod
def format_date(date):
return getdate(date).strftime("%Y-%m-%d")

View file

@ -541,3 +541,12 @@ class MariaDBDatabase(MariaDBConnectionUtil, MariaDBExceptionUtil, Database):
finally:
self._cursor = original_cursor
new_cursor.close()
def estimate_count(self, doctype: str):
"""Get estimated count of total rows in a table."""
from frappe.utils.data import cint
table = get_table_name(doctype)
count = self.sql("select table_rows from information_schema.tables where table_name = %s", table)
return cint(count[0][0]) if count else 0

View file

@ -483,6 +483,14 @@ class PostgresDatabase(PostgresExceptionUtil, Database):
def get_database_list(self):
return self.sql("SELECT datname FROM pg_database", pluck=True)
def estimate_count(self, doctype: str):
"""Get estimated count of total rows in a table."""
from frappe.utils.data import cint
table = get_table_name(doctype)
count = self.sql("select reltuples from pg_class where relname = %s", table)
return cint(count[0][0]) if count else 0
def modify_query(query):
""" "Modifies query according to the requirements of postgres"""

View file

@ -510,6 +510,9 @@ class TestDB(IntegrationTestCase):
self.assertEqual(frappe.db.exists(dt, [["name", "=", dn]]), dn)
def test_estimated_count(self):
self.assertGreater(frappe.db.estimate_count("DocField"), 100)
def test_datetime_serialization(self):
dt = now_datetime()
dt = dt.replace(microsecond=0)