-- ============================================================================
-- ROA TABLESPACE CREATION
-- ============================================================================
-- Creates ROA tablespace with 1GB initial size, autoextend enabled
-- Works for both non-CDB (Oracle SE) and PDB (Oracle XE in XEPDB1)
--
-- Usage:
--   @create-tablespace.sql "D:\Oracle\oradata\ORCL"
--   @create-tablespace.sql "D:\Oracle\oradata\XE\XEPDB1"
--
-- Parameters:
--   &1 - Datafile directory path (e.g., D:\Oracle\oradata\ORCL)
--
-- Connect as: SYSDBA
-- ============================================================================

SET ECHO OFF
SET FEEDBACK ON
SET SERVEROUTPUT ON
WHENEVER SQLERROR CONTINUE

PROMPT
PROMPT ========================================
PROMPT Creating ROA Tablespace
PROMPT ========================================
PROMPT

-- Define datafile path
DEFINE datafile_dir = "&1"

PROMPT Datafile directory: &datafile_dir

-- Check if tablespace already exists
DECLARE
    v_count NUMBER;
BEGIN
    SELECT COUNT(*) INTO v_count
    FROM dba_tablespaces
    WHERE tablespace_name = 'ROA';

    IF v_count > 0 THEN
        DBMS_OUTPUT.PUT_LINE('WARNING: Tablespace ROA already exists. Skipping creation.');
    ELSE
        DBMS_OUTPUT.PUT_LINE('Creating tablespace ROA...');
    END IF;
END;
/

-- Create tablespace if it doesn't exist
DECLARE
    v_count NUMBER;
    v_sql VARCHAR2(1000);
BEGIN
    SELECT COUNT(*) INTO v_count
    FROM dba_tablespaces
    WHERE tablespace_name = 'ROA';

    IF v_count = 0 THEN
        v_sql := 'CREATE SMALLFILE TABLESPACE "ROA" ' ||
                 'DATAFILE ''&datafile_dir\ROA.DBF'' ' ||
                 'SIZE 1000M ' ||
                 'AUTOEXTEND ON NEXT 10M MAXSIZE UNLIMITED ' ||
                 'LOGGING ' ||
                 'EXTENT MANAGEMENT LOCAL ' ||
                 'SEGMENT SPACE MANAGEMENT AUTO';
        EXECUTE IMMEDIATE v_sql;
        DBMS_OUTPUT.PUT_LINE('Tablespace ROA created successfully.');
    END IF;
END;
/

PROMPT
PROMPT Verifying tablespace creation:
SELECT tablespace_name, status, contents, extent_management, segment_space_management
FROM dba_tablespaces
WHERE tablespace_name = 'ROA';

PROMPT
PROMPT Datafile information:
SELECT file_name, bytes/1024/1024 AS size_mb, autoextensible, maxbytes/1024/1024 AS max_mb
FROM dba_data_files
WHERE tablespace_name = 'ROA';

PROMPT
PROMPT ========================================
PROMPT ROA Tablespace Creation Complete
PROMPT ========================================
PROMPT
