Oracle что такое owner
This chapter describes the central set of read-only reference tables and views of each Oracle database, known collectively as the data dictionary .
This chapter contains the following topics:
Introduction to the Data Dictionary
One of the most important parts of an Oracle database is its data dictionary , which is a read-only set of tables that provides information about the database. A data dictionary contains:
The definitions of all schema objects in the database (tables, views, indexes, clusters, synonyms, sequences, procedures, functions, packages, triggers, and so on)
How much space has been allocated for, and is currently used by, the schema objects
Default values for columns
Integrity constraint information
The names of Oracle users
Privileges and roles each user has been granted
Auditing information, such as who has accessed or updated various schema objects
Other general database information
The data dictionary is structured in tables and views, just like other database data. All the data dictionary tables and views for a given database are stored in that database's SYSTEM tablespace.
Not only is the data dictionary central to every Oracle database, it is an important tool for all users, from end users to application designers and database administrators. Use SQL statements to access the data dictionary. Because the data dictionary is read only, you can issue only queries ( SELECT statements) against it's tables and views.
"Bigfile Tablespaces" for more information about SYSTEM tablespaces
Structure of the Data Dictionary
The data dictionary consists of the following:
Base Tables
The underlying tables that store information about the associated database. Only Oracle should write to and read these tables. Users rarely access them directly because they are normalized, and most of the data is stored in a cryptic format.
User-Accessible Views
The views that summarize and display the information stored in the base tables of the data dictionary. These views decode the base table data into useful information, such as user or table names, using joins and WHERE clauses to simplify the information. Most users are given access to the views rather than the base tables.
Altering Users
Users can change their own passwords. However, to change any other option of a user security domain, you must have the ALTER USER system privilege. Security administrators are typically the only users that have this system privilege, as it allows a modification of any user security domain. This privilege includes the ability to set tablespace quotas for a user on any tablespace in the database, even if the user performing the modification does not have a quota for a specified tablespace.
You can alter user security settings with the ALTER USER statement. Changing user security settings affects the future user sessions, not current sessions.
The following statement alters the security settings for the user, avyrros :
The ALTER USER statement here changes the security settings for the user avyrros as follows:
Authentication is changed to use the operating system account of the user avyrros .
The default and temporary tablespaces are explicitly set for user avyrros .
avyrros is given a 100M quota for the data_ts tablespace.
The quota on the test_ts is revoked for the user avyrros .
avyrros is assigned the clerk profile.
Changing User Authentication Mechanism
Most non-DBA users can still change their own passwords with the ALTER USER statement, as follows:
No special privileges (other than those to connect to the database) are required for a user to change passwords. Users should be encouraged to change their passwords frequently.
Users must have the ALTER USER privilege to switch between methods of authentication. Usually, only an administrator has this privilege.
"User Authentication Methods" for information about authentication methods that are available for Oracle Database users
Changing User Default Roles
A default role is one that is automatically enabled for a user when the user creates a session. You can assign a user zero or more default roles.
SYS, Owner of the Data Dictionary
The Oracle user SYS owns all base tables and user-accessible views of the data dictionary. No Oracle user should ever alter ( UPDATE , DELETE , or INSERT ) any rows or schema objects contained in the SYS schema, because such activity can compromise data integrity. The security administrator must keep strict control of this central account.
Altering or manipulating the data in data dictionary tables can permanently and detrimentally affect the operation of a database.
DBA_TAB_COLUMNS
Предположим, вы нужно узнать среднюю длину каждой строки таблицы или значение по умолчанию каждого столбца (если таковое есть). Представление DBA_TAB_COLUMNS — отличный способ быстро получить всю детальную информацию о столбцах таблиц схемы, как показано в листинге ниже.
DBA_IND_COLUMNS
Представления DBA_IND_COLUMNS по структуре подобно представлению DBA_CONS_COLUMNS и содержит информацию обо всех проиндексированных столбцах каждой таблицы. Эта информация важна при настройке производительности, когда вы замечаете,что запрос использует индекс, но вы не знаете точно, на каких столбцах этот индекс определен. Запрос, приведенный в листинге ниже, показывает, что таблица имеет индексы, определенные на неверных столбцах.
Совет. Взглянув на столбец INDEX_NAME, можно легко идентифицировать составные ключи. Если одно и то же вхождение INDEX_NAME появляется больше одного раза, значит, это составной ключ; и столбцы, являющиеся его частью, показаны в столбце COLUMN_NAME. Например,INVENTORY_PK — первичный ключ таблицы INVENTORIES, определенный на двух столбцах:PRODUCT_ID и WAREHOUSE_ID. Порядок столбцов в определении составного ключа можно узнать с помощью столбца COLUMN_POSITION.
DBA_MVIEWS
Представление словаря DBA_MVIEWS сообщает все о материализованных представлениях в базе данных, в том числе информацию, включено ли для них средство переписывания запросов. В листинге ниже демонстрируется использования этого представления.
Dynamic Performance Tables
Throughout its operation, Oracle maintains a set of virtual tables that record current database activity. These tables are called dynamic performance tables.
Dynamic performance tables are not true tables, and they should not be accessed by most users. However, database administrators can query and create views on the tables and grant access to those views to other users. These views are sometimes called fixed views because they cannot be altered or removed by the database administrator.
SYS owns the dynamic performance tables; their names all begin with V_$ . Views are created on these tables, and then public synonyms are created for the views. The synonym names begin with V$ . For example, the V$DATAFILE view contains information about the database's datafiles, and the V$FIXED_TABLE view contains information about all of the dynamic performance tables and views in the database.
Oracle Database Reference for a complete list of the dynamic performance views' synonyms and their columns
DBA_TAB_PARTITIONS
Представление DBA_TAB_PARTITIONS подобно представлению DBA_TABLES, но содержит детальную информацию о разделах таблиц. Благодаря DBA_TAB_PARTITIONS, можно узнать имя раздела, его максимальные значения, информацию о хранении раздела,статистику по разделу, а также прочую информацию, которая доступна в представлении DBA_TABLES. В листинге ниже показан простой запрос, использующий представление DBA_TAB_PARTITIONS.
DBA_VIEWS
Как известно, представления — это результаты запросов к некоторым таблицам базы данных. Представление словаря данных DBA_VIEWS позволяет увидеть SQL-запросы, лежащие в основе представлений. В листинге ниже показано, как получить текст представления OS_CUSTOMERS, принадлежащего пользователю oe.
Совет. Чтобы обеспечить полное отображение текста при использовании представления DBA_VIEWS, установите большое значение переменной long (например, SET LONG 2000). В противном случае вы увидите лишь несколько первых строк определения представления.
DBA_EXTERNAL_TABLES
Представление DBA_EXTERNAL_TABLES показывает подробности о любой внешней таблице в базе данных, включая их тип доступа, параметры доступа и информацию о каталоге.
Dropping Users
When a user is dropped, the user and associated schema are removed from the data dictionary and all schema objects contained in the user schema, if any, are immediately dropped .
If a user schema and associated objects must remain but the user must be denied access to the database, then revoke the CREATE SESSION privilege from the user.
Do not attempt to drop the SYS or SYSTEM user. Doing so will corrupt your database.
A user that is currently connected to a database cannot be dropped. To drop a connected user, you must first terminate the user sessions using the SQL statement ALTER SYSTEM with the KILL SESSION clause.
You can drop a user from a database using the DROP USER statement. To drop a user and all the user schema objects (if any), you must have the DROP USER system privilege. Because the DROP USER system privilege is powerful, a security administrator is typically the only type of user that has this privilege.
If the user's schema contains any dependent schema objects, then use the CASCADE option to drop the user and all associated objects and foreign keys that depend on the tables of the user successfully. If you do not specify CASCADE and the user schema contains dependent objects, then an error message is returned and the user is not dropped. Before dropping a user whose schema contains objects, thoroughly investigate which objects the user's schema contains and the implications of dropping them. Pay attention to any unknown cascading effects. For example, if you intend to drop a user who owns a table, then check whether any views or procedures depend on that particular table.
The following statement drops the user, jones and all associated objects and foreign keys that depend on the tables owned by jones .
Oracle Database Administrator's Guide for more information about terminating sessions
INDEX_STATS
Представление INDEX_STATS полезно для того, чтобы узнать, насколько эффективно индекс использует свое пространство. Крупные индексы имеют тенденцию со временем становиться несбалансированными, если происходит много удалений данных таблицы (а, следовательно, и индекса). Ваша цель — не упускать из виду эти крупные индексы,чтобы сохранять их сбалансированными.
Обратите внимание, что представление INDEX_STATS наполняется, только когда таблица подвергается анализу с помощью команды ANALYZE, как показано ниже:
Запрос из листинга ниже, использующий представление INDEX_STATS, помогает определить необходимость в перестройке индекса. Чтобы определить, следует ли перестраивать индекс, в запросе необходимо сосредоточиться на перечисленных ниже столбцах представления INDEX_STATS.
In the context of this article, the schema owner represents the Oracle user that owns all your database objects, while application users are Oracle users that need access to those schema objects.
Allowing applications to make direct connections to the schema owner is a bad idea because it gives those applications far to many privileges, which can easily result in damage to your data and the objects themselves. Instead, it is better to define application users and grant those users the necessary privileges on the schema owners objects.
This article presents two methods for achieving this separation and highlights their pros and cons. For simplicities sake I've only defined two roles, but you can define as many roles as you wish, making the security as granular as you need for each type of application user.
DBA_INDEXES
Представление словаря DBA_INDEXES служит для того, чтобы узнать все необходимое об индексах в базе данных, включая имя индекса, его тип, таблицу и табличное пространство, к которому он относится. Определенные столбцы, наподобие BLEVEL (сообщает уровень B-дерева индекса) и DISTINCT_KEYS (количество разных значений ключа индекс), наполняются, только если собрана статистика по индексу с использованием пакета DBMS_STATS.
Viewing Information About Database Users and Profiles
The wide variety of options that are available for viewing such information are discussed in the following subsections:
DBA_TAB_MODIFICATIONS
Представление DBA_TAB_MODIFICATIONS показывает все изменения DML в таблице,произошедшие с момента последнего сбора статистики по этой таблице. Вот запрос к этому представлению:
База данных не обновляет представление DBA_TAB_MODIFICATIONS в реальном времени. Следовательно, вы можете и не увидеть изменений в различных таблицах, немедленно отраженных в этом представлении.
Database Object Metadata
The DBMS_METADATA package provides interfaces for extracting complete definitions of database objects. The definitions can be expressed either as XML or as SQL DDL. Two styles of interface are provided:
Существует несколько важных представлений словаря базы данных, которые можно использовать для нахождения детальной информации о любом из объектов базы данных, о которых говорилось в этой главе. Администраторы баз данных также интенсивно используют представления словаря данных, чтобы управлять различными объектами схемы. Здесь приводится краткий список важнейших представлений, часть из которых упоминалась выше. Полные данные о типах информации, которую можно получить от каждого из этих представлений, доступны по команде DESCRIBE (например, DESCRIBE DBA_CATALOG).
В этой статье блога будут описаны некоторые важные представления словаря данных, которые помогут управлять объектами, не хранящими данные (т.е. объектами, которые не относятся к таблицам и индексам). Ниже приведен список важнейших представлений словаря данных для просмотра объектов базы данных.
- DBA_SYNONYMS. Информация о синонимах базы данных.
- DBA_TRIGGERS. Информация о триггерах.
- DBA_SEQUENCES. Информация о созданных пользователем последовательностях.
- DBA_DB_LINKS. Информация о связях базы данных.
Как упоминалось ранее, представление DBA_OBJECTS предоставляет важную информацию обо всех перечисленных объектах, наряду с некоторыми другими типами объектов базы данных. Однако перечисленные представления содержат детальную информацию о каждом объекте, такую как исходный текст триггера, которую вы не получите из представления DBA_OBJECTS.
Управление такими объектами, как таблицы и представления, осуществляется ссылкой на представления словаря данных, наподобие DBA_TABLES и DBA_VIEWS. Существуют также отдельные представления для секционированных таблиц. Давайте рассмотрим ключевые представления словаря данных, относящиеся к таблицам и индексам.
CURRENT_SCHEMA Approach
This method uses the CURRENT_SCHEMA session attribute to automatically point application users to the correct schema.
First, we create the schema owner and an application user.
Notice that the application user can connect, but does not have any tablespace quotas or privileges to create objects.
Next, we create some roles to allow read-write and read-only access.
We want to give our application user read-write access to the schema objects, so we grant the relevant role.
We need to make sure the application user has its default schema pointing to the schema owner, so we create an AFTER LOGON trigger to do this for us.
Now we are ready to create an object in the schema owner.
Notice how the privileges are granted to the relevant roles. Without this, the objects would not be visible to the application user. We now have a functioning schema owner and application user.
This method is ideal where the application user is simply an alternative entry point to the main schema, requiring no objects of its own. It is clean and doesn't require management of thousands of synonyms. I don't find it very useful for developers who need to make copies or modify schema objects during development.
Creating Users
You create a database user with the CREATE USER statement. To create a user, you must have the CREATE USER system privilege. Because it is a powerful privilege, a DBA or security administrator is normally the only user who has the CREATE USER system privilege.
Example 11-1 creates a user and specifies the user password, default tablespace, temporary tablespace where temporary segments are created, tablespace quotas, and profile.
Example 11-1 Create a User and Grant the Create Session System Privilege
A newly created user cannot connect to the database until granted the CREATE SESSION system privilege.
As administrator, you should create your own roles and assign only those privileges that are needed. For example, many users formerly granted the CONNECT privilege did not need the additional privileges CONNECT used to provide. Instead, only CREATE SESSION was actually needed, and in fact that is the only privilege CONNECT presently retains.
Creating its own roles gives an organization detailed control of the privileges it assigns, and protects it in case Oracle changes the roles that it defines. For example, both CONNECT and RESOURCE roles will be deprecated in future Oracle versions.
This section refers to the preceding example as it discusses the following aspects of creating a user:
Granting System Privileges and Roles on page 25-11
Specifying a Name
Within each database, a user name must be unique with respect to other user names and roles. A user and role cannot have the same name. Furthermore, each user has an associated schema. Within a schema, each schema object must have a unique name.
Setting Up User Authentication
In Example 11-1, the new user is to be authenticated using the database. In this case, the connecting user must supply the correct password to the database to connect successfully.
Selecting and specifying the method of user authentication is discussed in "User Authentication Methods".
Assigning a Default Tablespace
Each user should have a default tablespace. When a user creates a schema object and specifies no tablespace to contain it, Oracle Database stores the object in the default user tablespace.
The default setting for the default tablespaces of all users is the SYSTEM tablespace. If a user does not create objects, and has no privileges to do so, then this default setting is fine. However, if a user is likely to create any type of object, then you should specifically assign the user a default tablespace. Using a tablespace other than SYSTEM reduces contention between data dictionary objects and user objects for the same data files. In general, it is not advisable for user data to be stored in the SYSTEM tablespace.
You can create a permanent default tablespace other than SYSTEM at the time of database creation, to be used as the database default for permanent objects. By separating the user data from the system data, you reduce the likelihood of problems with the SYSTEM tablespace, which can in some circumstances cause the entire database to become nonfunctional. This default permanent tablespace is not used by system users, that is, SYS , SYSTEM , and OUTLN , whose default permanent tablespace remains SYSTEM . A tablespace designated as the default permanent tablespace cannot be dropped. To accomplish this goal, another tablespace must first be designated as the default permanent tablespace. It is possible to ALTER the default permanent tablespace to another tablespace, affecting all users or objects created after the ALTER DDL commits.
You can also set a user default tablespace during user creation, and change it later with the ALTER USER statement. Changing the user default tablespace affects only objects created after the setting is changed.
When you specify the default tablespace for a user, also specify a quota on that tablespace.
In Example 11-1, the default tablespace for user jward is data_ts , and his quota on that tablespace is 500K .
Assigning Tablespace Quotas
You can assign each user a tablespace quota for any tablespace (except a temporary tablespace). Assigning a quota does the following things:
Users with privileges to create certain types of objects can create those objects in the specified tablespace.
Oracle Database limits the amount of space that can be allocated for storage of a user's objects within the specified tablespace to the amount of the quota.
By default, a user has no quota on any tablespace in the database. If the user has the privilege to create a schema object, then you must assign a quota to allow the user to create objects. Minimally, assign users a quota for the default tablespace, and additional quotas for other tablespaces in which they can create objects.
You can assign a user either individual quotas for a specific amount of disk space in each tablespace or an unlimited amount of disk space in all tablespaces. Specific quotas prevent a user's objects from consuming too much space in the database.
You can assign quotas to a user tablespace when you create the user, or add or change quotas later. If a new quota is less than the old one, then the following conditions hold true:
If a user has already exceeded a new tablespace quota, then the user's objects in the tablespace cannot be allocated more space until the combined space of these objects falls below the new quota.
If a user has not exceeded a new tablespace quota, or if the space used by the user's objects in the tablespace falls under a new tablespace quota, then the user's objects can be allocated space up to the new quota.
Revoking User Ability to Create Objects in a Tablespace
You can revoke the ability of a user to create objects in a tablespace by changing the current quota of the user to zero. After a quota of zero is assigned, the user's objects in the tablespace remain, but new objects cannot be created and existing objects cannot be allocated any new space.
UNLIMITED TABLESPACE System Privilege
To permit a user to use an unlimited amount of any tablespace in the database, grant the user the UNLIMITED TABLESPACE system privilege. This overrides all explicit tablespace quotas for the user. If you later revoke the privilege, then explicit quotas again take effect. You can grant this privilege only to users, not to roles.
Before granting the UNLIMITED TABLESPACE system privilege, you must consider the consequences of doing so.
You can grant a user unlimited access to all tablespaces of a database with one statement.
The privilege overrides all explicit tablespace quotas for the user.
You cannot selectively revoke tablespace access from a user with the UNLIMITED TABLESPACE privilege. You can grant selective or restricted access only after revoking the privilege.
Assigning a Temporary Tablespace
Each user also should be assigned a temporary tablespace . When a user executes a SQL statement that requires a temporary segment, Oracle stores the segment in the user's temporary tablespace. These temporary segments are created by the system when doing sorts or joins and are owned by SYS , which has resource privileges in all tablespaces.
In the previous CREATE USER statement, the temporary tablespace of jward is temp_ts , a tablespace created explicitly to contain only temporary segments. Such a tablespace is created using the CREATE TEMPORARY TABLESPACE statement.
If the temporary tablespace of a user is not explicitly set, then the user is assigned the default temporary tablespace that was specified at database creation, or by an ALTER DATABASE statement at a later time. If there is no default temporary tablespace explicitly assigned, then the default is the SYSTEM tablespace or another permanent default established by the system administrator. It is not advisable for user data to be stored in the SYSTEM tablespace. Also, assigning a tablespace to be used specifically as a temporary tablespace eliminates file contention among temporary segments and other types of segments.
If your SYSTEM tablespace is locally managed, then users must be assigned a specific default (locally managed) temporary tablespace. They may not be allowed to default to using the SYSTEM tablespace because temporary objects cannot be placed in permanent locally managed tablespaces.
You can set the temporary tablespace for a user at user creation, and change it later using the ALTER USER statement. Do not set a quota for temporary tablespaces. You can also establish tablespace groups instead of assigning individual temporary tablespaces.
Multiple Temporary Tablespaces: Using Tablespace Groups
Specifying a Profile
You also specify a profile when you create a user. A profile is a set of limits on database resources and password access to the database. If no profile is specified, then the user is assigned a default profile.
Setting Default Roles
You cannot set default roles for a user in the CREATE USER statement. When you first create a user, the default role setting for the user is ALL , which causes all roles subsequently granted to the user to be default roles. Use the ALTER USER statement to change the default roles for the user.
How the Data Dictionary Is Used
The data dictionary has three primary uses:
Oracle accesses the data dictionary to find information about users, schema objects, and storage structures.
Oracle modifies the data dictionary every time that a data definition language (DDL) statement is issued.
Any Oracle user can use the data dictionary as a read-only reference for information about the database.
Managing Oracle Users
Each Oracle database has a list of valid database users. To access a database, a user must run a database application and connect to the database instance using a valid user name defined in the database. This section explains how to manage users for a database, and contains the following topics:
Oracle Database SQL Reference for more information about SQL statements used for managing users
DBA_TABLES
Представление DBA_TABLES содержит информацию обо всех реляционных таблицах базы данных. Представление DBA_TABLES — основной справочник для нахождения информации о хранении, количестве строк в таблице, состоянии протоколирования, информации буферного пула и многих других деталях. Ниже приведен простой пример запроса представления DBA_TABLES:
На заметку! Представление DBA_ALL_TABLES содержит информацию обо всех объектных и реляционных таблицах в базе данных, в то время как представление DBA_TABLES ограничено только реляционными таблицами.
Представление DBA_TABLES служит для нахождения таких вещей, как включено ли сжатие и отслеживание зависимостей на уровне строки, и была ли таблица уничтожена и помещена в корзину (Recycle Bin).
DBA_OBJECTS
Представление DBA_OBJECTS содержит информацию обо всех объектах базы данных, включая таблицы, индексы, пакеты, процедуры, функции, измерения, материализованные представления, планы ресурсов, типы, последовательности, синонимы, триггеры, представления и разделы таблиц (оно же секционирование). Как несложно догадаться, это представления удобно, когда нужно знать общую информацию относительно любого объекта базы данных. В листинге ниже показан запрос, предназначенный для нахождения времени создания и времени последней модификации объекта (LAST_DDL_TIME). Этот тип запроса поможет идентифицировать время модификации определенного объекта, что часто используется в процессе аудита.
DBA_PART_TABLES
Представление DBA_PART_TABLES содержит информацию о типе схемы раздела и прочих параметрах хранения разделов и подразделов. Узнать тип каждого раздела каждой секционированной таблицы можно с помощью следующего запроса:
How to Use the Data Dictionary
The views of the data dictionary serve as a reference for all database users. Access the data dictionary views with SQL statements. Some views are accessible to all Oracle users, and others are intended for database administrators only.
The data dictionary is always available when the database is open. It resides in the SYSTEM tablespace, which is always online.
The data dictionary consists of sets of views. In many cases, a set consists of three views containing similar information and distinguished from each other by their prefixes:
Table 7-1 Data Dictionary View Prefixes
User's view (what is in the user's schema)
Expanded user's view (what the user can access)
Database administrator's view (what is in all users' schemas)
The set of columns is identical across views, with these exceptions:
Views with the prefix USER usually exclude the column OWNER . This column is implied in the USER views to be the user issuing the query.
Some DBA views have additional columns containing information useful to the administrator.
Oracle Database Reference for a complete list of data dictionary views and their columns
Views with the Prefix USER
The views most likely to be of interest to typical database users are those with the prefix USER . These views:
Refer to the user's own private environment in the database, including information about schema objects created by the user, grants made by the user, and so on
Display only rows pertinent to the user
Have columns identical to the other views, except that the column OWNER is implied
Return a subset of the information in the ALL views
Can have abbreviated PUBLIC synonyms for convenience
For example, the following query returns all the objects contained in your schema:
Views with the Prefix ALL
Views with the prefix ALL refer to the user's overall perspective of the database. These views return information about schema objects to which the user has access through public or explicit grants of privileges and roles, in addition to schema objects that the user owns. For example, the following query returns information about all the objects to which you have access:
Views with the Prefix DBA
Views with the prefix DBA show a global view of the entire database. Synonyms are not created for these views, because DBA views should be queried only by administrators. Therefore, to query the DBA views, administrators must prefix the view name with its owner, SYS , as in the following:
Oracle recommends that you implement data dictionary protection to prevent users having the ANY system privileges from using such privileges on the data dictionary. If you enable dictionary protection ( O7_DICTIONARY_ACCESSIBILITY is false ), then access to objects in the SYS schema (dictionary objects) is restricted to users with the SYS schema. These users are SYS and those who connect as SYSDBA .
Oracle Database Administrator's Guide for detailed information on system privileges restrictions
The DUAL Table
The table named DUAL is a small table in the data dictionary that Oracle and user-written programs can reference to guarantee a known result. This table has one column called DUMMY and one row containing the value X .
Oracle Database SQL Reference for more information about the DUAL table
Synonym Approach
This method relies on synonyms owned by the application user to point to the correct location of the schema objects.
First, we create the users in a similar way to the previous example.
Once again, the application user can connect, but does not have any tablespace quotas. The difference here is that the application user does have the privilege to create synonyms.
Next, we create some roles to allow read-write and read-only access and grant the read-write role to the application user.
Now we are ready to create an object in the schema owner in the same way we did in the previous example.
If we now connect to the application user we are not able to see the object without qualifying it with a schema name. We can either proceed in this fashion, or use a synonym to point to the correct object.
I find this method rather cumbersome due to the sheer number of synonyms required, especially when there are a large number of application users. Obviously, it is possible to use public synonyms, but this can be problematic when you have multiple application schemas on a single instance. I only use this method when I have developers who need to create their own schema objects for testing.
How Oracle Uses the Data Dictionary
Data in the base tables of the data dictionary is necessary for Oracle to function . Therefore, only Oracle should write or change data dictionary information. Oracle provides scripts to modify the data dictionary tables when a database is upgraded or downgraded.
No data in any data dictionary table should be altered or deleted by any user.
During database operation, Oracle reads the data dictionary to ascertain that schema objects exist and that users have proper access to them. Oracle also updates the data dictionary continuously to reflect changes in database structures, auditing, grants, and data.
For example, if user Kathy creates a table named parts , then new rows are added to the data dictionary that reflect the new table, columns, segment, extents, and the privileges that Kathy has on the table. This new information is then visible the next time the dictionary views are queried.
Public Synonyms for Data Dictionary Views
Oracle creates public synonyms for many data dictionary views so users can access them conveniently. The security administrator can also create additional public synonyms for schema objects that are used systemwide. Users should avoid naming their own schema objects with the same names as those used for public synonyms.
Cache the Data Dictionary for Fast Access
Much of the data dictionary information is kept in the SGA in the dictionary cache , because Oracle constantly accesses the data dictionary during database operation to validate user access and to verify the state of schema objects. All information is stored in memory using the least recently used (LRU) algorithm.
Parsing information is typically kept in the caches. The COMMENTS columns describing the tables and their columns are not cached unless they are accessed frequently.
Other Programs and the Data Dictionary
Other Oracle products can reference existing views and create additional data dictionary tables or views of their own. Application developers who write programs that refer to the data dictionary should refer to the public synonyms rather than the underlying tables: the synonyms are less likely to change between software releases.
Physical Organisation
In the following article I discuss my preferred physical organisation. The techniques described in this article can be used during its implementation.
Есть запрос к произвольной базе данных:
SELECT OWNER, TABLE_NAME, 'TABLE' AS TABLE_TYPE
FROM ALL_TABLES
WHERE OWNER = @owner
SELECT OWNER, VIEW_NAME AS TABLE_NAME, 'VIEW' AS TABLE_TYPE
FROM ALL_VIEWS
WHERE OWNER = @owner"
То есть достаются все таблицы и представления принадлежащие пользователю,
необходимо модифицировать запрос, чтобы избавиться от owner.
То есть предположим, что у нас пользователь имеет право читать данные, но
не является владельцем, надо получить таблицы которые он может читать.
Если просто убрать WHERE OWNER = @owner", то появится много всего лишнего —
различные системные таблицы ( те же all_tables и так далее). Так вот хотелось
бы от них избавиться.
Здравствуйте, Unholy, Вы писали:
U>не является владельцем, надо получить таблицы которые он может читать.
U>Если просто убрать WHERE OWNER = @owner", то появится много всего лишнего —
U>различные системные таблицы ( те же all_tables и так далее). Так вот хотелось
U>бы от них избавиться.
как раз all_tables показывает таблицы, находящиеся в области видимости пользователя
если не нужны системные — укажи where owner not in ('SYS', 'SYSTEM')
Здравствуйте, romashka, Вы писали:
R>как раз all_tables показывает таблицы, находящиеся в области видимости пользователя
R>если не нужны системные — укажи where owner not in ('SYS', 'SYSTEM')
Спасибо. Насколько я понимаю эти два пользователя всегда создаются вместе с базой данных и
их переименовать нельзя.
Но вроде как эти пользователи могут иметь пользовательские таблицы, это плохо но такое вроде бы не
запрещается?
Может есть таблица, которая содержит признаки системных таблиц.
Здравствуйте, Unholy, Вы писали:
Ты толком объясни какие таблицы хочешь получить.
Здравствуйте, Unholy, Вы писали:
U>Может есть таблица, которая содержит признаки системных таблиц.
тебе дело говорят.
select * from all_tables;
select * from user_tables;
посмотри на оба, и выбери, что тебе больше подходит.
ну и до кучи
select * from tab;
глянь.
Здравствуйте, wildwind, Вы писали:
W>Здравствуйте, Unholy, Вы писали:
W>Ты толком объясни какие таблицы хочешь получить.
Мне необходимы получить все таблицы, которые может читать подключенный пользователь(который в строке соединения), но при этом мне не
нужны системные таблицы типа all_tables.
Предположим, что мы выкинули все таблицы, которые принадлежат пользователям SYS и SYSTEM, но эти пользователи
также могут содержать пользовательские таблицы(оракл не запрещает это, хотя это не рекомендуется делать).
Здравствуйте, bastrakov, Вы писали:
B>тебе дело говорят.
B>select * from all_tables;
содержит все таблицы, которые доступны пользователю.
B>select * from user_tables;
содержит только те таблицы, которые принадлежат пользователю.
Мне нужно select * from all_tables минус все системные таблицы.
Может я чего-то жестко не понимаю?
Здравствуйте, Unholy, Вы писали:
U>Мне необходимы получить все таблицы, которые может читать подключенный пользователь(который в строке соединения),
Это ALL_TABLES, но не совсем. Если таблица содержится в ALL_TABLES, то пользователь имеет к ней какой-то доступ, но не обязательно select, может быть только insert или update.
U>но при этом мне не нужны системные таблицы типа all_tables.
Вот "системность" таблиц надо определить поточнее.
U>Предположим, что мы выкинули все таблицы, которые принадлежат пользователям SYS и SYSTEM, но эти пользователи
U>также могут содержать пользовательские таблицы(оракл не запрещает это, хотя это не рекомендуется делать).
Что есть "пользовательская" таблица в схеме SYS? Созданная не при установке, не при создании базы, не из стандартных скриптов? А патчи, а дроп и повторный прогон стандартных скриптов, а установка дополнительных продуктов? Это понятие весьма и весьма расплывчатое.
С другой стороны, таблицы и другие объекты в схемах XDB, CTXSYS, WMSYS, OUTLN и т.п. можно считать в некотором смысле "системными".
В общем, такая постановка задачи мне представляется некорректной и даже надуманной. Так что колись, зачем тебе это надо.
Здравствуйте, Unholy, Вы писали:
B>>тебе дело говорят.
.
B>>select * from all_tables;
дальше я писал: "посмотри на оба, и выбери".
ок. давай я дальше буду гадать для тебя. не забудь позолотить ручку, яхонтовый.
select * from all_tables t
where t.TABLESPACE_NAME not like 'SYS%'
правда мне кажеться, что лучше будет
select * from all_tables t
where t.TABLESPACE_NAME in (и здесь список tablespaces, которые хочешь)
U>Может я чего-то жестко не понимаю?
может. потому и обьяснить не можешь.
попробуй пересмотреть (переспросить?) постановку задачи.
Здравствуйте, wildwind, Вы писали:
W>В общем, такая постановка задачи мне представляется некорректной и даже надуманной. Так что колись, зачем тебе это надо.
Задача не надуманная — например в том же sql sevrver есть таблицы sysobjects где можно посмотреть является ли таблица системной или нет.
Необходимо получить все таблицы, к которым пользователь имеет доспут (при этом будем считать, что это как минимум select).
Для чего: необходимо чтобы пользователь мог строить запросы к базе данных(может быть любой) через интерфейс.
Понятно, что при этом показывать пользователю системные таблицы как-то неправильно, хотя на это можно и забить, но
это усложнит работу.
Причем пользователь может быть не только владельцем таблиц, но и может просто иметь право выбирать из них данные(поэтому all_tables).
Здравствуйте, Unholy, Вы писали:
U>Для чего: необходимо чтобы пользователь мог строить запросы к базе данных(может быть любой) через интерфейс.
Ага, ты пишешь универсальную SQL-тулзу. Так вот, в Oracle нет особого признака того, что таблица системная. И определить это в общем случае нельзя, примеры я привел выше. Если только держать в программе список таких "системных" (для Oracle) таблиц, и фильтровать по нему. Но это не лучшее решение. Поэтому обычно в таких программах группируют объекты по схемам, то есть по владельцам, а не вываливют все в один огромный список. А уж пользователь сам знает, что в схеме SYS, к примеру, ему делать нечего; выбирает схему USER и получает список таблиц, пренадлежащих USER, и т.д.
Many tasks, with many interwoven considerations, are involved in administering user privileges, roles, and profiles. These necessary operations and principles are discussed in the following sections:
Читайте также: