Dropping Oracle connections using a query - oracle

I wanted to drop/kill connections made to specific schema of a database. Could you please sugest a prudent way to do this?
Cheers

In order to prevent a user from connecting you could lock the account:
ALTER USER usr ACCOUNT LOCK;
If you want to disconnect all sessions of a user, you could use the method described in another SO:
BEGIN
FOR x IN (SELECT Sid, Serial# FROM v$session WHERE username = 'USR') LOOP
EXECUTE IMMEDIATE 'Alter System Kill Session ''' || x.Sid || ','
|| x.Serial# || ''' IMMEDIATE';
END LOOP;
END;

Related

How to delete sequences and procedures during logoff trigger?

Could you please help me in a unique situation I am in. I am receiving "ORA-30511: invalid DDL operation in system triggers" when dropping sequences and procedures during logoff trigger.
I need to delete tables, sequences and procedures of users before logoff event happens. I am writing the table details in DB_OBJECTS table upon create using a separate trigger. Below is my logoff trigger - could you please help me where I am doing wrong. Dropping tables is working fine in the below code. Only Dropping sequences and procedures is giving me "ORA-30511: invalid DDL operation in system triggers" error.
CREATE OR REPLACE TRIGGER DELETE_BEFORE_LOGOFF
BEFORE LOGOFF ON DATABASE
DECLARE
USER_ID NUMBER := SYS_CONTEXT('USERENV', 'SESSIONID');
BEGIN
FOR O IN (SELECT USER, OBJECT_NAME, OBJECT_TYPE
FROM DB_OBJECTS WHERE SID = USER_ID
AND USERNAME = USER AND SYSDATE > CREATED_DTTM) LOOP
IF O.OBJECT_TYPE = 'TABLE' THEN
EXECUTE IMMEDIATE 'DROP TABLE ' || O.USER || '.' || O.OBJECT_NAME || ' CASCADE CONSTRAINTS';
ELSIF O.OBJECT_TYPE = 'SEQUENCE' THEN
EXECUTE IMMEDIATE 'DROP SEQUENCE ' || O.USER || '.' || O.OBJECT_NAME;
ELSIF O.OBJECT_TYPE = 'PROCEDURE' THEN
EXECUTE IMMEDIATE 'DROP PROCEDURE ' || O.USER || '.' || O.OBJECT_NAME;
END IF;
END LOOP;
EXCEPTION WHEN NO_DATA_FOUND THEN NULL;
END;
/
That's a simple one.
Error code: ORA-30511
Description: invalid DDL operation in system triggers
Cause: An attempt was made to perform an invalid DDL operation in a system trigger. Most DDL operations currently are not supported in system triggers. The only currently supported DDL operations are table operations and ALTER/COMPILE operations.
Action: Remove invalid DDL operations in system triggers.
That's why only
Dropping tables is working fine
succeeded.
Therefore, you can't do that using trigger.
You asked (in a comment) how to drop these objects, then. Manually, as far as I can tell. Though, that's quite unusual - what if someone accidentally logs off? You'd drop everything they created. If you use that schema for educational purposes (for example, every student gets their own schema), then you could create a "clean-up" script you'd run once class is over. Something like this:
SET SERVEROUTPUT ON;
DECLARE
l_user VARCHAR2 (30) := 'SCOTT';
l_str VARCHAR2 (200);
BEGIN
IF USER = l_user
THEN
FOR cur_r IN (SELECT object_name, object_type
FROM user_objects
WHERE object_name NOT IN ('EMP',
'DEPT',
'BONUS',
'SALGRADE'))
LOOP
BEGIN
l_str :=
'drop '
|| cur_r.object_type
|| ' "'
|| cur_r.object_name
|| '"';
DBMS_OUTPUT.put_line (l_str);
EXECUTE IMMEDIATE l_str;
EXCEPTION
WHEN OTHERS
THEN
NULL;
END;
END LOOP;
END IF;
END;
/
PURGE RECYCLEBIN;
It is far from being perfect; I use it to clean up my Scott schema I use to answer questions on various sites so - once it becomes a mess, I run that PL/SQL code several times (because of possible foreign key constraint).
Other option is to keep a create user script(s) (along with all grant statements) and - once class is over - drop existing user and simply recreate it.
Or, if that user contains some pre-built tables, keep export file (I mean, result of data pump export) and import it after the user is dropped.
There are various options - I don't know whether I managed to guess correctly, but now you have something to think about.

Permissions for two schemas in Oracle

I have two schemas MONITORING and MONITORING_CONFIGURATION.
I am trying to create a table to which both schemas have access.
I am running the script as MONITORING_CONFIGURATION, but it is not completely ruled out that it runs as MONITORING. Can I simply ignore the error that i am getting on GRANT and get permissions because I created the table as MONITORING_CONFIGURATION while still achieving the goal of a table to which both schemas have access? The error is SQL-Fehler: ORA-01749: you may not GRANT/REVOKE privileges to/from yourself
01749. 00000 - "you may not GRANT/REVOKE privileges to/from yourself"
CREATE TABLE "MONITORING"."WEB_SERVICE_STATUS"
( "WEB_SERVICE_STATUS_ID" NUMBER,
"WEB_SERVICE_ID" NUMBER,
"STATUS" CHAR(1)
);
GRANT ALTER, DELETE, INDEX, INSERT, SELECT, UPDATE, REFERENCES, ON COMMIT REFRESH, QUERY REWRITE, DEBUG, FLASHBACK ON "MONITORING"."WEB_SERVICE_STATUS" TO "MONITORING_CONFIGURATION";
When I do select * from "MONITORING"."WEB_SERVICE_STATUS"; it appears I have the SELECT permission.
I would drop the table, and then rerun that exact script as MONITORING. Then you will know you have the correct grants for both users.
Does the following help - use PLSQL to add logic around what the current user is then taken the appropriate action via dynamic SQL using EXECUTE IMMEDIATE:
DECLARE
vsql VARCHAR2(1000);
BEGIN
IF user = 'MONITORING' THEN
DBMS_OUTPUT.PUT_LINE ( ' Running as ' || USER || ' - creating table' );
vsql := 'CREATE TABLE "MONITORING"."WEB_SERVICE_STATUS"
( "WEB_SERVICE_STATUS_ID" NUMBER,
"WEB_SERVICE_ID" NUMBER,
"STATUS" CHAR(1)
)';
EXECUTE IMMEDIATE vsql;
DBMS_OUTPUT.PUT_LINE ( ' Running as ' || USER || ' - issuing grant' );
vsql := ' GRANT ALTER, DELETE, INDEX, INSERT, SELECT, UPDATE, REFERENCES, ON COMMIT REFRESH, QUERY REWRITE, DEBUG, FLASHBACK ON "MONITORING"."WEB_SERVICE_STATUS" TO "MONITORING_CONFIGURATION"';
EXECUTE IMMEDIATE vsql;
ELSE
DBMS_OUTPUT.PUT_LINE ( ' Running as ' || USER || ' - no action taken' );
END IF;
END;
/
Are you trying to achieve connection between to schema- ?
CREATE PUBLIC DATABASE LINK MONITORING_CONFIGURATION
USING 'MONITORING_CONFIGURATION';

Issues with user/system oracle role access and permissions

I am having a bit of an odd issue when it comes to oracle roles and my schema creation code, I will do my best to describe my problem below:
On schema create a role is created using the schema name provided.
EXECUTE IMMEDIATE 'CREATE ROLE ' || USER || 'ADMIN_R';
This role is then granted to specific users associated with that schema.
DECLARE
V_ROLE_NAME CONSTANT VARCHAR2(30) := USER || 'ADMIN_R';
CURSOR C_ADMIN_USERS IS
SELECT USERNAME FROM DBUSERS WHERE ROLE = 'ADMINISTRATION';
BEGIN
FOR REC IN C_ADMIN_USERS
LOOP
EXECUTE IMMEDIATE 'GRANT ' || V_ROLE_NAME || ' TO ' || REC.USERNAME || ' WITH ADMIN OPTION';
END LOOP;
END;
Users with this role have access to a special administration package.
EXECUTE IMMEDIATE 'GRANT EXECUTE ON P_ADMINISTRATION TO ' || USER || 'ADMIN_R';
The problem is When I drop the schema it does not drop this role (belongs to oracle), so when I recreate this schema the whole process fails because this role already exists. I also can't grant access to this role without logging into the system users which I want to avoid. The simple solution would be to just drop it, but my concern in that instance is that the DBA has been using that role to grant access to additional users and potentially additional packages, which would all be lost if we just arbitrarily drop the role to recreate it.
Any assistance would be greatly appreciated.
You could surround your role create with something like this:
SELECT COUNT(*)
INTO v_count
FROM DBA_ROLES
WHERE ROLE = USER || 'ADMIN_R';
IF v_count = 0 THEN
--grant your roles
END IF;
You can grant the same privilege as many times as you like.
you can drop the role before create
declare
i int;
begin
select count(*) into i
from dba_roles where role = USER||'ADMIN_R';
if (0 != i) then
execute immediate 'drop role '||USER||'ADMIN_R';
dbms_output.put_line('Role ' ||USER||'ADMIN_R has been dropped');
end if;
execute immediate 'create role '||USER||'ADMIN_R';
dbms_output.put_line('Role ' ||USER||'ADMIN_R has been created');
end;
1st try:
Role SCMADMIN_R has been created
2nd try:
Role SCMADMIN_R has been dropped
Role SCMADMIN_R has been created

ALTER SYSTEM is not executing in jruby

I am trying to execute plsql block in which I have ALTER USER and then ALTER SYSTEM statements one after other. ALTER USER is executing but ALTER SYSTEM is not.
My code does the following:
1. Connects to the database using jdbc driver.
2. Changes the login user of a particular user (here I am using ALTER USER statement).
3. Kills the session of that particular user before dropping it (here I use ALTER SYSTEM statement which is not running).
Below is the code fragment which is not running for me.
users = ['ABC', 'XYZ']
$users.each do|x|
if( is_usr?("#{x}") )
puts "Working on #{x}"
stmt = <<-EOF
DECLARE
id NUMber(10);
s_num NUMBER(10);
CURSOR cur IS
SELECT sid, serial#
FROM v$session WHERE username like ('#{x}');
BEGIN
OPEN cur;
LOOP
FETCH cur INTO id, s_num;
dbms_output.put_line(id||' '||s_num);
EXECUTE IMMEDIATE 'ALTER USER #{x} IDENTIFIED BY dummypass';
EXECUTE IMMEDIATE 'ALTER SYSTEM KILL SESSION ''' ||id|| ',' ||s_num||'''';
EXIT when sess_cur%notfound;
END LOOP;
CLOSE cur;
END;
EOF
puts "#{stmt}"
plsql = #conn.create_statement
plsql.execute_update(stmt)
else
puts "#{x} does not exist"
end
end
Output looks like this:
Working on ABC
DECLARE
id NUMber(10);
s_num NUMBER(10);
CURSOR cur IS
SELECT sid, serial#
FROM v$session WHERE username like ('ABC');
BEGIN
OPEN cur;
LOOP
FETCH cur INTO id, s_num;
dbms_output.put_line(id||' '||s_num);
EXECUTE IMMEDIATE 'ALTER USER ABC IDENTIFIED BY dummypass';
EXECUTE IMMEDIATE 'ALTER SYSTEM KILL SESSION ''' ||id|| ',' ||s_num||'''';
EXIT when sess_cur%notfound;
END LOOP;
CLOSE cur;
END;
Working on XYZ
DECLARE
id NUMber(10);
s_num NUMBER(10);
CURSOR cur IS
SELECT sid, serial#
FROM v$session WHERE username like ('XYZ');
BEGIN
OPEN cur;
LOOP
FETCH cur INTO id, s_num;
dbms_output.put_line(id||' '||s_num);
EXECUTE IMMEDIATE 'ALTER USER XYZ IDENTIFIED BY dummypass';
EXECUTE IMMEDIATE 'ALTER SYSTEM KILL SESSION ''' ||id|| ',' ||s_num||'''';
EXIT when sess_cur%notfound;
END LOOP;
CLOSE cur;
END;
Observation after running this script:
1. I am able to login to db as ABC and XYZ with 'dummypass' as password. Hence I know that ALTER USER statement has been run successfully.
2. I still see all the same session ids and serial#s for 'ABC' and 'XYZ'. Hence I know that ALTER SYSTEM statement did not run.
I am struggling in fixing this one since past 3-days. Please help me in fixing this. Thanks in advance.
ALTER SYSTEM KILL SESSION does not instantly get rid of the session. It only marks it for being killed. Normally a background process will get rid of it in a minute. If there are many uncommitted changes it can take a very long time to rollback everything.
There is no way to speed up the process. The best you can do it ignore those sessions with a predicate like where v$session.status <> 'KILLED'.

Dropping connected users in Oracle database

I want to drop some users in Oracle DB using sqlplus but I am getting error:
SQL> DROP USER test CASCADE;
DROP USER test CASCADE
*
ERROR at line 1:
ORA-01940: cannot drop a user that is currently connected
I followed the link in SO to find out the sessions - Dropping a connected user from an Oracle 10g database schema
But when I ran the command I am not getting any results:
SQL> select sid,serial# from v$session where username = 'test';
no rows selected
Please help me how to drop users in this case.
Users are all capitals in v$session (and data dictionary views). If you match with capitals you should find your session to kill.
SELECT s.sid, s.serial#, s.status, p.spid
FROM v$session s, v$process p
WHERE s.username = 'TEST' --<<<--
AND p.addr(+) = s.paddr
/
Pass actual SID and SERIAL# values for user TEST then drop user...:
ALTER SYSTEM KILL SESSION '<SID>, <SERIAL>'
/
Solution :
login as sysdaba:
sqlplus / as sysdba
then:
sql>Shutdown immediate;
sql>startup restrict;
sql>drop user TEST cascade;
If you want to re-activate DB normally either reset the server or :
sql>Shutdown immediate;
sql>startup;
:)
Issue has been fixed using below procedure :
DECLARE
v_user_exists NUMBER;
user_name CONSTANT varchar2(20) := 'SCOTT';
BEGIN
LOOP
FOR c IN (SELECT s.sid, s.serial# FROM v$session s WHERE upper(s.username) = user_name)
LOOP
EXECUTE IMMEDIATE
'alter system kill session ''' || c.sid || ',' || c.serial# || ''' IMMEDIATE';
END LOOP;
BEGIN
EXECUTE IMMEDIATE 'drop user ' || user_name || ' cascade';
EXCEPTION WHEN OTHERS THEN
IF (SQLCODE = -1940) THEN
NULL;
ELSE
RAISE;
END IF;
END;
BEGIN
SELECT COUNT(*) INTO v_user_exists FROM dba_users WHERE username = user_name;
EXIT WHEN v_user_exists = 0;
END;
END LOOP;
END;
/
Do a query:
SELECT * FROM v$session s;
Find your user and do the next query (with appropriate parameters):
ALTER SYSTEM KILL SESSION '<SID>, <SERIAL>';
If you use RAC then you need to use GV$* views instead V$*.
Try to find your session by
select * from gv$session where username = 'test';
and then you can kill the session by
alter system kill session 'sid, serial#, #inst_id' immediate;
This can be as simple as:
SQL> ALTER SYSTEM ENABLE RESTRICTED SESSION;
SQL> DROP USER test CASCADE;
SQL> ALTER SYSTEM DISABLE RESTRICTED SESSION;
go to services in administrative tools and select oracleserviceSID and restart it
I was trying to follow the flow described here - but haven't luck to completely kill the session.. Then I fond additional step here:
http://wyding.blogspot.com/2013/08/solution-for-ora-01940-cannot-drop-user.html
What I did:
1. select 'alter system kill session ''' || sid || ',' || serial# || ''';' from v$session where username = '<your_schema>'; - as described below.Out put will be something like this:alter system kill session '22,15' immediate;
2. alter system disconnect session '22,15' IMMEDIATE ; - 22-sid, 15-serial - repeat the command for each returned session from previous command
3. Repeat steps 1-2 while select... not return an empty table
4. Call
drop user...
What was missed - call alter system disconnect session '22,15' IMMEDIATE ; for each of session returned by select 'alter system kill session '..
Sometimes Oracle drop user takes long time to execute. In that case user might be connected to the database. Better you can kill user session and drop the user.
SQL> select 'alter system kill session ''' || sid || ',' || serial# || ''' immediate;' from v$session where username ='&USERNAME';
SQL> DROP USER barbie CASCADE;
I had the same problem, Oracle config in default affects letter register. In exact my Scheme_Name was written all Capital letters. You can see your Scheme_Name on "Other Users" tab, if you are using Oracle S
Basically I believe that killing all sessions should be the solution, but...
I found similar discussion - https://community.oracle.com/thread/1054062 to my problem and that was I had no sessions for that users, but I still received the error. I tried also second the best answer:
sql>Shutdown immediate;
sql>startup restrict;
sql>drop user TEST cascade;
What worked for me at the end was to login as the user, drop all tables manually - select for creating drop statements is
select 'drop table ' || TABLE_NAME || ';' from user_tables;
(Needs to be re-run several times because of references)
I have no idea how is that related, I dropped also functions and sequences (because that was all I had in schema)
When I did that and I logged off, I had several sessions in v$session table and when I killed those I was able to drop user.
My DB was still started in restricted mode (not sure if important or not).
Might help someone else.
BTW: my Oracle version is Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
//'SYS' is username from where you wanted to kill session'
SELECT * FROM DBA_TAB_PRIVS WHERE GRANTEE = 'SYS';
**Step 1:**
CREATE OR REPLACE PROCEDURE sys.kill_session(p_sid NUMBER, p_serial NUMBER)
AS
v_user VARCHAR2(30);
BEGIN
SELECT MAX(username)
INTO v_user
FROM v$session
WHERE sid = p_sid
AND serial# = p_serial;
**Step 2**
create or replace procedure kill_session( p_sid in number, p_serial# in number)
is v_count pls_integer;
BEGIN
select count(*) into v_count
from V$session
where username = 'SYS'
and sid = p_sid
and serial# = p_serial# ;
if ( v_count = 1 )
then
execute immediate '
alter system kill session ''' ||
to_char(p_sid,'999999')||','||
to_char(p_serial#,'999999')||'''';
else
raise_application_error( -20001,
'You do not own session ''' ||
p_sid || ',' || p_serial# ||
'''' );
end if;
END;
/
**Step 3**
grant execute on kill_session to SYS;
**Step 4**
select inst_id, sid, serial#, username, action, program, service_name, con_id from gv$session where username like 'FCM_469';
Check there will be no sessions now
**Step 5**
DROP USER USER_345 CASCADE;
Output:User Dropped
Here's how I "automate" Dropping connected users in Oracle database:
# A shell script to Drop a Database Schema, forcing off any Connected Sessions (for example, before an Import)
# Warning! With great power comes great responsibility.
# It is often advisable to take an Export before Dropping a Schema
if [ "$1" = "" ]
then
echo "Which Schema?"
read schema
else
echo "Are you sure? (y/n)"
read reply
[ ! $reply = y ] && return 1
schema=$1
fi
sqlplus / as sysdba <<EOF
set echo on
alter user $schema account lock;
-- Exterminate all sessions!
begin
for x in ( select sid, serial# from v\$session where username=upper('$schema') )
loop
execute immediate ( 'alter system kill session '''|| x.Sid || ',' || x.Serial# || ''' immediate' );
end loop;
dbms_lock.sleep( seconds => 2 ); -- Prevent ORA-01940: cannot drop a user that is currently connected
end;
/
drop user $schema cascade;
quit
EOF

Resources