Oracle права на тип
Полномочия – это право на выполнение конкретного типа SQL-оператора или на доступ к объекту базы данных, принадлежащему другому пользователю. В базе данных Oracle необходимо явно предоставить пользователю полномочия для выполнения любых действий, включая подключение к базе данных или выборку, изменение и обновление данных в любой таблице, кроме собственной.
Существуют два основных типа полномочий Oracle: системные полномочия и объектные полномочия. Для предоставления пользователям как системных, так и объектынх полномочий служит оператор GRANT.
Системные полномочия:
Системные полномочия позволяют пользователю выполнить конкретное действие в базе данных либо действие с любым объектом схемы, конкретного типа. Хороший пример первого типа системных полномочий – полномочия, которые позволяют подключаться к базе данных, носящие название полномочий CONNECT. Другими полномочиями этого типа являются полномоичия CREATE TABLESPACE, CREATE USER, DROP USER и ALTER USER.
Второй класс системных полномоичий предоставляет пользователям право на выполнение операций, которыевлияют на объекты в любой схеме. Примерами этого типа системных полномочий служат ANALYZE ANY TABLE, GRANT ANY PRIVILEGE, INSERT ANY TABLE, DELETE ANY TABLE и т.п. Системные полномочия являются очень мощным средством и выдача их не тому пользователю может оказать разруши тельное влияние на базу данных.
Ниже перечислены некоторые наиболее часто используемые полномочия базы данных Oracle:
- ADVISOR
- ALTER DATABASE
- ALTER SYSTEM
- AUDIT SYSTEM
- CREATE DATABASE LINK
- CREATE TABLE
- CREATE ANY INDEX
- CREATE SESSION
- CREATE TABLESPACE
- CREATE USER
- DROP USER
- INSERT ANY TABLE
Пример:
Системные полномочия:
Системные полномочия позволяют пользователю выполнить конкретное действие в базе данных либо действие с любым объектом схемы, конкретного типа. Хороший пример первого типа системных полномочий – полномочия, которые позволяют подключаться к базе данных, носящие название полномочий CONNECT. Другими полномочиями этого типа являются полномоичия CREATE TABLESPACE, CREATE USER, DROP USER и ALTER USER.
Второй класс системных полномоичий предоставляет пользователям право на выполнение операций, которыевлияют на объекты в любой схеме. Примерами этого типа системных полномочий служат ANALYZE ANY TABLE, GRANT ANY PRIVILEGE, INSERT ANY TABLE, DELETE ANY TABLE и т.п. Системные полномочия являются очень мощным средством и выдача их не тому пользователю может оказать разруши тельное влияние на базу данных.
Ниже перечислены некоторые наиболее часто используемые полномочия базы данных Oracle:
- ADVISOR
- ALTER DATABASE
- ALTER SYSTEM
- AUDIT SYSTEM
- CREATE DATABASE LINK
- CREATE TABLE
- CREATE ANY INDEX
- CREATE SESSION
- CREATE TABLESPACE
- CREATE USER
- DROP USER
- INSERT ANY TABLE
Пример:
Привилегии DML
Для объектных таблиц традиционные привилегии SELECT , INSERT , UPDATE и DELETE также имеют смысл. Пользователь, обладающий только привилегией SELECT для объектной таблицы, может загрузить любые реляционные столбцы базового типа, на котором основана таблица, но ему не удастся загрузить объект как объект (то есть VALUE , TREAT , REF и DEREF ему недоступны). Другие привилегии DML — INSERT , UPDATE и DELETE — также применяются только к реляционной интерпретации таблицы.
Аналогичным образом получатель не сможет использовать конструктор или другие объектные методы, если только владелец типа объекта не предоставит ему привилегию EXECUTE для объектного типа. Все столбцы, определенные в подтипах, останутся невидимыми.
Словарь данных
Типы, определяемые пользователем (объекты и коллекции), в словаре данных относятся к категории TYPE . Определения и тела объектных типов находятся в представлении USER_SOURCE (или DBA_SOURCE , или ALL_SOURCE ), как и спецификации и тела пакетов. В табл. 1 перечислены некоторые полезные запросы.
Таблица 1. Элементы словаря данных для объектных типов
Вопрос
Запрос, используемый для получения ответа
Какие объектные типы и типы коллекций я создал?
SELECT * FROM user types;
SELECT * FROM user_objects WHERE object type = 'TYPE';
Как выглядят мои иерархии объектных типов?
SELECT RPAD(' ', 3*(LEVEL-1)) || type name
WHERE typecode = 'OBJECT'
CONNECT BY PRIOR type name = supertype name;
Какие атрибуты содержит тип foo ?
SELECT * FROM user_type_attrs
WHERE type_name = 'FOO';
Какие методы содержит тип foo?
SELECT * FROM user_type_methods
WHERE type_name = 'FOO';
Какие параметры получают методы foo?
SELECT * FROM user_method_params
WHERE type_name = 'FOO';
Какой тип данных возвращает метод bar типа foo ?
SELECT * FROM user_method_results
WHERE type_name = 'FOO' AND method_name = 'BAR';
Как выглядит исходный код foo , включая все команды ALTER ?
SELECT text FROM user source
WHERE name = 'FOO'
AND type = 'TYPE' /* или 'TYPE BODY' */ ORDER BY line;
Какие объектные таблицы реализуют foo ?
SELECT table_name FROM user_object_tables WHERE table_type = 'FOO';
Какие столбцы содержит объектная таблица f oo_tab (включая скрытые)?
SELECT column_name, data_type, hidden_column, virtual_column
WHERE table name = 'FOO TAB';
Какие столбцы реализуют foo ?
SELECT table_name, column_name FROM user_tab_columns WHERE data type = 'FOO';
Какие объекты базы данных зависят от foo ?
SELECT name, type FROM user_dependencies
WHERE referenced name = 'FOO';
Какие объектные представления я создал, какие OID при этом использовались?
SELECT view_name, view_type, oid_text FROM user_views
WHERE type text IS NOT NULL;
Как выглядит моя иерархия представлений? (Требует использования временной таблицы в версиях Oracle, которые не могут использовать подзапрос с CONNECT BY )
CREATE TABLE uvtemp AS
SELECT v.view_name, v.view_type, v.superview_name, v1.view_type superview_type FROM user_views v, user_views v1
WHERE v.superview_name = v1.view_name (+);
SELECT RPAD(' ', 3*(LEVEL-1)) || view_name
CONNECT BY PRIOR view_type = superview_type;
DROP TABLE uvtemp;
На основе какого запроса было определено представление foo_v ?
SET LONG 1000 -- or greater SELECT text FROM user_views
WHERE view name = 'FOO V';
Какие столбцы присутствуют в представлении foo_v ?
SELECT column_name, data_type_mod, data_type FROM user_tab_columns
WHERE table name = 'FOO V';
При работе со словарем данных Oracle могут возникнуть недоразумения из-за того, что объектные таблицы не видны в представлении USER_TABLES . Вместо этого список объектных таблиц присутствует в USER_OBJECT_TABLES (а также USER_ALL_TABLES ).
7.1.4 Example: Privileges on Object Types
This section presents several related examples, creating users or schemas and then granting privileges on them.
Example 7-1 creates three users or schemas, USER1 , USER2 , and USER3 , and grants them the CREATE SESSION and RESOURCE roles. Some of the subsequent examples in this chapter use these schemas.
This example requires you to create and use several passwords. If you plan to run the example, make these changes to your SQL code first.
For simplicity, this example does not perform the password management techniques that a deployed system normally uses. In a production environment, follow the Oracle Database password management guidelines, and disable any sample accounts.
See Oracle Database Security Guide for password management guidelines and other security recommendations.
Example 7-1 Creating User Schemas
Example 7-2 requires the input of a password, USER1 performs the CREATE and GRANT Data Definition Language (DDL) statements in the USER1 schema:
Example 7-2 Granting Privileges on Object Types
In Example 7-3, USER2 performs the CREATE DDL statement in the USER2 schema:
Example 7-3 Performing DDL Statements in USER2 Schema
In Example 7-4, the first two statements succeed because USER2 was granted the EXECUTE privilege with the GRANT option on USER1 's TYPE2 in the last line of Example 7-2 and Example 7-3 created type3 as an object using attr3 user1.type2 .
However, the last grant Example 7-4 fails because USER2 has not been granted the EXECUTE privilege with the GRANT option on USER1.TYPE1 .
Example 7-4 Performing Grants to USER3
In Example 7-5, USER3 has the necessary privileges to perform the following actions:
Example 7-5 Creating Tables and Types
Привилегия DEBUG
Если ваш коллега использует отладчик PL/SQL для анализа кода, использующего созданный вами тип, вы можете предоставить ему привилегию DEBUG :
Предоставление этой привилегии позволит другому разработчику заглянуть «за кулисы», изучить переменные, использованные в типе, и установить точки прерывания внутри методов.
Привилегия DEBUG также применяется к объектным представлениям, давая возможность отладки исходного кода PL/SQL триггеров INSTEAD OF .
7.1.5 Access Privileges on Objects, Types, and Tables
Object types only make use of the EXECUTE privilege.
However, object tables use all the same privileges as relational tables:
READ or SELECT lets you access an object and its attributes from the table.
UPDATE lets you modify attributes of objects in the table.
INSERT lets you add new objects to the table.
DELETE lets you delete objects from the table.
Similar table and column privileges regulate the use of table columns of object types.
Selecting columns of an object table does not require privileges on the type of the object table. Selecting the entire row object , however, does.
Consider the schema and queries created below in Example 7-6:
Example 7-6 SELECT Privileges on Type Access
For both queries, Oracle database checks the user's SELECT privilege for the object table emp . For the first query, the user needs to obtain the emp_type type information to interpret the data. When the query accesses the emp_type type, the database checks the user's EXECUTE privilege.
The second query, however, does not involve named types, so the database does not check type privileges.
Additionally, USER3 can perform queries such as these:
Note that in both queries, USER3 does not have explicit privileges on the underlying type. However, the statement succeeds because the type and table owners have the necessary privileges with the GRANT option.
Oracle database checks privileges on the following requests and returns an error if the requestor does not have the privilege for the action:
Pinning an object in the object cache using its REF value causes the database to check the READ or SELECT privilege on the object table containing the object and the EXECUTE privilege on the object type.
Modifying an existing object or flushing an object from the object cache causes the database to check the UPDATE privilege on the destination object table. Flushing a new object causes the database to check the INSERT privilege on the destination object table.
Deleting an object causes the database to check the DELETE privilege on the destination table.
Invoking a method causes the database to check the EXECUTE privilege on the corresponding object type.
Oracle database does not provide column level privileges for object tables.
Oracle Call Interface Programmer's Guide for tips and techniques for using OCI program effectively with objects
Use the GRANT statement to grant:
Roles to users, roles, and program units. The granted roles can be either user-defined (local or external) or predefined. For a list of predefined roles, refer to Oracle Database Security Guide .
Global roles (created with IDENTIFIED GLOBALLY ) are granted through enterprise roles and cannot be granted using the GRANT statement.
Notes on Authorizing Database Users
You can authorize database users through means other than the database and the GRANT statement.
Many Oracle Database privileges are granted through supplied PL/SQL and Java packages. For information on those privileges, refer to the documentation for the appropriate package.
Some operating systems have facilities that let you grant roles to Oracle Database users with the initialization parameter OS_ROLES . If you choose to grant roles to users through operating system facilities, then you cannot also grant roles to users with the GRANT statement, although you can use the GRANT statement to grant system privileges to users and system privileges and roles to other roles.
Note on Oracle Automatic Storage Management
A user authenticated AS SYSASM can use this statement to grant the system privileges SYSASM , SYSOPER , and SYSDBA to a user in the Oracle ASM password file of the current node.
Note on Editionable Objects
A GRANT operation to grant object privileges on an editionable object actualizes the object in the current edition. See Oracle Database Development Guide for more information about editions and editionable objects.
CREATE USER and CREATE ROLE for definitions of local, global, and external privileges
Oracle Database Security Guide for information about other authorization methods and for information about privileges
REVOKE for information on revoking grants
To grant a system privilege , one of the following conditions must be met:
You must have been granted the GRANT ANY PRIVILEGE system privilege. In this case, if you grant the system privilege to a role, then a user to whom the role has been granted does not have the privilege unless the role is enabled in user's session.
You must have been granted the system privilege with the ADMIN OPTION . In this case, if you grant the system privilege to a role, then a user to whom the role has been granted has the privilege regardless whether the role is enabled in the user's session.
To grant a role to a user or another role , you must have been directly granted the role with the ADMIN OPTION , or you must have been granted the GRANT ANY ROLE system privilege, or you must have created the role.
To grant a role to a program unit in your own schema , you must have been directly granted the role with either the ADMIN OPTION or the DELEGATE OPTION , or you must have been granted the GRANT ANY ROLE system privilege, or you must have created the role.
To grant a role to a program unit in another user's schema , you must be the user SYS and the role must have been created by the schema owner or directly granted to the schema owner.
To grant an object privilege on a user , by specifying the ON USER clause of the on_object_clause , you must be the user on whom the privilege is granted, or you must have been granted the object privilege on that user with the WITH GRANT OPTION , or you must have been granted the GRANT ANY OBJECT PRIVILEGE system privilege. If you can grant an object privilege on a user only because you have the GRANT ANY OBJECT PRIVILEGE , then the GRANTOR column of the *_TAB_PRIVS views displays the user on whom the privilege is granted rather than the user who issued the GRANT statement.
To grant an object privilege on all other types of objects , you must own the object, or the owner of the object must have granted you the object privileges with the WITH GRANT OPTION , or you must have been granted the GRANT ANY OBJECT PRIVILEGE system privilege. If you have the GRANT ANY OBJECT PRIVILEGE , then you can grant the object privilege only if the object owner could have granted the same object privilege. In this case, the GRANTOR column of the *_TAB_PRIVS views displays the object owner rather than the user who issued the GRANT statement.
To specify the CONTAINER clause, you must be connected to a multitenant container database (CDB). To specify CONTAINER = ALL , the current container must be the root.
Use the GRANT statement to grant:
Roles to users, roles, and program units. The granted roles can be either user-defined (local or external) or predefined. For a list of predefined roles, refer to Oracle Database Security Guide .
Global roles (created with IDENTIFIED GLOBALLY ) are granted through enterprise roles and cannot be granted using the GRANT statement.
Notes on Authorizing Database Users
You can authorize database users through means other than the database and the GRANT statement.
Many Oracle Database privileges are granted through supplied PL/SQL and Java packages. For information on those privileges, refer to the documentation for the appropriate package.
Some operating systems have facilities that let you grant roles to Oracle Database users with the initialization parameter OS_ROLES . If you choose to grant roles to users through operating system facilities, then you cannot also grant roles to users with the GRANT statement, although you can use the GRANT statement to grant system privileges to users and system privileges and roles to other roles.
Note on Oracle Automatic Storage Management
A user authenticated AS SYSASM can use this statement to grant the system privileges SYSASM , SYSOPER , and SYSDBA to a user in the Oracle ASM password file of the current node.
Note on Editionable Objects
A GRANT operation to grant object privileges on an editionable object actualizes the object in the current edition. See Oracle Database Development Guide for more information about editions and editionable objects.
CREATE USER and CREATE ROLE for definitions of local, global, and external privileges
Oracle Database Security Guide for information about other authorization methods and for information about privileges
REVOKE for information on revoking grants
To grant a system privilege , one of the following conditions must be met:
You must have been granted the GRANT ANY PRIVILEGE system privilege. In this case, if you grant the system privilege to a role, then a user to whom the role has been granted does not have the privilege unless the role is enabled in user's session.
You must have been granted the system privilege with the ADMIN OPTION . In this case, if you grant the system privilege to a role, then a user to whom the role has been granted has the privilege regardless whether the role is enabled in the user's session.
To grant a role to a user or another role , you must have been directly granted the role with the ADMIN OPTION , or you must have been granted the GRANT ANY ROLE system privilege, or you must have created the role.
To grant a role to a program unit in your own schema , you must have been directly granted the role with either the ADMIN OPTION or the DELEGATE OPTION , or you must have been granted the GRANT ANY ROLE system privilege, or you must have created the role.
To grant a role to a program unit in another user's schema , you must be the user SYS and the role must have been created by the schema owner or directly granted to the schema owner.
To grant an object privilege on a user , by specifying the ON USER clause of the on_object_clause , you must be the user on whom the privilege is granted, or you must have been granted the object privilege on that user with the WITH GRANT OPTION , or you must have been granted the GRANT ANY OBJECT PRIVILEGE system privilege. If you can grant an object privilege on a user only because you have the GRANT ANY OBJECT PRIVILEGE , then the GRANTOR column of the *_TAB_PRIVS views displays the user on whom the privilege is granted rather than the user who issued the GRANT statement.
To grant an object privilege on all other types of objects , you must own the object, or the owner of the object must have granted you the object privileges with the WITH GRANT OPTION , or you must have been granted the GRANT ANY OBJECT PRIVILEGE system privilege. If you have the GRANT ANY OBJECT PRIVILEGE , then you can grant the object privilege only if the object owner could have granted the same object privilege. In this case, the GRANTOR column of the *_TAB_PRIVS views displays the object owner rather than the user who issued the GRANT statement.
To specify the CONTAINER clause, you must be connected to a multitenant container database (CDB). To specify CONTAINER = ALL , the current container must be the root.
Продолжаем разговор об объектно-ориентированных возможностях Oracle и PL/SQL в целом, и об объектных представлениях в частности. При работе с объектными типами существует несколько способов получения информации о созданных вами типах и представлениях. Если возможностей команды SQL*Plus DESCRIBE окажется недостаточно, вероятно, придется перейти на прямые запросы к словарю данных Oracle.
7.1.3 Types Used in New Types or Tables
In addition to the permissions detailed in the previous sections, you need specific privileges to:
Create types or tables that use types created by other users.
Grant use of your new types or tables to other users.
You must have either the EXECUTE ANY TYPE system privilege or the EXECUTE object privilege for any type used to define a new type or table. You must have been granted these privileges explicitly, and not through a role.
To grant access to your new type or table to other users, you must have either the required EXECUTE object privileges with the GRANT option or the EXECUTE ANY TYPE system privilege with the option WITH ADMIN OPTION . You must have been granted these privileges explicitly, not through a role.
Привилегии
С объектными типами связана группа привилегий системного уровня:
- CREATE [ ANY ] TYPE — создание, изменение и удаление объектных типов и тел типов. ANY означает «в любой схеме».
- CREATE [ ANY ] VIEW — создание и удаление представлений, включая объектные представления. ANY означает «в любой схеме».
- ALTER ANY TYPE — использование средств ALTER TYPE с типами в любой схеме.
- EXECUTE ANY TYPE — использование объектного типа из любой схемы для таких целей, как создание экземпляров, выполнение методов, обращение по ссылкам и разыменование.
- UNDER ANY TYPE — создание подтипа в одной схеме как производного от типа в любой другой схеме.
- UNDER ANY VIEW — создание подпредставления в одной схеме как производного от представления в любой другой схеме.
Всего существуют три разновидности привилегий объектного уровня для объектных типов: EXECUTE , UNDER и DEBUG . Также важно понимать, как традиционные привилегии DML применяются к объектным таблицам и представлениям.
Объектыные полномочия:
Объектыне полномочия – это полномочия по отношению к различным типам объектов базы данных. Объектыные полномочия дают пользователю возможность выполнять действия с конкретной таблицей, представлением, материализованным представлением, последовательностью, процедурой, функцией или пакетом. Следовательно, всем пользователям базы данных нужны объектные полномочия.
Для выдачи объектных полномочий можно использовать следующие SQL-операторы.
Privileges for object types exist at the system level and the schema object level.
Привилегия EXECUTE
Если вы хотите, чтобы ваш коллега Джо использовал один из ваших типов в своих программах PL/SQL или таблицах, предоставьте ему привилегию EXECUTE :
Если Джо обладает привилегией, необходимой для создания синонимов, и работает в Oracle9i Database Release 2 и выше, он сможет создать синоним:
и использовать его следующим образом:
Джо также может использовать уточненную ссылку на тип scott.catalog_item_t .
Если вы ссылаетесь на объектный тип в хранимой программе, а потом предоставляете привилегию EXECUTE для этой программы пользователю или роли, наличие этой привилегии для типа не обязательно, даже если программа определяется с правами вызывающего. Аналогичным образом, если пользователь имеет привилегию DML для представления, содержащего триггер INSTEAD OF для этой операции DML, пользователю не понадобятся явные привилегии EXECUTE , если триггер ссылается на объектный тип, потому что триггеры выполняются с моделью прав создателя. Тем не менее привилегия EXECUTE необходима для пользователей, выполняющих анонимные блоки, в которых используется объектный тип.
Привилегия UNDER
Привилегия UNDER дает право создания подтипов. Она предоставляется следующим образом:
Чтобы схема могла создать подтип, необходимо определить супертип с правами вызывающего ( AUTHID CURRENT_USER ).
Она также может дать получателю право создания подпредставления:
7.1.2 Schema Object Privileges
Two schema object privileges apply to object types:
EXECUTE enables you to use the type to:
Define a column in a relational table.
Declare a variable or parameter of the named type.
EXECUTE lets you invoke the methods of a type, including the constructor.
Method execution and the associated permissions are the same as for stored PL/SQL procedures.
UNDER enables you to create a subtype or subview under the type or view on which the privilege is granted.
Only a grantor with the UNDER privilege WITH GRANT OPTION on the direct supertype or superview can grant the UNDER privilege on a subtype or subview.
The phrase WITH HIERARCHY OPTION grants a specified object privilege on all subtypes of the object. This option is meaningful only with the SELECT object privilege granted on an object view in an object view hierarchy. In this case, the privilege applies to all subviews of the view on which the privilege is granted.
7.1.1 System Privileges for Object Types
Oracle database defines the following system privileges for object types:
CREATE TYPE enables you to create object types in your own schema
CREATE ANY TYPE enables you to create object types in any schema
ALTER ANY TYPE enables you to alter object types in any schema
DROP ANY TYPE enables you to drop named types in any schema
EXECUTE ANY TYPE enables you to use and reference named types in any schema
UNDER ANY TYPE enables you to create subtypes under any non-final object types
UNDER ANY VIEW enables you to create subviews under any object view
The following roles are helpful:
The RESOURCE role includes the CREATE TYPE system privilege.
The DBA role includes all of these privileges.
Читайте также: