Bazy danych « Różności …

Różności …

24 lutego 2011

Oracle datastructures (K1)

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 10:51

Triggers

Although you can write triggers to perform the work of a constraint,
Oracle has optimized the operation of constraints, so it’s best to
always use a constraint instead of a trigger if possible.

There are three types of events that can cause a trigger to fire:

• A database UPDATE

• A database INSERT

• A database DELETE

There are three times when a trigger can fire:

• Before the execution of the triggering event

• After the execution of the triggering event

• Instead of the triggering event

Triggers are defined and stored separately from the tables that use them. Oracle8i and beyond also support Java as a procedural language, so you can create Java triggers with those versions. Youcan write a trigger directly in PL/SQL or Java, or a trigger can call an existing stored procedure written in either language.

Query Optimization

When a SQL query is submitted to an Oracle database, Oracle must decide how to access the data. The process of making this decision is called query optimization. This retrieval is known as the execution path.

For instance, even with a query that involves only a single table, Oracle can take either of these approaches:

Use an index to find the ROWIDs of the requested rows and then retrieve those rows from the table.
• Scan the table to find and retrieve the rows; this is referred to as a full table scan.

Although it’s usually much faster to retrieve data using an index, the process of getting the values from the index involves an additional I/O step in processing the query. Using the index values to select the desired rows involves less I/O and is therefore more efficient than retrieving all the data from the table and then imposing the selection conditions. Another factor in determining the optimal query execution plan is whether there is an ORDER BY condition in the query that can be automatically implemented by the presorted index. Alternatively, if the table is small enough, the optimizer may decide to simply read all the blocks of the table and bypass the index since it estimates the cost of the index I/O plus the table I/O to be higher than just the table I/O.

Prior to Oracle Database 10g, you could choose between two different Oracle query optimizers, a rule-based optimizer and a cost-based optimizer. With Oracle Database 10g, the rule-based optimizer is desupported. As the name implies, the cost-based optimizer does more than simply look at a set of optimization rules; instead, it selects the execution path that requires the least number of logical I/O operations. To properly evaluate the cost of any particular execution plan, the cost-based optimizer uses statistics about the composition of the relevant data structures. These statistics are automatically gathered by default since the Oracle Database 10g release into the Automatic Workload Repository (AWR).

The accuracy of the cost-based optimizer depends on the accuracy of the statistics it uses, so updating statistics has always been a must. Formerly, you would have used the SQL statement ANALYZE to compute or estimate these statistics. When managing an older release, many database administrators also used a built-in PL/SQL package, DBMS_STATS, that contains a number of procedures that helped automate the process of collecting statistics.

Oracle gives youa way to influence the decisions of the optimizer with a technique called hints. A hint is nothing more than a comment with a specific format inside a SQL statement.
Here, the hint forces the optimizer to use the EMP_IDX index for the EMP table:
SELECT /*+ INDEX(EMP_IDX) */ LASTNAME, FIRSTNAME, PHONE FROM EMP

Starting with Oracle8i, youcou ld create a stored outline that stored the attributes used by the optimizer to create an execution plan.

With the release of Oracle Database 11g, Oracle suggests that you move your stored outlines to SQL plan baselines.

The SQL*Analyzer tool is designed to give youthe ability to recognize potential problems caused by optimizer upgrades.

Oracle Database 11g also includes a feature called Database Replay. This feature captures workloads from production systems and allows them to be run on test systems. With this capability, you can test actual production scenarios against new configurations or versions of the database, and Database Replay will spot areas of potential performance problems on the changed platform.

The  SQL EXPLAIN PLAN statement. When you use EXPLAIN PLAN, followed by the keyword FOR and the SQL statement whose execution plan you want to view, the Oracle cost-based optimizer returns a description of the execution plan it will use for the SQL statement and inserts this description into a database table.

The optimizer writes all of this information to a table in the database. By default, the optimizer uses a table called PLAN_TABLE; make sure the table exists before you use EXPLAIN PLAN. (The utlxplan.sql script included with your Oracle database creates the default PLAN_TABLE table.)

There are other times when youwant to look at the plans for a group of SQL statements. For these situations, you can set up a trace for the statements you want to examine and then use the second utility, TKPROF, to give you the results of the trace in a more readable format in a separate file. At other times, youmight also use Oracle’s SQL Trace facility to generate a file containing the SQL generated when using TKPROF in tuning applications.

You must use the EXPLAIN keyword when you start TKPROF, as this will instruct the utility to execute an EXPLAIN PLAN statement for each SQL statement in the trace file. Youcan also specify how the results delivered by TKPROF are sorted. For instance, youcan have the SQL statements sorted on the basis of the physical I/Os they used; the elapsed time spent on parsing, executing, or fetching the rows; or the total number of rows affected. The TKPROF utility uses a trace file as its raw material. The trace process can significantly affect the performance of an application, so you should turn it on only when you have some specific diagnostic work to do.

You can also view the execution plan through Enterprise Manager for the SQL statements that use the most resources. Tuning your SQL statements isn’t a trivial task, but with the EXPLAIN PLAN and TKPROF utilities you can get to the bottom of the decisions made by the cost-based optimizer.

SQL ADVISORS

Oracle Database 10g added a tool called the SQL Tuning Advisor. This tool performs advanced optimization analysis on selected SQL statements, using workloads that have been automatically collected into the Automatic Workload Repository or that you have specified yourself. Once the optimization is done, the SQL Tuning Advisor makes recommendations, which could include updating statistics, adding indexes, or creating a SQL profile. This profile is stored in the database and is used as the optimization plan for future executions of the statement, which allows you to “fix” errant SQL plans without having to touch the underlying SQL.

The tool is often used along with the SQL Access Advisor since that tool provides advice on materialized views and indexes. Oracle Database 11g introduces a SQL Advisor tool that combines functions of the SQL Tuning Advisor and the SQL Access Advisor (and now includes a new Partition Advisor). The Partition Advisor component advises on how to partition tables, materialized views, and indexes in order to improve SQL performance.

Data Dictionary Tables

DBA_
Includes all the objects in the database. A user must have DBA privileges to use this view.
USER_
Includes only the objects in the user’s own database schema.
ALL_
Includes all the objects in the database to which a particular user has access. If a user has been granted rights to objects in another user’s schema, these objects will appear in this view.

23 lutego 2011

ORA-02266 ORA-02297 ORA-02429 ORA-29857

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 11:49

ORA-02266:

unique/primary keys in table referenced by enabled foreign keys
Cause: An attempt was made to truncate a table with unique or primary keys referenced by foreign keys enabled in another table. Other operations not allowed are dropping/truncating a partition of a partitioned table or an ALTER TABLE EXCHANGE PARTITION.
Action: Before performing the above operations the table, disable the foreign key constraints in other tables. You can see what constraints are referencing a table by issuing the following command: SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME = “tabnam”;

alter table
table_name
DISABLE constraint
constraint_name;

lub

begin
for i in (select constraint_name, table_name from user_constraints) LOOP
execute immediate ‘alter table ‘||i.table_name||’ disable constraint ‘||i.constraint_name||”;
end loop;
end;
/

ORA-02297:

cannot disable constraint (string.string) – dependencies exist
Cause: an alter table disable constraint failed becuase the table has foriegn keys that are dpendent on this constraint.
Action: Either disable the foreign key constraints or use disable cascade

SQL> alter table transaction disable constraint TRANSACTION_PK;
alter table transaction disable constraint TRANSACTION_PK
*
ERROR at line 1:
ORA-02297: cannot disable constraint (OMS.TRANSACTION_PK) – dependencies exist

Cause of the Problem
Disable constraint command fails as the table is parent table and it has foreign key that are dependent on this constraint.

Solution of the Problem
Two solutions exist for this problem.
1)Find foreign key constraints on the table and disable those foreign key constraints and then disable this table constraint.

Following query will check dependent table and the dependent constraint name. After that disable child first and then parent constraint.

SQL> SELECT p.table_name "Parent Table", c.table_name "Child Table",
       p.constraint_name "Parent Constraint", c.constraint_name "Child Constraint"
       FROM dba_constraints p
       JOIN dba_constraints c ON(p.constraint_name=c.r_constraint_name)
       WHERE (p.constraint_type = 'P' OR p.constraint_type = 'U')
       AND c.constraint_type = 'R'
       AND p.table_name = UPPER('&table_name');
Enter value for table_name: transaction
old   7:      AND p.table_name = UPPER('&table_name')
new   7:      AND p.table_name = UPPER('transaction')
Parent Table                   Child Table                    Parent Constraint              Child Constraint
------------------------------ ------------------------------ ------------------------------ ------------------------------
TRANSACTION                    USER_SALARY_RECORD             TRANSACTION_PK                 SYS_C005564
TRANSACTION                    TRANSACTION_DETAIL             TRANSACTION_PK                 TRNSCTN_DTL_TRNSCTN_FK

SQL> alter table USER_SALARY_RECORD disable constraint SYS_C005564;
Table altered.

SQL> alter table TRANSACTION_DETAIL  disable constraint TRNSCTN_DTL_TRNSCTN_FK;
Table altered.

SQL> alter table transaction disable constraint TRANSACTION_PK;
Table altered.

2)Disable the constraint with cascade option.
SQL> alter table transaction disable constraint TRANSACTION_PK cascade;
Table altered.

The six types of integrity constraint are described briefly here and more fully in “Semantics”:

  • NOT NULL constraint prohibits a database value from being null.
  • unique constraint prohibits multiple rows from having the same value in the same column or combination of columns but allows some values to be null.
  • primary key constraint combines a NOT NULL constraint and a unique constraint in a single declaration. That is, it prohibits multiple rows from having the same value in the same column or combination of columns and prohibits values from being null.
  • foreign key constraint requires values in one table to match values in another table.
  • check constraint requires a value in the database to comply with a specified condition.
  • REF column by definition references an object in another object type or in a relational table. A REF constraint lets you further describe the relationship between the REF column and the object it references.

ORA-02429:

cannot drop index used for enforcement of unique/primary key
Cause: user attempted to drop an index that is being used as the enforcement mechanism for unique or primary key.
Action: drop the constraint instead of the index.

Trzeba znaleźć w PKs dany constraint i sprawdzić do jakiej tabeli się odwołuje. (ewentualnie usunąć)

ORA-02273:

this unique/primary key is referenced by some foreign keys
Cause: Self-evident.
Action: Remove all references to the key before the key is to be dropped.

It’s very easy to reproduce this situation:create table test1(test1_parent_id number,col1 varchar2 (30),constraint test1_pk primary key (test1_parent_id))/create table test2(test2_id number,test1_child_id number,col2 varchar2(30),constraint test2_fk foreign key (test1_child_id) references test1(test1_parent_id))/alter table test1 drop constraint test1_pk/ORA-02273: this unique/

select *
from dba_constraints
where r_constraint_name in ( select constraint_name
from   dba_constraints
where  table_name = ‘<your table>’
);

select * from all_constraints
where constraint_type='R' and r_constraint_name='YOUR_CONSTRAINT';

(wykasować child constraints)

ORA-29857:

domain indexes and/or secondary objects exist in the tablespace
Cause: An attempt was made to drop a tablespace which contains secondary objects and/or domain indexes.
Action: Drop the domain indexes in his tablespace. Also, find the domain indexes which created secondary objects in this tablespace and drop them. Then try dropping the tablespace.

Przy kasowaniu przestrzeni tablic EXAMPLE (10g)

wcześniej należy:

DROP USER BI CASCADE;

DROP USER HR CASCADE;

DROP USER IX CASCADE;

DROP USER OE CASCADE;

DROP USER PM CASCADE;

DROP USER SH CASCADE;

ALTER TABLESPACE EXAMPLE OFFLINE;
DROP TABLESPACE EXAMPLE INCLUDING CONTENTS AND datafiles;

Źródła:

http://www.dba-oracle.com/t_oracle_disable_constraints.htm

http://arjudba.blogspot.com/2008/12/ora-02297-cannot-disable-constraint.html

http://www.dba-oracle.com/t_constraints.htm

http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/clauses002.htm

http://www.dba-oracle.com/t_alter_table_add_constraint_syntax_example.htm

http://oraclequirks.blogspot.com/2007/09/ora-02273-this-uniqueprimary-key-is.html

role w oracle:
http://www.idevelopment.info/data/Oracle/DBA_tips/Database_Administration/DBA_26.shtml

21 lutego 2011

ORA-02292 Constraint violation – child records found

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 10:28

ORA-02292 – przy kasowaniu rekordu z tabeli master
Błąd wskazuje właściciela i constraint name

Np: tworzenie constraint:

SQL> alter table emp
2 add (constraint job_fk foreign key (job_key)
3 references job (job_key)
4 on delete cascade);

Now, when INSERT or UPDATE the job key column in the EMP table, the foreign key constraint will check to insure that the job already exists in the JOB table (or at least the job key exist in the JOB table).

Foreign key constraints can also be disabled, enabled and dropped.
alter table emp disable constraint job_fk;
alter table emp enable constraint job_fk;
alter table emp drop constraint job_fk;

Now, let’s talk about the ON DELETE part of the constraint. When we created the foreign key constraint . we included ON DELETE SET NULL or ON DELETE CASCADE. This clause tells the database what to do with the child records when the parent record is deleted. In the example above, we created the job_fk constraint with ON DELETE CASCADE.

This will cause the database to cascade the deletes. If I go to the JOB table and DELETE a job, all the employees that have that job will also be deleted as the DELETE will cascade to the child rows.

If we use the ON DELETE SET NULL, then when we delete the parent record, the child records with that value will be set to NULL.

ORA-O6413
Ten błąd pojawił się po instalce Forms and Reports 9i na Win7 (64 bit) przy próbach połączenia z SQL Tools do dowolnej bazy danych.
Zmieniłem PATH i wpis “c:\orawin\bin” (od forms and reports) przeniosłem z pierwszej na ostatnią pozycję – to rozwiązało problem.

SGA_TARGET

ALTER SYSTEM SET SGA_TARGET=2048M scope=both;

ORA-02097: parametr nie może być zmodyfikowany ponieważ podana wartość jest niepoprawna
ORA-00823: Podana wartość sga_target jest większa niż sga_max_size

alter SYSTEM SET SGA_MAX_SIZE=2560M scope=both;
ORA-02095: Podany parametr inicjalizacyjny nie może być modyfikowany

ALTER SYSTEM SET SGA_MAX_SIZE=2560M scope=spfile;
restart bazy

(w systemie jest 4GB RAM)

(w 32 bitowych obsługiwane 1,8 GB – jako SGA)

ORA-27100 shared memory realm already exist
sql> create pfile from spfile
C:\oracle\product\10.2.0\db_1\database\INITorcl.ora
zmienić wartość sga_max_size na mniejszą
sql>create spfile from pfile
zrestartować serwis i jest OK

sql> show parameter sga

Źródła:
http://www.dba-oracle.com/t_ora_02292_constraint_violation_child_record_found.htm

http://blog.flimatech.com/tag/ora-02292/

http://www.dbasupport.com/oracle/ora10g/sizingSGA02.shtml

Oracle Memory Configuration for Windows

18 lutego 2011

Oracle datastructures (K1)

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 12:57

The Expression Filter
The Expression Filter uses the Rules Manager to work with expressions.

Once you’ve completed an optimal logical database
design, youmu st go back and consider what indexes youshou ld add to improve the
anticipated performance of the database and whether youshou ld designate any
tables as part of a cluster or hash cluster.

Constraints
A constraint enforces certain aspects of data integrity within a database. When youadd a constraint to a particular column, Oracle automatically ensures that data violatingthat constraint is never accepted. (unique, not null)

Each table can have, at most, a single primary key constraint. The primary keymay consist of more than one column in a table. The primary key constraint forces each primary key to have a unique value. Itenforces both the unique constraint and the NOT NULL constraint. A primarykey constraint will create a unique index, if one doesn’t already exist for thespecified column(s).

The foreign key constraint is defined for a table (known as the child) that has arelationship with another table in the database (known as the parent). The value entered in a foreign key must be present in a unique or primary key of another specific table. For example, the column for a department ID in an employee table might be a foreign key for the department ID primary key in the department table. Normally, you cannot delete a row in a parent table if it causes a row in the childtable to violate a foreign key constraint. However, you can specify that a foreignkey constraint causes a cascade delete, which means that deleting a referenced row in the parent table automatically deletes all rows in the child table that reference the primary key value in the deleted row in the parent table.

All constraints can be either immediate or deferred. An immediate constraint is enforced as soon as a write operation affects a constrained column in the table. A deferred constraint is enforced when the SQL statement that caused the change in the constrained column completes.
You can temporarily suspend the enforcement of constraints for a particular table. When youenable the operation of the constraint, you can instruct Oracle tovalidate all the data for the constraint or simply start applying the constraint to thenew data. When you add a constraint to an existing table, youcan also specifywhether you want to check all the existing rows in the table. (126)

15 lutego 2011

JAVA w Oracle i kasowanie dużej ilości wierszy z tabeli, triggers.

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 14:22

ALTER JAVA CLASS ODM.”/10b943ec_CompoundPredicate” resolve;

Kasowanie dużej ilości wierszy z tabeli:

– Create a test table
CREATE TABLE test_tbl
(test_col INTEGER)
/
– Populate it with 100,000 rows
BEGIN
FOR i in 1..100000 LOOP
INSERT INTO test_tbl
VALUES (i – TRUNC(i, -1));
END LOOP;
END;
/
COMMIT
/
– Delete 60% of the rows. This is the actual delete. You would just replace the
– where clause with yours.
DECLARE
TYPE tt_delete IS TABLE OF ROWID;
t_delete tt_delete;
CURSOR c_delete IS
SELECT ROWID
FROM test_tbl
WHERE test_col < 6;
l_delete_buffer PLS_INTEGER := 5000;
BEGIN
OPEN c_delete;
LOOP
FETCH c_delete BULK COLLECT
INTO t_delete LIMIT l_delete_buffer;
FORALL i IN 1..t_delete.COUNT
DELETE test_tbl
WHERE ROWID = t_delete (i);
EXIT WHEN c_delete%NOTFOUND;
COMMIT;
END LOOP;
CLOSE c_delete;
END;
/

(źródło: http://forums.oracle.com/forums/thread.jspa?threadID=345861)

i trochę inne podejście:

CREATE TABLE test_tbl_temp AS
SELECT *
  FROM TEST_TBL
 WHERE
MONTHS_BETWEEN(SYSDATE, TO_DATE(YRMO_NBR||'01','YYYYMMDD')) <= 38;

TRUNCATE TABLE test_tbl;
lub drop test_tbl; 

INSERT /*+ APPEND +/ INTO test_tbl
SELECT *
  FROM test_tbl_temp;
lub
RENAME TABLE test_tbl_temp to test_tbl;

ale tutaj trzeba uważać na ORA=02449 (unique/primary keys in table referenced by foreign keys)
aby sprawdzić jakie constraints odwołują się do tabeli można:
SELECT * FROM DBA_CONSTRAINTS WHERE TABLE_NAME = “test_tabl”;

lub

DELETE FROM myfata$ WHERE rownum < 100000; –Start with a small number and gradually increase to see how many rows you can delete in one shot without hitting the UNDO problem.

lub

CREATE OR REPLACE PROCEDURE delete_tab (tablename IN VARCHAR2,
                                            empno IN NUMBER  ,
                                            nrows IN NUMBER    ) IS

 sSQL1    VARCHAR2(2000);
 sSQL2    VARCHAR2(2000);
 nCount    NUMBER; 

BEGIN

  nCount := 0;
  sSQL1:='delete from '|| tablename ||
         ' where ROWNUM < ' || nrows || ' and empno=' || empno;
  sSQL2:='select count(ROWID) from ' || tablename ||
         ' where empno= ' || empno;

  LOOP

    EXECUTE IMMEDIATE sSQL1;

    EXECUTE IMMEDIATE sSQL2 INTO nCount;

    DBMS_OUTPUT.PUT_LINE('Existing records: ' || to_char(ncount) );

    commit;    

    EXIT WHEN nCount = 0;

  END LOOP;

END delete_tab;
/

Wyłączenie wyzwalacza:
ALTER TRIGGER trigger_name DISABLE;

ALTER TABLE inventory
    ENABLE ALL TRIGGERS;

3 lutego 2011

Instalacja Oracle 11G R2 na Solaris 10

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 15:33

Najpierw ustawimy sobie polską klawiaturę.
Zainstaluj z poziomu systemu polską klawiaturę (quertz)

Zainstaluj patch:

/usr/sfw/bin/wget http://www.jaceksen.pl/pliki/pl-keyboard-5.10.patch
patch -i pl-keyboard-5.10.patch -p1 /usr/X11/lib/X11/xkb/symbols/pl

/usr/sfw/bin/wget http://www.jaceksen.pl/pliki/setxkbmap
chmod 755 setxkbmap
./setxkbmap pl

groupadd oinstall
groupadd dba
groupadd oper
useradd -g oinstall -G dba -d /export/home/oracle oracle
mkdir /export/home/oracle
chown -R oracle:oinstall /export/home/oracle
passwd -r files oracle (-r okresla repozytorium do ktorego sie odnosi)

unzip solaris.x64_11gR2_database_1of2.zip
unzip solaris.x64_11gR2_database_2of2.zip

projadd oracle

do pliku /etc/user_attr dopisujemy
oracle::::project=oracle

Loguję się na użytkownika Oracle i sprawdzam aktualne parametry:

prctl -n project.max-shm-memory -i project oracle

u mnie:

ustawiam nowe wartości:
# prctl -n project.max-shm-memory -v 4gb -r -i project oracle
zapisuję je na stałe do pliku /etc/project:
# projmod -s -K “project.max-shm-memory=(priv,4gb,deny)” oracle

sprawdzam /etc/project

Ku przestrodze:
The Oracle installer seems incapable of recognising kernel parameter set using resource control projects, but if you ignore the warnings the installation completes successfully.

Instaluję “SUNWi1cs” i “SUNWi15cs”:
# pkgadd -d /cdrom/sol_10_910_x86/Solaris_10/Product SUNWi1cs SUNWi15cs

mkdir -p /u01/app/oracle/product/11gR2/db_1
chown -R oracle:oinstall /u01

tworze plik .profile:

# Oracle Settings
TMP=/tmp; export TMP
TMPDIR=$TMP; export TMPDIR
# Select the appropriate ORACLE_BASE
#ORACLE_BASE=/export/home/oracle; export ORACLE_BASE
ORACLE_BASE=/u01/app/oracle; export ORACLE_BASE
ORACLE_HOME=$ORACLE_BASE/product/11gR2/db_1; export ORACLE_HOME
ORACLE_SID=db1sol; export ORACLE_SID
PATH=$ORACLE_HOME/bin:$PATH; export PATH
/usr/bin/setxkbmap pl

Źródła:
http://blogs.sun.com/roller/resources/timf/setxkbmap

http://www.oracle-base.com/articles/10g/OracleDB10gR2InstallationOnSolaris10.php

http://automaciej.jogger.pl/2009/02/23/solaris-10-i-polska-klawiatura-programisty

20 stycznia 2011

Oracle Temporary tablespaces.

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 09:00

Temporary tablespaces are used to manage space for database sort operations and for storing global temporary tables. For example, if you join two large tables, and Oracle cannot do the sort in memory (see SORT_AREA_SIZE initialisation parameter), space will be allocated in a temporary tablespace for doing the sort operation. Other SQL operations that might require disk sorting are: CREATE INDEX, ANALYZE, Select DISTINCT, ORDER BY, GROUP BY, UNION, INTERSECT, MINUS, Sort-Merge joins, etc.

The DBA should assign a temporary tablespace to each user in the database to prevent them from allocating sort space in the SYSTEM tablespace.

Note that a temporary tablespace cannot contain permanent objects and therefore doesn’t need to be backed up.

Unlike normal data files, TEMPFILEs are not fully initialised (sparse). When you create a TEMPFILE, Oracle only writes to the header and last block of the file. This is why it is much quicker to create a TEMPFILE than to create a normal database file.

TEMPFILEs are not recorded in the database’s control file. This implies that one can just recreate them whenever you restore the database, or after deleting them by accident. This opens interesting possibilities like having different TEMPFILE configurations between permanent and standby databases, or configure TEMPFILEs to be local instead of shared in a RAC environment.

One cannot remove datafiles from a tablespace until you drop the entire tablespace. However, one can remove a TEMPFILE from a database. Look at his example:

SQL> ALTER DATABASE TEMPFILE '/oradata/temp02.dbf' DROP INCLUDING DATAFILES;

If you remove all tempfiles from a temporary tablespace, you may encounter error: ORA-25153: Temporary Tablespace is Empty. Use the following statement to add a TEMPFILE to a temporary tablespace:

SQL> ALTER TABLESPACE temp ADD TEMPFILE '/oradata/temp03.dbf' SIZE 100M;

Except for adding a tempfile, as illustrated in the above example, you cannot use the ALTER TABLESPACE statement for a locally managed temporary tablespace (operations like rename, set to read only, recover, etc. will fail).

SQL> CREATE TEMPORARY TABLESPACE temp
      TEMPFILE '/oradata/mytemp_01.tmp' SIZE 20M
      EXTENT MANAGEMENT LOCAL UNIFORM SIZE 16M;
For best performance, the UNIFORM SIZE must be a multiple of the SORT_AREA_SIZE parameter.

To see the default temporary tablespace for a database, execute the following query: SQL> SELECT * FROM DATABASE_PROPERTIES where PROPERTY_NAME='DEFAULT_TEMP_TABLESPACE'; Unlike datafiles, tempfiles are not listed in V$DATAFILE and DBA_DATA_FILES. Use V$TEMPFILE and DBA_TEMP_FILES instead. One can monitor temporary segments from V$SORT_SEGMENT and V$SORT_USAGE DBA_FREE_SPACE does not record free space for temporary tablespaces. Use V$TEMP_SPACE_HEADER instead:

SQL> select TABLESPACE_NAME, BYTES_USED, BYTES_FREE from V$TEMP_SPACE_HEADER;

TABLESPACE_NAME                BYTES_USED BYTES_FREE
------------------------------ ---------- ----------
TEMP                             52428800   52428800

Oracle 9i does not release allocated TEMP segments until you shutdown the database. While the TEMP segment is allocated, it does not mean that it is unavailable for use. When a user requests a disk sort, Oracle will allocate a TEMP segment. Once that sort is done, Oracle releases this TEMP segment for future use, but does not deallocate it. When the next user requests a disk sort, Oracle does not have to allocate a new TEMP segment. It uses the same one that no user is currently using. Oracle manages this for you in 9i. And there is really only one TEMP segment in the TEMP tablespace. Multiple users can utilitize this one segment.
There have been problems in 9i where users running a TEMPORARY TEMP tablespace with TEMPFILES that is Locally Managed where Oracle does not release the sort space once it is no longer being used. This is a known bug. The workaround has been to revert back to Dictionary Managed tablespace for TEMP.

Tekst pochodzi ze strony: http://www.orafaq.com/node/2

14 stycznia 2011

Instalacja Oracle11g na Fedora 14 (64 Bit)

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 09:18

Tu można znaleźć wszystko czego dusza zapragnie:
http://www.oracle-base.com/articles/11g/OracleDB11gR2InstallationOnFedora14.php

Fajna strona o parametrach SHMALL, SHMMAX ..
http://www.idevelopment.info/data/Oracle/DBA_tips/Linux/LINUX_8.shtml

Fajna strona o ustawianiu parametrów TCP w Linuksie:
http://www.speedguide.net/articles/linux-tweaking-121

Strona o instalacji OHS:
http://apex-at-work.blogspot.com/2010/11/oracle-http-server-ohs-part-of-oracle.html

aio-nr & aio-max-nr:
	aio-nr is the running total of the number of events specified on the
	io_setup system call for all currently active aio contexts.  If aio-nr
	reaches aio-max-nr then io_setup will fail with EAGAIN.  Note that
	raising aio-max-nr does not result in the pre-allocation or re-sizing
	of any kernel data structures.
you can increase the maximum number of open files by setting a new value
in kernel variable /proc/sys/fs/file-max
Setting SHMALL Parameter
This parameter sets the total amount of shared memory pages that can
be used system wide. Hence, SHMALL should always be at least
ceil(shmmax/PAGE_SIZE).
The default size for SHMALL in RHEL 3/4 and 2.1 is 2097152 which is also
Oracle's recommended minimum setting for 9i and 10g on x86 and x86-64
platforms. In most cases this setting should be sufficient since it means
that the total amount of shared memory available on the system is
2097152*4096 bytes (shmall*PAGE_SIZE) which is 8 GB. PAGE_SIZE is usually
4096 bytes unless you use Big Pages or Huge Pages which supports the
configuration of larger memory pages.
First off, editing sysctl.conf doesn't change the value until you either reboot, or execute:
sysctl -p
To have it reload the values.
You mention this is a 32-bit Linux. That puts constraints on how large you can set SHMMAX
 to and how big the Oracle SGA can be. See Installing Oracle9i on FC2 for more information
 about the limits you'll run into here. The largest generally useful setting is this:
kernel.shmmax=2147483648
And since the one you tried is >4GB that's why it failed altogether.
Many people seem to use some guide or Oracle's suggestions for a setting here as a magic
number without actually considering whether the shared memory values really make sense
for their system or not. I wrote the following little script to generate the settings
for me on Linux. As written, it limits the shared memory block to 50% of total RAM, which
might be light for your Oracle use; easy to adjust it to a higher percentage.
I hate seeing people set this value to higher than the amount of RAM in their server.
#!/bin/bash
mem_bytes=`awk '/MemTotal:/ { printf "%0.f",$2 * 1024}' /proc/meminfo`
mem_max=`expr $mem_bytes / 2`
page_size=`getconf PAGE_SIZE`
shmall=`expr $mem_bytes / $page_size`
echo \# Maximum shared segment size in bytes
echo kernel.shmmax = $mem_max
echo \# Maximum number of shared memory segments in pages
echo kernel.shmall = $shmall
The output from this can get written right to the end of the sysctl.conf, run "sysctl -p",
and you're off with a reasonable yet safe setting.
shmmni specifies the maximum number of shared memory segments allowed to exist simultaneously,
system-wide.
Setting shmmni to an arbitrarily large number wastes memory and can degrade system performance.
 Setting the value too high on systems with small memory configuration may consume enough memory
space that the system cannot boot. Select a value that is as close to actual system requirements
as possible for optimum memory usage. A value not exceeding 1024 is recommended unless system
requirements dictate otherwise.

Semaphores can best be described as counters which are used to provide synchronization between
processes or between threads within a process for shared resources like shared memories.
System V semaphores support semaphore sets where each one is a counting semaphore. So when an
application requests semaphores, the kernel releases them in “sets”. The number of semaphores
per set can be defined through the kernel parameter SEMMSL
/proc/sys/net/core/rmem_max - Maximum TCP Receive Window
/proc/sys/net/core/wmem_max - Maximum TCP Send Window
/proc/sys/net/ipv4/tcp_rmem - memory reserved for TCP rcv buffers (reserved memory per connection default)
/proc/sys/net/ipv4/tcp_wmem  - memory reserved for TCP snd buffers (reserved memory per connection default)

/etc/selinux/config
ustawić selinux=disabled
The xhost program is used to add and delete host names or user names to the list allowed to make connections
to the X server.
Po wykonaniu instalki wg. instrukcji instalator dalej marudzi:


Gdy się da ignoruj, to wywala się na linkowaniu binariów:
aby pozbyć się błędu ins_emagent.mk należy:
This error is due to a change in the GCC linker in Fedora 13. The announcement is here. The fix is to
edit $ORACLE_HOME/sysman/lib/ins_emagent.mk, search for the line $(MK_EMAGENT_NMECTL) and replace the
line with $(MK_EMAGENT_NMECTL) -lnnz11 as shown above.
Informacja pochodzi ze strony:
http://blog.fpmurphy.com/2010/08/installing-oracle-11g-release-2-on-fedora-13.html#ixzz1BIWbQ3ps

Logowanie do EM: OK
emctl stop dbconsole
emctl start dbconsole

13 stycznia 2011

Instalacja APEX 4.0.2

Zaszufladkowany do: ApEx,Oracle — Tagi: , — Jacek @ 13:11

Pobieram najnowszego APEXa z: http://www.oracle.com/technetwork/developer-tools/apex/downloads/index.html

Kopiuję rozpakowany katalog do: /home/oracle/orahome/base/db11gr2/apex402

Będąc w katalogu /home/oracle/orahome/base/db11gr2/apex402/owa loguję się na SYSa do bazy.

Instaluję najnowszą wersję PL/SQL Web Toolkit:
Aktulaną wersję można sprawdzić przez: SQL>select owa_util.get_version from dual;  (moja była: 10.1.2.0.8)
SQL>@owainst.sql
Dostałem informację, że mam już nowszą wersję i że nie jest wymagana instalacja.

Będąc w katalogu /home/oracle/orahome/base/db11gr2/apex402 loguję się na SYSa do bazy.
Uruchamiamy skrypt upgradeu z parametriami.
Pierwszy parametr to przestrzeń tabel w jakiej powinny być składowane obiekty bazodanowe (tablespace_apex) , drugi parametr to przestrzeń tabel w której maja byc składane pliki (tablespace_files), trzeci parametr to przestrzeń tymczasowa która ma być wykorzystywana przez APEX (tablespace_temp), przestrzeń ta musi być typem przetrzeni tabel tymczasowych. Ostatnim elementem jest tzw. katalog wirtualny (images), w którym znajdować się będą pliki graficzne i odpowiadające za wygląd templatów.
SQL> @apexins APEX APEX APEX_TMP apeximages

.. wśród całej masy komunikatów otrzymamy między innymi:

The structure of the link to the Application Express administration services is as follows:
http://host:port/pls/apex/apex_admin (Oracle HTTP Server with mod_plsql)
http://host:port/apex/apex_admin     (Oracle XML DB HTTP listener with the embedded PL/SQL gateway)
The structure of the link to the Application Express development interface is as follows:
http://host:port/pls/apex (Oracle HTTP Server with mod_plsql)
http://host:port/apex     (Oracle XML DB HTTP listener with the embedded PL/SQL gateway)
JOB_QUEUE_PROCESSES: 1000

Na mojej testowej (czytaj gównianej) maszynie, skrypt wykonywał się przez 16 minut.

Teraz pozostało nam wykonanie podmiany plików graficznych, css i javascript.
W tym celu należy uruchomić skrypt: apxldimg.sql
Skrypt ten przyjmuje tylko jeden argument: lokalizację katalogu z instalką ApEx’a.
Skrypt załaduje obrazki do XDB.

SQL> @apxldimg.sql /home/oracle/orahome/base/db11gr2/apex402


old   1: create directory APEX_IMAGES as ‘&1/apex/images’
new   1: create directory APEX_IMAGES as ‘/home/oracle/orahome/base/db11gr2/apex402/apex/images’
Directory created.
declare
*
ERROR at line 1:
ORA-22288: file or LOB operation FILEOPEN failed
No such file or directory
ORA-06512: at “SYS.XMLTYPE”, line 296
ORA-06512: at line 15

Ostatni krok to ustawienie hasła dla Administratora workspace-ów.

SQL> @apxxepwd.sql jakies_haslo

Session altered.
…changing password for ADMIN
PL/SQL procedure successfully completed.

2 stycznia 2011

ApEx – instalacja.

Zaszufladkowany do: ApEx,Oracle — Tagi: , — Jacek @ 10:29

Fajny artykuł dotyczący instalacji ApExa.

Oracle Datastructures (K1)

Zaszufladkowany do: Oracle — Tagi: — Jacek @ 08:59

CHAR
between 1 and 2000 characters. Domyślna długośc 1. Jeżeli string krótszy niż zadeklarowana wartość, to pozostałe pola są wypełnione spacjami.
VARCHAR2
Określa się maksymalną długość, puste pola nie są wypełniane spacjami. Do 4000 znaków.
NCHAR, NVARCHAR2
datatypes store fixed-length or variable-length character data, respectively, using a different character set from the one used by the rest of the database.
LONG
up to 2 GB of character data. Lepiej używć CLOB i NCLOB. You cannot use LONGs in WHERE, GROUP BY, ORDER BY, or CONNECT BY clauses or in SQL statements with the DISTINCT qualifier. You also cannot create an index on a LONG column.
CLOB and NCLOB
up to 4 GB of character data prior to Oracle Database 10g. Starting with Oracle Database 10g, the limit has been increased to 128 TBs, depending on the block size of the database. The NCLOB datatype stores the NLS data.

NUMBER
provide a precision of 38 digits.
The NUMBER datatype is the only datatype that stores numeric values in Oracle.
The ANSI datatypes of DECIMAL, NUMBER, INTEGER, INT, SMALLINT,
FLOAT, DOUBLE PRECISION, and REAL are all stored in the NUMBER datatype.
With Oracle Database 10g, Oracle added support for the precision defined in the
IEEE 754-1985 standard with the number datatypes of BINARY_FLOAT and
BINARY_DOUBLE. Oracle Database 11g added support for the number datatype
SIMPLE_INTEGER.

DATE
As with the NUMERIC datatype, Oracle stores all dates and times in a standard
internal format.
The standard Oracle date format for input takes the form of DD-MON-YY HH:MI:SS
Youcan change the format youu se for inserting dates for an instance by changing
the NLS_DATE_FORMAT parameter for the instance. Youcan do this for a session
by using the ALTER SESSION SQL statement or for a specific value by using parameters
with the TO_DATE expression in your SQL statement.
As of Oracle9i Release 2, Oracle also supports two INTERVAL datatypes, INTERVAL
YEAR TO MONTH
and INTERVAL DAY TO SECOND.

RAW, LONG RAW
When youspecify one of these datatypes, Oracle will
store the data as the exact series of bits presented to it. The RAW datatypes typically
store objects with their own internal format, such as bitmaps. A RAW
datatype can hold 2 KB, while a LONG RAW datatype can hold 2 GB.
ROWID
special type of column known as a pseudocolumn.The ROWID
pseudocolumn can be accessed just like a column in a SQL SELECT statement.
There is a ROWID pseudocolumn for every row in an Oracle database.
The ROWID relates to a specific location on a disk drive. Because of this, the
ROWID is the fastest way to retrieve an individual row. However, the ROWID
for a row can change as the result of dumping and reloading the database.
It points to the database object number in addition to the identifiers that point to the datafile, block, and row.
ORA_ROWSCN
Oracle Database 10g and later releases support a pseudocolumn ORA_ROWSCN,
which holds the System Change Number (SCN) of the last transaction that modified
the row.
LOB
4 GB of information. CLOB, which can store only character data. NCLOB, which stores National Language character set data. BLOB, which stores data as binary information.
Youcan designate that a LOB should store its data within the Oracle database or
that it should point to an external file that contains the data.
LOBs can participate in transactions. Selecting a LOB datatype from Oracle will
return a pointer to the LOB. You must use either the DBMS_LOB PL/SQL builtin
package or the OCI interface to actually manipulate the data in a LOB.
BFILE
acts as a pointer to a file stored outside of the Oracle database.
columns or variables with BFILE datatypes don’t
participate in transactions, and the data stored in these columns is available only
for reading.
XMLType
A column defined as this type of data will store an XML document in a
character LOB column. There are built-in functions that allow you to extract
individual nodes from the document.
User-defined data
combinations of the basic Oracle datatypes.
AnyType, AnyData, AnyDataSet
datatypes that can be used to explicitly define data structures that exist outside the realm of existing datatypes.
Each of these datatypes must be defined with program units that let Oracle know how
to process any specific implementation of these types.

Tables
As of Oracle9i, youcan define external tables. As the name implies, the data for an
external table is stored outside the database, typically in a flat file. The external table is read only.
The external table is good for loading and unloading data to files from a database, among other purposes.
Oracle Database 11g introduces the ability to create virtual columns for a table.
These columns are defined by an expression and, although the results of the expression
are not stored, the columns can be accessed by applications at runtime.

VIEWS
data structure defined through a SQL statement. The SQL statement
is stored in the database. When you use a view in a query, the stored query is
executed and the base table data is returned to the user. Views do not contain data.
Use a view for:

  • To simplify access to data stored in multiple tables
  • To implement specific security for the data in a table. Starting with Oracle9i, youcan use fine-grained access control to accomplish the
    same purpose.
  • Starting with Oracle9i, youcan use fine-grained access control to accomplish the
    same purpose.

Oracle8i introduced materialized views. These are not really views as defined in this
section, but are physical tables that hold presummarized data providing significant
performance improvements in a data warehouse.

Indeksy
An index is a data structure that speeds up access to particular rows in a database.
An index is associated with a particular table and contains the data from one or more
columns in the table.
The Oracle database server automatically modifies the values in the index when the
values in the corresponding columns are modified.
An index can be either unique (which means that no two rows in the table or view
can have the same index value) or nonunique. If the column or columns on which an
index is based contain NULL values, the row isn’t included in an index.

B*-tree indexes – default index used in Oracle.

The B*-tree index structure doesn’t contain many blocks at the higher levels of
branch blocks, so it takes relatively few I/O operations to read quite far down the B*-
tree index structure.
Oracle allows youto create index organized tables (IOTs), in which the leaf blocks
store the entire row of data rather than only the ROWID that points to the associated
row. Index organized tables reduce the total amount of space needed to store an
index and a table by eliminating the need to store the ROWID in the leaf page. But
index organized tables cannot use a UNIQUE constraint or be stored in a cluster.
(kolejne wersje oracle znoszą w znacznej mierze te ograniczenia)

Reverse key indexes
Reverse key indexes, as their name implies, automatically reverse the order of the
bytes in the key value stored in the index. If the value in a row is “ABCD”, the value
for the reverse key index for that row is “DCBA”.
This reversal causes the index entries to be more evenly distributed
over the width of the leaf nodes.
For example, rather than having the values
234, 235, and 236 be added to the maximum side of the index, they are translated to
the values 432, 532, and 632 for storage. These values are more evenly spread throughout the leaf nodes.

Bitmap indexes (113)
In a standard B*-tree index, the ROWIDs are stored in the leaf blocks of the index. In
a bitmap index, each bit in the index represents a ROWID. If a particular row contains
a particular value, the bit for that row is “turned on” in the bitmap for that
value.The functionality provided by bitmap indexes is especially important in data warehousing
applications in which each dimension of the warehouse contains many
repeating values.

Function-based indexes
A function-based index is just like a standard B*-tree or bitmap index, except that youcan base the index on the
result of a SQL function, rather than just on the value of a column or columns.

Invisible indexes
Normally, all indexes are used by the optimizer.
With the invisible option, an index is not considered as a possible step in an access path, but updates and
deletes to the underlying data are still applied to the index.

PARTITIONING

A partitioned data structure is divided based on column values in the table.
Oracle won’t bother to access partitions that won’t contain any data to satisfy
the query.
You can perform all maintenance operations, such as backup, recovery, and loading, on a single partition.
Youcan automatically implement this type of partitioning,
which is called equipartitioning, by specifying an index for a partitioned table as
a LOCAL index. Local indexes simplify maintenance, since standard operations,
such as dropping a partition, will work transparently with both the index partition
and the table partition.

Sequences

Sequence numbers are defined with a name, an incremental value, and some additional
information about the sequence. Sequences exist independently of any particular table,
so more than one table can use the same sequence number.

Synonyms

To make names simpler and more readable, you can create a synonym for any
table, view, snapshot, or sequence, or for any PL/SQL procedure, function, or package.
Synonyms can be either public, which means that all users of a database can use
them, or private, which means that only the user whose schema contains the synonym
can use it.

Clusters

A cluster is a data structure that improves retrieval performance. A cluster, like an
index, does not affect the logical view of the table.
A cluster is a way of storing related data values together on disk.
Oracle reads data a block at a time, so storing related values together reduces the number of I/O operations
needed to retrieve related values, since a single data block will contain only related rows.
A cluster is composed of one or more tables. The cluster includes a cluster index,
which stores all the values for the corresponding cluster key.
Clusters may not be appropriate for tables that regularly require full table scans, in
which a query requires the Oracle database to iterate through all the rows of the
table. Because you access a cluster table through the cluster index, which then points
to a data block, full table scans on clustered tables can actually require more I/O
operations, lowering overall performance.

Hash Clusters

Each request for data in a clustered table involves at least two I/O operations,
one for the cluster index and one for the data. A hash cluster stores related data rows
together, but groups the rows according to a hash value for the cluster key. The hash
value is calculated with a hash function, which means that each retrieval operation
starts with a calculation of the hash value and then goes directly to the data block
that contains the relevant rows.
By eliminating the need to go to a cluster index, a hash clustered table can be even
faster for retrieving data than a clustered table.

Rules Manager

The concept behind the Rules Manager is simple. A rule is stored in the database and
is called and evaluated by applications. If business conditions or requirements
change, the rule covering those scenarios can be changed without having to touch
the application code. Rules can be shared across multiple application systems, bringing
standardization along with reduced maintenance across the set of applications.
Rules are invoked by events.
You can define conflict resolution routines to handle situations where more than one
rule is matched by an event. The Rules Manager also can aggregate different events
into composite events and maintain state information until all events are received.
Using rules can be a very powerful tool for implementing complex logic, but the use
of rules can affect your application design.

The external table
Should You Use NULLs?
The idea of three-state logic may seem somewhat confusing, especially when you imagine
your poor end users executing ad hoc queries and trying to account for a value
that’s neither TRUE nor FALSE. This prospect may concern you, so you may decide
not to use NULL values at all.
We believe that NULLs have an appropriate use. The NULL value covers a very specific
situation: a time when a column has not had a value assigned. The alternative to
using a NULL is using a value with another meaning—such as 0 for numbers—and
then trying to somehow determine whether that value has actually been assigned or
simply exists as a replacement for NULL.
If you choose not to use NULL values, you’re forcing a value to be assigned to a column
for every row. Youare, in effect, eliminating the possibility of having a column that
doesn’t require a value, as well as potentially assigning misleading values for certain
columns. This situation can be misleading for end users and can lead to inaccurate
results for summary actions such as AVG (average).
Avoiding NULL values simply replaces one problem—educating users or providing
them with an interface that implicitly understands NULL values—with another set of
problems, which can lead to a loss of data integrity.
Basic Data Structures | 91
is read-only;

28 grudnia 2010

Oracle installation notes (K1)

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 13:11

You can install and run multiple versions of Oracle on a single-server machine. AllOracle products use a directory referred to by the environment or system variable ORACLE_HOME to find the base directory for the software they will use.

A rolling upgrade allows you to bring down some of the nodes of the cluster, upgrade their software, and then bring them back online as part of the cluster.

Online transaction processing (OLTP) systems usually have a larger number of users performing smaller transactions, while data warehouses usually have a smaller number of users performing larger queries.

With Automatic Storage Management (ASM), introduced in Oracle Database 10g, you can add additional disk space or take away disks without interrupting database service.

The Automatic Workload Repository (AWR), first available in Oracle Database 10g, maintains a history of workload and performance measurements, which are used by the Automatic Database Diagnostic Monitor (ADDM) to spot performance anomalies. You can also use AWR to track ongoing changes in workload.

Oracle Database Configuration Assistant
Tworzenie ze skryptów: The Oracle software CD-ROM also includes a sample scriptcalled BUILD_DB.SQL

A version of Oracle Net runs on the client machine and on the database server, andallows clients and servers to communicate over a network using virtually any popularnetwork protocol.
Local name resolution – TNSNAMES.ORA
Oracle Names service -  przestarzały 9i
Oracle Internet Directory – Lightweight Directory Access Protocol (LDAP). Oracle Internet Directory (OID) is a part of FusionMiddleware. The OID is also used for a variety of other purposes, such as enabling single sign-on for the Oracle Application Server Portal.
Host naming

These name resolution options are not mutually exclusive. For example, you can use Oracle Internet Directory and local name resolution (TNSNAMES.ORA files)together. In this case, you specify the order Oracle should use in resolving names inthe SQLNET.ORA file.

Oracle Net requires several configuration files. The default location for the files usedto configure an Oracle Net network are as follows:
• On Windows, ORACLE_HOME\net80\admin for Oracle8
and ORACLE_HOME\network\ admin for Oracle8i and more current releases
• On Unix, ORACLE_HOME/network/admin

Youcan place these files in another location, in which case youmu st set an environment or system variable called TNS_ADMIN to the nondefault location.
The files that form a simple Oracle Net configuration are as follows:
LISTENER.ORA –  Contains details for configuring the Oracle Net Listener, such as which instances or services the Listener is servicing.
TNSNAMES.ORA –  Decodes a service name into a specific machine address and Oracle instance for the connection request.
SQLNET.ORA – Provides important defaults and miscellaneous configuration details. Default domain name for your network.
LDAP.ORA - For Oracle8i and later releases, the LDAP.ORA file contains the configuration information needed to use an LDAP directory, such as the Oracle Internet Directory.

The SPFILE can also be kept on a shared disk, so that it can be used to initialize multiple instances in an Oracle Real Application Clusters configuration.

Start bazy danych:
- start instancji - Oracle reads the instance initialization parameters from the SPFILE or INIT.ORA file on the server. Oracle then allocates memory for the System Global Area and starts the background processes of the instance. At this point, none of the physical files in the database have been opened, and the instance is in the NOMOUNT state.
- montowanie bazy danych –  The instance opens the database’s control files. At this point, only the control files are open. This is called the MOUNT state.
- otwarcie bazy danych –  The instance opens the redo log files and datafiles using the information in the control file.

Zamknięcie bazy danych
- zamknięcie bazy –  Oracle flushes any modified database blocks that haven’t yet been written to the disk from the SGA cache to the datafiles. Oracle also writes out any relevant redo information remaining in the redo log buffer. Oracle then checkpoints the datafiles, marking the datafile headers as “current” as of the time the database was closed, and closes the datafiles and redo log files.
- odmontowanie bazy - Oracle updates the relevant entries in the control files to record a clean shutdown and then closes them. At this point, the entire database is closed; only the instance remains.
- zamknięcie instancji - The Oracle software stops the background processes of the instance and frees, or deallocates, the shared memory used for the SGA.

The matchmaker that arranges marriages between Oracle clients and server processes is called the Oracle Net Listener. The Listener detects an incoming request and introduces the requesting client to an Oracle server process. The Listener steps out of the way and lets the client and server communicate directly.

Multi-Threaded Server (MTS) in Oracle7, known as the shared server since Oracle9i. Shared servers allow the Oracle instance to share a set of server processes across a larger group of users. Dispatchers - Clients directly connect to their dispatchers instead of to a server. The dispatchers accept requests from clients and place them in a request queue, which is a memory structure in the SGA. Shared servers - The shared server processes read from the request queue, process the requests, and place the results in the response queue for the appropriate dispatcher.

Program Global Area (PGA) - state information contains information about the SQL statements executed by the session. When youu se a dedicated server, this state is stored in the private memory used by the dedicated server. If you’re using the shared servers, however, any server can work on behalf of a specific client. The session state cannot be stored in the PGA of the shared server process. All servers must be able to access the session state because the session can migrate between different shared servers. For this reason, Oracle places this state information in the System Global Area (SGA). By default, the memory for the shared server session state comes from the shared pool (z SGA). Alternatively, you cou ld also configure something called the large pool as a separate area of memory for shared servers. Oracle Database 11g introduced automated memory management of the SGA and PGA size by default when you set the MEMORY_TARGET initialization parameter.

MTS można sprawdzić w:
- V$SHARED_SERVER_MONITOR - This view contains dynamic information about the shared servers, such as highwater marks for connections and how many shared servers have been started and stopped in response to load variations.
- V$DISPATCHER
- V$SHARED_SERVER
- V$CIRCUIT - Youcan think of the route from a client to its dispatcher and from the dispatcher to the shared server (using the queues) as a virtual circuit. This view details these virtual circuits for user connections.

Data Manipulation Language (DML)
System Change Number (SCN) - A key factor in preserving database integrity is an awareness of which transaction came first. For example, if Oracle is to prevent a later transaction from unwittingly overwriting an earlier transaction’s changes, it must know which transaction began first.
Rollback segments –  Rollback segments are structures in the Oracle database used to store “undo” information for transactions, in case of rollback. When a transaction starts changing some data in a block, it first writes the old image of the data to a rollback segment. A rollback segment is not the same as a redo log. The redo log is used to log all transactions to the database and to recover the database in the event of a system failure, while the rollback segment provides rollback for transactions and read consistency. Blocks of rollback segments are cached in the SGA just like blocks of tables and indexes. In Oracle9i, youhad the option of specifying automatic management of all rollback segments through the use of an undo tablespace.

The server process copies the old image of the employee data about to be changed to a rollback segment and to a redo seqment. The rollback segment changes are part of the redo. This may seem a bit odd, but remember that redo is generated for all changes resulting from the transaction.

Oracle can do one of two things to get the changes into the database on the disk:
• Write all the database blocks the transaction changed to their respective datafiles.
• Write only the redo information, which typically involves much less I/O than writing the database blocks. This recording of the changes can be replayed to reproduce all the transaction’s changes later, if they are needed due to a failure.
To provide maximum performance without risking transactional integrity, Oracle writes out only the redo information.

In Oracle9i, rollback segments were also used to implement a feature called Flashback Query. Remember that rollback segments are used to provide a consistent image of the data in your Oracle database at a previous point in time. With Flashback Query, you can direct Oracle to return the results for a SQL query at a specific point in time.
• Flashback Database, to roll back the entire database to a consistent state
• Flashback Table, to roll back a specific table
• Flashback Drop to roll back a DROP operation
• Flashback Versions Query, to retrieve changes to one or more rows

Oracle notki, performance, system tuning

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 12:50

System tuning
- how to size redo_logs aby nie przełączały się co 2 sekundy
log_checkpoint_timeout
log_checkpoint_interval
fast_start_mttr_target (10g)
- pga_aggregate_target (9i)

program global area - zastepuje: sort_area_size, hash_area_size, bitmap_merge_area_size, create_bitmap_area_size

16% całej pamięci na OLTP
40% całej pamięci na data warehouse

- pinning packages in memory
- statspack

należy ustawić statistics_level = Typical|All
show parameter statistics_level

i badać widkoki:
v$shared_pool_advice
select shared_pool_size_for_estimate, shared_pool_size_factor,est_lc_time_saved from v$shared_pool_advice;
pierwsza kolumna to MB
można ustawić na ostatnią wartość

alter system set shared_pool_size=124m scope=spfile;
shutdown immediate;
startup

show parameter share_pool_size

v$pga_target_advice
v$db_cache_advice
v$java_pool_advice

SQL tuninig
- indexes
- oracle optimizer
- explain plan – co zrobi baza przy wykonaniu czegos ale tak naprawde nie bedzie tego wykonywala
- hins – into individual statements
- stored outlines – save an execution path for a execution statement

Oracle notki, latches, locks

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 12:46

latches dają exclusive access do obiektu
locks – concurrent access but only one can write at the time
simple objects (np. buffer cache)
compound object (table)

locks dla simple objects:
- exclusive – session needs to modify a simple object
- shared – session needs to view an object
- null – if session caches info about an object – null locki is placed on it – it acts like a trigger in case an object is invalidated

tylko dla compound
- sub shared – shared locks on some rows in a table (np w przypadku utworzenia kursora)
- sub exclusive – session need an exclusive lock on a part of an object
- shared sub-exclusive lock – shared lock on a whole table and an exclusive lock on a part of a table

dictionary views:
dba_locks – session id who is holding a lock, type of lock, what mod the lock is in, whether it is blocking another session for access
dba_dml_locks – data manipulation language locks
dba_ddl_locks – data dictionary language locks
dba_blockers – show which sessions are blocking other sessions
dba_waiters – show which sessions are waiting for resources

select * from dba_tables
tam jet init_trans i max_trans
buffer cache – tu trzymane bloki z transakcji

v$system_event
select event, total_waits, average_wait from v$system_event where wait_class != ‘Idle’;

V$session_event – describes events since the session has started up

V$session_wait – check what sid is of the user which is haveing problems

select event, seconds_in_wait, state
from v$session_waits
where sid=142;

select * from v$session;

blocking_session, blockin_instance
select row_wait_obj#, row_wait_block#, row_wait_row#, blocking_session from v$session where sid=142;

w dba_objects sprawdzam czego dotyczy ten object
select owner, object_name from dba_objects where object_id=51161;

select * from v$session

śledzenie sesji
alter session set events ’10046 trace name context forever, lever 8′;

wyłączenie śledzenia sesji
alter session set events ’10046 trace name context off’;

potem do userdump directory i sprawdzenie co się dzieje.
aby to działało to trzeba mieć time_statistics ustawione na true

show paramete timed_statistics;
db file sequential read – indexes
db file scattered read - full table scans
direct path read/write – extensive sort – not enough memory
buffer busy wait – you should tune your sql statements

Oracle notki, Net Services

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 12:35

select * from dba_ts_quotqs;
grant unlimited tablespace to scott; – przyznanie nieograniczonej przestrzeni tabel
sprawdzenie jakie przywileje ma Scott:
select privilege from dba_sys_privs where grantee=’SCOTT’;

select * from dba_profile;
DBA_STMT_AUDIT_OPTS
DBA_PRIV_AUDIT_OPTS
DBA_AUDIT_SESSION

———————- NET SERVICES ———————-

sqlplus scott@host:1521/orcl
po ustawieniu zmiennej TNS_ADMIN – tam pliki net
listener.ora – konfiguracja listenera
tu można ustawić shared server zamiast dedicated server
sqlnet.ora – tu różne rzeczy – nameing, authentication
można dodać TCP_VALIDNODE_CHECKING = YES

TCP.INVITED_NODES = (, ,)
TCP.EXCLUDED_NODES = ( , , )
SQLNET.AUTHENTICATION_SERVICES = (NTS)
NTS – windows authentication
NAMES.TRACE_LEVEL = ADMIN

tnsnames.ora – używany tylko, jeżelu używa się metody local naeming

na kliencie:
netca
nameing methods
on modyfikuje sqlnet.ora i dodaje NAMES.DIRECTORY_PATH = (EZCONNECT, TNSNAMES)

aby zmodyfikować tns to: netca
a potel local net service name configuration
lsnrctl
status
set trc_level support
set log_directory c:\oratrc
set log_file mylog.log
seve_config

RAC – wiele instancji w jednej bazie
netca – konfiguracja net – graficzna
select * from all_services;
distributed query – zapytuje wiecej niż jedna baze danych
sqlplus / as sysdba

sql> create public database link orcl2
connect to scott identified by tiger
using ‘orcl2′ (tu nazwa na której nasłuchuje listener)

sql> select sysdate from dual@orcl2;
select * from dba_db_links;
col db_link format a20
col username format a15
col host format a12

w tnsnames.ora można zdefiniować w jakim modzie będzie pracował serwar shared or dedicated
defoult’owe pasło dla sys is “change_on_install”
delfoul’owe paseło dla system is “manager”

scott/tiger
hr/hr

aby uruchomić funkcje sprawdzające hasło:
@%oracle_home%\rdbms\admin\utlpwdmg

select text from dba_source;

Oracle notki, packages

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 12:32

Pomaga w organizacji kodu.
Składają się ze specyfikacji (SPEC) i kodu (BODY). Body można zaszyfrować (wrap function)

Common packages:

-standard
commit, rollback, round
select round(3.14) from dual;
select sys.standard.round(3.14) from dual;
desc sys.standard; – opis danego package

-dbms_output
dbms_output.put_line(‘name’);

-dbms_stats
exec dbms_stats.gather_table_stats(‘SCOTT’,'PERSON’);
select table_name, to_char(last_analyzed,’hh23:mi’) analyzed
from user_tables where table_name=’PERSON’;

-dbms_schduler
(dbms_job – oracle 9)

grant create job to scott;
select snap_id,to_char(snap_time,’dd-mm-yyyy hh24:mi:ss’) from stats$snapshot
select text from dba_source where name=’MISC’;

Kompilacja obiektów w schemacie
SQL> dbms_utility.compile_schema(‘SCOTT’);

UNDO TABLESPACE

SELECT tablespace_name,status,CONTENTS FROM dba_tablespaces;
show parameter undo
SELECT file_name FROM dba_data_files;
SELECT file_name, bytes FROM dba_data_files WHERE tablespace_name=’UNDOTBS1′;
SELECT DISTINCT owner,tablespace_name, bytes, status FROM dba_undo_extents WHERE status = ‘ACTIVE’;
SELECT DISTINCT owner,tablespace_name, bytes, status FROM dba_undo_extents;

Oracle notes – PL/SQL basics

Zaszufladkowany do: Bazy danych,Oracle,PL/SQL,SQL — Tagi: — Jacek @ 12:16

PL/SQL Procedural Language SQL
anonymous blocks – bez nazwy
procedures/functions – stored in data dictionary
packages – zgrupowane procedury i funkcje

Data Types
- scalar (binary_integer, integer, string …)
- composite (nested tables, varrays, record …)

r employees%rowtype;

nested tables of numbers:

TYPE – określamy jakiego jest typu
linia 5 – konstruktor –  przypisujemy konstruktor do zmiennej (na razie on nie istnieje)
tworzymy go przez extend. W lini 7 tworzenie slotu dla zmiennych.

- reference – procedury mogą odwoływać się do refcursors.

Anonymous blocks:

od DECLARE do BEGIN – deklarujemy zmienne
od BEGIN do EXCEPTION – kod
:=” (przypisanie wartości)
anchor data type – można przypisać typ danych do zmiennej na podstawie tabeli (linia 6)

Procedures:

tu są nasze procedury
select * from user_source;
select text from user_source where name = ‘nazwa_procedury’;

Zamiast DECLARE (jak w anoymouns blocks) jest AS. Pomiędzy AS a BEGING deklarujemy zmienne.
Wywołanie takiej procedury:
SQL> BEGIN
SQL> give_raises(1.5);
SQL> END;
SQL> /
lub:
exec give_raises(1.5);

CURSOR – to jest SELECT wewnątrz bloku PL/SQL który może zwrócić dużą liczbę rekordów.
Jeżeli SELECT może mieć więcej niż jeden wynik trzeba używać CUROSR’ów.

CURSOR – deklaracja kursora – i następnie SELECT
Cursor zostaje wykonane w kodzie (po BEGIN)
rec – nazwa zmiennej IN in nazwa kursora
count – metoda należąca do nested tables … count równe 1,2,3 …

Te wartości które mamy w tablicy możemy przkazać np do innej procedury.

Cursor teraz zawiera employee_id, hire_data
Aby zrobic updaty na cursorze  trzeba go zrobic FOR UPDATE
WHER CURRENT OF EMP_CUR – praca na aktualnych danych w kursorze

LOOPS

EXCEPTION HANDLING

crate or replace procedure add_emp(eid number, last varchar2, first varchar2, email varchar2, hire_date date)
as
hire_date_excepition exception;
email_exception exception;
begin
if hire date > sysdate then
raise hird_date_exception;
end if;
if email is not null and email not like ‘%@%.%’ then
raise email_exception;
end if;

— jakis kod dodajacy pracownika

exception
when hire_date_exception then
dbms_output.put_line(‘wrong date’);
when email_exception then
dbms_output.put_line(‘wrong email format’);
end;
/

exception – tu się zaczyna blok exception
Wywołujemy procedurę:

exec add_emp(500,’Joe’,'Jule’,'joe@serwer.com’,sysdate + 2)

i zwraca błąd, że jest zła data.

Oracle notki – export, import, DataPump, SQL Loader

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 12:07

export/import

transportable tablespaces – importuje sie tylko metadane, a potem kopiuje pliki

DataPump (10g)

SQL Loader

exp scott tables=person,cities log=log.txt grants=n

transportable tablespaces
alter tablespace users read only;
alter tablespace data read only;
exp sys/sys tablespaces=users,data transportable_tablespace=y
skopiowac dane pliki miedzy systemami

DataPump (10g)

select directory_path from dba_directories where directory_name=’DATA_PUMP_DIR’;
expdp scott/tiger dumpfile=data_dump_dir:info.dmp nologfile=y tables=person,cities

select * from dba_datapump_jobs;
sql> create directory dp as ‘c:\expimp’;
sql> grant read,write od directory dp to public;
sql> grant exp_full_database to scott;

expdp scott/tiger full=y dumpfile=dp:full%u.dmp logfile=dp:full.log job_name=full_export

w trakcie trwania exportu mozna wcisnac CTR+C aby wejsc w tryb interaktywny i mozna dac np.: exit_client (export idzie w tlo i trwa nadal)

expdp scott/tiger full=y estimate_only=y logfile=dp:estimate_full.log job_name=estimate_full_export

SQL Loader

tworze plik: person.ctl
load data
infile ‘c:\data.txt’
into table person2
fileds terminated by “:” optionally enclosed by ‘”‘
(pid,first,last)

potem uruchamiam komende:
sqlldr scott/tiger contro=person.ctl
tworze plik: person2.ctl

load data infile ‘c:\data.txt’ replace into table person2
(pid position (01:02) integer external,
first position (03:10) char,
last position (10:20) char)

tworze plik: person3.ctl

load data
infile ‘c:\data.txt’
replace
into table person2
when city=’denver’
fileds terminated by “:” optionally enclosed by ‘”‘
(pid,first,last,city,state)

Oracle notki, constraints, sequences, views

Zaszufladkowany do: Bazy danych,Oracle,PL/SQL,SQL — Tagi: — Jacek @ 11:56
alter table person add constraint pk_person primary key(id);
compound primary key – złożony – na więcej niż jednej kolumnie.
create table citeis(city varchar(30), state char2(2), constraint pk_cities primary key(city,state));
obydwie kolumny będą widziane jako NOT NULL – ale to wcale nie znaczy że są primary_keys

select * from USER_CONSTRAINTS;
select * from DBA_CONSTRAINTS;

aby dowiedzieć się jakie są naprawdę constraints nałożone na daną tebelę.
select * from USER_CONS_COLUMNS;
select * from DBA_CONS_COLUMNS;

aby sprawdzić na jakich kolumnach są nałożone constraints.
select constraint_name, column_name, position
from USER_CONS_COLUMNS
where constraint_name in(select constraint_name from user_constraints where table_name = ‘CITIES’);

sprawdzenie domyśnej tablespace:
slect default_tablespace from user_users;
slect default_tablespace from dba_users;

create table as statement
create table COLORADO_PERSON as select * from PERSON where st = ‘CO’;

select * from USER_TAB_COLUMNS; – aby dowiedzieć się jak są zdefiniowane kolumny w danej tabeli;

UNIC CONSTRAINT

taki sam jak primary key ale dozwolone są NULL
alter table PERSON add constraint UK_PERSON_USERNAME unique(USERNAME);
alter table PERSON add constraint ck_person_gender check(gender in(‘M’,'F’));

FOREIGN CONSTRAINT – pozwala znaleźć releacje pomiędzy dwoma tablicami

jedna tablica to child druga to parent
dodajemy foreign constraint to child table:
alter table person add constraint fk_person_cities foreign key(city,state) references cities(city, state);

tabela cities jest tu tabelą parent i tu są zdefiniowane miasta i stany. Przy próbie wpisu to tabeli person miasta i stanu którego nie ma w tabeli cities otrzymamy błąd.

select a.constraint_name, constraint_type, column_name, r_constraint_name
from user_constraints a, user_cons_clumns b
where a.constraint_name = b.constraint_name
and a.table_name = ‘PERSON’;

Wyłączenie danego CONSTRAINT:
alter table PERSON disable constraint fk_person_cities;
alter table PERSON enable constraint fk_person_cities;

alter table users add constraint fk_users_person
foreign key(username) references person(username)
deferrable initially deferred;

SEQUENCE

autoincrement, przechowuje liczby
create sequence username_seq start with 10 increment by 1;
select * from user sequences;
update users set id = username_seq.nextval;
select username_seq.currval from dual;

VIEWS:

create or replace view person_view(name) as
select last || ‘,’ || first
from person
order by last, first;
create or replace view person_view as
select last,first,city,st
from person
order by last,first;

W drugim wypadku kolumny dokładnie odpowiadają nazwom kolumn w tabeli dlatego ten widok można wykorzystać do updateowania tabeli.

select * from USER_VIEWS;
select * from DBA_VIEWS;
select * from DBA_OBJECTS;

Oracle notki

Zaszufladkowany do: Bazy danych,Oracle — Tagi: — Jacek @ 11:52
sql> alter system suspend; zabrania wprowadzania danych
sql> alter system resume – powrót do normalnego stanu
V$PARAMETER – tabela z parametrami – można sprawdzić czy jest system modificable;
sql> alter system set background_dump_dest=’c:\oracle’;
sql> alter system set audit_file_dest=’c:\oracle’ scope=spfile; zmiana tylko w spfilu i uwzględniona po ponownym uruchomieniu.
sql> alter system set user_dump_dest=’c:\oracle’ scope=memory; zmiana tylko na daną chwilę, po ponownym uruchomieniu wszystko wróci do normy.
V$SYSTEM_PARAMETER
V$SYSTEM_PAREMETER2 – dotyczą danej instancj
V$PARAMETER
V$PAREMERER2 – dotyczą danej sesji
alter session set statistics_level=basic; – dotyczy tylko danej sesji, pozostałe sesje pozostaną niezmienione
V$SPPARAMETER – ustawinia dla pliku spfile;
V$OBSOLETE_PARAMETER –  przestarzałe parametry – raczej nie powinny być ustawiane w plikach inicjalizacyjnych.
select * from v$obsolete_parameter where isspecified=’TRUE’;
« Nowsze wpisyStarsze wpisy »

Strona startowa: www.jaceksen.pl