-- ============================================================================
-- SCRIPT: 04_monitoring_view.sql
-- DESCRIPTION: Creates a view to monitor partition status and sizes.
-- ============================================================================

CREATE OR REPLACE VIEW partitions.monitoring AS
SELECT
    parent.relname AS parent_table,
    c.table_name,
    c.period,
    c.keep_history,
    count(child.relname) AS partition_count,
    pg_size_pretty(sum(pg_total_relation_size(child.oid))) AS total_size,
    min(child.relname) AS oldest_partition,
    max(child.relname) AS newest_partition,
    c.last_updated
FROM partitions.config c
JOIN pg_class parent ON parent.relname = c.table_name
LEFT JOIN pg_inherits ON pg_inherits.inhparent = parent.oid
LEFT JOIN pg_class child ON pg_inherits.inhrelid = child.oid
WHERE parent.relkind = 'p' -- Only partitioned tables
GROUP BY parent.relname, c.table_name, c.period, c.keep_history, c.last_updated;
