-- PostgreSQL Support Migration
-- Adds support for PostgreSQL databases and users in WHP

USE whp;

-- Create PostgreSQL databases tracking table
CREATE TABLE IF NOT EXISTS postgresql_databases (
    id INT AUTO_INCREMENT PRIMARY KEY,
    database_name VARCHAR(255) NOT NULL UNIQUE,
    owner_username VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    size_mb DECIMAL(10,2) DEFAULT 0,
    encoding VARCHAR(50) DEFAULT 'UTF8',
    INDEX idx_owner (owner_username),
    INDEX idx_dbname (database_name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create PostgreSQL users tracking table
CREATE TABLE IF NOT EXISTS postgresql_users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(100) NOT NULL UNIQUE,
    owner_username VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    can_create_db BOOLEAN DEFAULT FALSE,
    connection_limit INT DEFAULT -1,
    INDEX idx_owner (owner_username),
    INDEX idx_username (username)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create PostgreSQL user database access table
CREATE TABLE IF NOT EXISTS postgresql_user_database_access (
    id INT AUTO_INCREMENT PRIMARY KEY,
    pg_user_id INT NOT NULL,
    pg_database_id INT NOT NULL,
    privileges TEXT,
    granted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY unique_user_db (pg_user_id, pg_database_id),
    FOREIGN KEY (pg_user_id) REFERENCES postgresql_users(id) ON DELETE CASCADE,
    FOREIGN KEY (pg_database_id) REFERENCES postgresql_databases(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;