ALTER SESSION SET CONTAINER=FREEPDB1;

DECLARE
  v_exists NUMBER := 0;
BEGIN
  SELECT COUNT(*) INTO v_exists FROM dba_users WHERE username = 'NETDATA';
  IF v_exists = 0 THEN
    EXECUTE IMMEDIATE 'CREATE USER netdata IDENTIFIED BY "Netdata123!"';
  END IF;
END;
/

GRANT CONNECT TO netdata;
GRANT SELECT_CATALOG_ROLE TO netdata;
GRANT SELECT ON V_$SQLSTATS TO netdata;
GRANT SELECT ON V_$SESSION TO netdata;
GRANT SELECT ON V_$SQL TO netdata;
GRANT EXECUTE ON DBMS_LOCK TO netdata;

BEGIN
  EXECUTE IMMEDIATE 'CREATE TABLE netdata.demo (id NUMBER PRIMARY KEY, name VARCHAR2(64))';
EXCEPTION
  WHEN OTHERS THEN
    IF SQLCODE != -955 THEN
      RAISE;
    END IF;
END;
/

MERGE INTO netdata.demo d
USING (SELECT 1 AS id, 'alpha' AS name FROM dual) s
ON (d.id = s.id)
WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name);

COMMIT;
