-- Upsert studio project data from RDS to Snowflake
-- This query inserts new records and updates existing ones based on ID and partition

MERGE INTO {studio_project_table_name} AS target
USING 
(
    SELECT 
        $1:id as id,
        $1:created_at as created_at,
        $1:updated_at as updated_at,
        $1:title as title,
        $1:user_id as user_id,
        $1:archived as archived,
        date(to_timestamp(created_at)) as p_date,
        hour(to_timestamp(created_at)) as p_hour
    FROM {stage_path} (file_format => 'BASIC_PARQUET_LOADER', pattern => ('.*.parquet'))
) AS source
ON (target.id = source.id AND target.p_date = source.p_date AND target.p_hour = source.p_hour)
WHEN MATCHED THEN
    UPDATE SET 
        target.created_at = source.created_at,
        target.updated_at = source.updated_at,
        target.title = source.title,
        target.user_id = source.user_id,
        target.archived = source.archived,
        target.p_date = source.p_date,
        target.p_hour = source.p_hour
WHEN NOT MATCHED THEN
    INSERT (id, created_at, updated_at, title, user_id, archived, p_date, p_hour)
    VALUES (source.id, source.created_at, source.updated_at, source.title, source.user_id, source.archived, source.p_date, source.p_hour);
