import pyodbc


class DatabaseInfo:
    conn: pyodbc.Connection

    def __init__(self):
        self._conn = pyodbc.connect("DSN=GC;UID=sa;PWD=Mffu3011#")

    def databases(self):
        res = self._conn.execute("SELECT name FROM master.sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')")
        return res.fetchall()

    def table_size(self, database):
        self._conn.execute(f"USE {database}")
        res = self._conn.execute("""
            SELECT db_name() as DatabaseName, s.name AS SchemaName, t.name AS TableName, p.rows AS RowCounts,
                SUM(a.total_pages) * 8 AS TotalSpaceKB,
                SUM(a.used_pages) * 8 AS UsedSpaceKB,
                (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
                u.last_user_update AS LastChanged
            FROM sys.tables AS t
            INNER JOIN sys.indexes AS i ON t.object_id = i.object_id
            INNER JOIN sys.partitions AS p ON i.object_id = p.object_id AND i.index_id = p.index_id
            INNER JOIN sys.allocation_units AS a ON p.partition_id = a.container_id
            LEFT OUTER JOIN sys.schemas AS s ON t.schema_id = s.schema_id
            LEFT OUTER JOIN sys.dm_db_index_usage_stats AS u ON t.object_id = u.object_id
            WHERE (t.name NOT LIKE 'dt%') AND (t.is_ms_shipped = 0) AND (i.object_id > 255)
            GROUP BY s.name, t.name, p.rows
            ORDER BY 1, 2, 3""")
        return res.fetchall()
