The Cuddletech Sas Guide To Oracle: Ben Rockwood Draft: Feb 10Th, 2005
The Cuddletech Sas Guide To Oracle: Ben Rockwood Draft: Feb 10Th, 2005
Ben Rockwood
This book is dedicated to the memory of my hero, Bob Larson, who gave
more to the UNIX community than most will ever know.
Contents
1 Introduction 5
1.1 The Relational Model . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2 Play Along at Home . . . . . . . . . . . . . . . . . . . . . . . . . 7
3 Oracle Basics 13
3.1 Create a database . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.2 Connect and Startup . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.3 Create a table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.4 Add data to a table . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.5 Create an index . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.6 Query the table . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.7 Creating and Querying a View . . . . . . . . . . . . . . . . . . . 18
3.8 Destroying Schema Objects . . . . . . . . . . . . . . . . . . . . . 18
3.9 Stopping the database . . . . . . . . . . . . . . . . . . . . . . . . 19
3.10 Destroy the database . . . . . . . . . . . . . . . . . . . . . . . . . 19
2
CONTENTS 3
7 The Listener 40
7.1 Configuring the Listener . . . . . . . . . . . . . . . . . . . . . . . 40
7.2 Starting the Listener . . . . . . . . . . . . . . . . . . . . . . . . . 42
7.3 TNS Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
7.4 Connecting remotely . . . . . . . . . . . . . . . . . . . . . . . . . 44
7.5 Troubleshooting TNS . . . . . . . . . . . . . . . . . . . . . . . . 44
8 Oracle Programming 46
8.1 SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
8.2 PL/SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
8.3 Pro*C: The Oracle SQL Precompiler . . . . . . . . . . . . . . . . 49
8.4 The C Interface: OCI . . . . . . . . . . . . . . . . . . . . . . . . 51
8.5 Regarding PERL . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
9 SQL*Loader 55
9.1 Loading SYSLOG into a table . . . . . . . . . . . . . . . . . . . . 55
11 Using RMAN 65
11.1 Enabling ARCHIVELOG Mode . . . . . . . . . . . . . . . . . . . 66
11.2 Basic RMAN Backup . . . . . . . . . . . . . . . . . . . . . . . . . 68
11.3 Basic Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
11.4 Listing Backups . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
11.5 Advanced Backup . . . . . . . . . . . . . . . . . . . . . . . . . . 74
11.6 Advanced Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . 75
12 Loose Ends 82
12.1 Oracle Flashback . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
12.2 Data Guard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
12.3 OLTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
12.4 Data Warehousing and Data Marts . . . . . . . . . . . . . . . . . 87
12.5 Oracle Options and Extensions . . . . . . . . . . . . . . . . . . . 88
12.6 Oracle Pricing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
12.7 License Enforcement . . . . . . . . . . . . . . . . . . . . . . . . . 91
CONTENTS 4
A Oracle Proccesses 96
Chapter 1
Introduction
5
CHAPTER 1. INTRODUCTION 6
lot of time that could have been better spent on other tasks I’ve finally gained
the added knowladge that makes a world of diffrence when I interface with my
DBA.
This book won’t teach you everything about Oracle, and its not intended to.
There are plenty of ”Oracle for Dummies” (or equivelent) books on the market.
Instead, your going to get an overview of all the major componants of Oracle,
specifically Oracle10g, in a practical start-to-finish linear fashion from chapter
to chapter. As a sysadmin I’ve focused on topics that are of most practical in-
terest to my needs whether it be for practical use or simply to better understand
and guide my DBA. Even though you might never export an Oracle database its
essential that you understand what it is, so that when your DBA uses them you
know what they are doing and how to provide for their requirements. Through-
out the book you’ll find URL’s to Oracle documentation which will provide you
with more information on a given topic.
By the end reading this book you’ll have the confidence to login to Oracle,
configure basic networking, manipulate user access, understand the program-
ming interfaces, utilize major tools for importing and exporting data, interface
with the backup system, but most importantly you’ll leave with the knowladge
required to allow you to learn the database in more detail for yourself. Any
mature RDBMS today requires a large amount of knowladge about to simply
get you into a position to ”poke around” and learn for yourself. Unlike your first
UNIX account, its not so easy as just logging in, typing ”ls” and learning from
there, you need to be able to understand the login proccess, enviromental vari-
ables, connection methods, some basic SQL, and possibly some basic network
configuration before you can even just explore the internals of the database. The
most important thing to take away is the confidence and basic skills required to
let you learn for yourself.
8. Batch and end-user operations are logically separate from physical storage
and access methods.
9. Batch and end-user operations can change the database schema without
having to recreate it or the applications built upon it.
10. Integrity constraints must be available and stored in the relational database
metadata, not in an application program
11. The data manipulation language of the relational system should not care
where or how the physical data is centralized or distributed.
12. Any row processing done in the system must obey the same integrity rules
and constraints that set-processing operations do.
provides you with a 30 Day trial period by which to test and explore the prod-
uct. Plese note that while the software will not stop you from running Oracle
longer than that, it is illegal.
Chapter 2
9
CHAPTER 2. INSTALLATION AND THE OFA 10
secondary groups. After Oracle is installed you can change the primary group
to dba, many people do, but it’s not recommended.
umask 022
ORACLE_BASE=/u01/app/oracle
ORACLE_SID=MYSID
ORACLE_HOME=$ORACLE_BASE/product/10.1.0/db_1
ORACLE_PATH=/u01/app/oracle/product/10.1.0/db_1/bin:. #( Oracle version of $PATH)
TNS_ADMIN=$ORACLE_HOME/network/admin #(Oracle Net Services config files)
The most important variables here are ORACLE SID and ORACLE HOME.
If these aren’t defined you’ll have problems all over the place, namely when
trying to use SQLPlus.
You can find a full list of all supported environmental variables in the docu-
mentation. (http://download-west.oracle.com/docs/html/B10812 02/chapter1.htm#sthref23)
/u01/app/oracle/ Base
/u01/app/oracle/oraInventory Oracle Inventory
/u01/app/oracle/product/ Oracle Software
/u01/app/oracle/product/9.2.0 Oracle9i Home
/u01/app/oracle/product/10.1.0/db_1 Oracle10g Home
/u01/app/oracle/admin/ Administrative
/u01/app/oracle/admin/TAR Admin Support Logs
CHAPTER 2. INSTALLATION AND THE OFA 11
When you create your databases with dbca continue to use the OFA by
installing your datafiles in /u01/oradata/SID, or if you prefer to use a different
mount point, /u02/oradata/SID. Obviously you can get creative with your data
layout as it maps to your disk subsystem. Some DBAs will request a local mount
for /u01 to install oracle, and then two or more /u0x directories with different
specs for datafiles. In this way, we can distribute files onto disks with different
accesses patterns or tuning specifications.
Chapter 3
Oracle Basics
To get a good understanding of the basics of Oracle, lets set out to do the most
basic operations that we would need to really utilize the database. These are:
13
CHAPTER 3. ORACLE BASICS 14
13. We’ll now have the chance to look at our configuration and save an HTML
copy of it. When done, create the database.
14. The database will now build. On my Sun Blade 100 this process took
about 10 minutes.
15. Lastly, you’ll get a confirmation dialog with the database name, SID,
Server Parameter Filename and an Enterprise Manager URL.
After the database has been created, you can go examine the files it created.
CHAPTER 3. ORACLE BASICS 15
bash-2.05# cd /u02/oradata/test
bash-2.05# ls -alh
total 1451556
drwxr-xr-x 2 oracle oinstall 512 Oct 5 16:43 .
drwxr-xr-x 4 oracle dba 512 Oct 5 16:40 ..
-rw-r----- 1 oracle oinstall 2.7M Oct 5 16:53 control01.ctl
-rw-r----- 1 oracle oinstall 2.7M Oct 5 16:53 control02.ctl
-rw-r----- 1 oracle oinstall 2.7M Oct 5 16:53 control03.ctl
-rw-r----- 1 oracle oinstall 10M Oct 5 16:53 redo01.log
-rw-r----- 1 oracle oinstall 10M Oct 5 16:46 redo02.log
-rw-r----- 1 oracle oinstall 10M Oct 5 16:51 redo03.log
-rw-r----- 1 oracle oinstall 210M Oct 5 16:53 sysaux01.dbf
-rw-r----- 1 oracle oinstall 430M Oct 5 16:53 system01.dbf
-rw-r----- 1 oracle oinstall 20M Oct 5 16:43 temp01.dbf
-rw-r----- 1 oracle oinstall 25M Oct 5 16:53 undotbs01.dbf
-rw-r----- 1 oracle oinstall 5.0M Oct 5 16:46 users01.dbf
There will also be files in your oracle admin directory (OFA path: /u01/app/oracle/admin/(sid))
and the dbs directory (OFA path: /u01/app/oracle/product/10.1.0/db 1/dbs).
If you want to play with Enterprise Manager, you can do so now. Go to the
URL listed in the final dialog of the dbca session. At the login screen use the
username ”sys”, the password ”passwd” (as we specified during creation) and
from the drop down choose ”SYSDBA”. Once you login you’ll get a licensing
information screen, agree to the terms to keep playing. After this you’ll get the
full Enterprise Manager experience. You’ll see that the database has already
been started and is up. On the ”Administration” tab you can really play with
some nifty things. You can create nearly any database component here without
ever touching SQL*Plus.
If you playing with the Enterprise Manager (EM), go ahead and shutdown
the database so we can see how to start it up using SQL*Plus.
There are a wide range of additional startup arguments that can be made
rather than just STARTUP, such as to keep the database from mounting (NOMOUNT)
or to force it to start (FORCE).
Once startup completes the database should be open, mounted and in read/write
mode.
Table created.
SQL>
1 row created.
1 row created.
1 row created.
SQL>
Index created.
SQL>
NAME
------------------------------
CHAPTER 3. ORACLE BASICS 18
Ben Rockwood
Tamarah Rockwood
Nova Rockwood
SQL>
View created.
NAME CELL_NUM
------------------------------ ------------
Ben Rockwood 650-555-2345
Tamarah Rockwood
Nova Rockwood
SQL>
View dropped.
3 Nova Rockwood
Menlo Park, CA
Table dropped.
SQL>
proper state, just issuing the SQL ”drop test” will destroy the test database we
created.
Chapter 4
21
CHAPTER 4. POKING AROUND INSIDE ORACLE 22
COUNT(*)
----------
1488
SQL>
Sadly, when managing Oracle your going to need to query the system tables
a lot, so keeping your SQL skills sharp and a reference or cheat sheet nearby is
a good idea. Here’s a common example:
SQL> select * from dba_users
2 where username = upper(’benr’);
SQL>
Something you’ll immediately find, if you haven’t already, is that SQL*Plus
table output sucks! Look at all that output, it’s hard to see whats happening.
For this reason, whenever possible limit your queries down to just what you
really need. You’ll also notice that when you are searching (the where clause)
CHAPTER 4. POKING AROUND INSIDE ORACLE 23
the search parameter is case sensitive, which can be confusing because so much
of SQL is very case insensitive. Most everything is stored in uppercase, so you
can either search for ’BENR’ or you can use the SQL function upper() to convert
the casing to uppercase.
Lets try outputting that table again with a little less cruft this time:
SQL>
Must better that time. Whenever possible, just trim down queries as a best
practice.
cause they are in the SYS schema, you’ll sometimes see them called properly
as SYS.V$something. The views are of interest to SAs because they contain
dynamic performance data. When looking at system views you might also see
GV$something views, these are for RAC installations were you want to see the
Global View.
You can learn about all of these views in the Oracle Database Reference.
http://download-west.oracle.com/docs/cd/B14117 01/server.101/b10755/dynviews part.htm#i403961
data is stored in more V$ views and is intended to be viewed via the Enterprise
Manager. While graphs aren’t as kool as piles of output, I’ll take Enterprise
Manager in this case.
Chapter 5
As an SA you need to be able to divide the various files in Oracle into logical
groups mentally. Knowing what goes where will help you get a better idea of
how you can help maintain Oracle from a systems level. For this discussion,
we’ll assume that you have installed Oracle according the the OFA discussed
earlier.
We can device the installation into 2 main catagories right off the bat: oracle
distribution files and instance files. Oracle distribution files would be everything
that you installed when you installed Oracle. Database files would be all the
files that pertain to a given instance of the database.
It’s important here to clarify the diffrence between a ”database” and an
”instance”. A ”database” is the collection of files that store your data and all
the metadata and configuration information to govern how that data is accessed,
utilized, etc. An ”instance” is a group of proccesses that make your database
accessable. So, the datafile ”users01.dbf” is a componant of the database and
the proccess logwritter proccess ”ora lgwr SID” is a componant of the instance.
26
CHAPTER 5. FILES AND COMPONANTS 27
of the controlfile, similar to the way SDS uses multiple state databases. This
guarrenties that even if 1 control file is lost or corrupt we still have another
usable copy. Controlfiles supposedly can be rebuilt if they are lost or destroyed
but it isn’t easy. If there is a file you want to make sure your backing up, this
is it.
The datafiles contain the actual data. These are after refered to as ta-
blespaces. Within the tablespace resides all the tables that make up your
database. Users use the ”users tablespace” which is in the users01.dbf datafile.
Temp tables are written to the ”temp tablespace” which is in the temp01.dbf
datafile. So on and so forth.
Redo logs are the database equivilent to a filesystem journal. When changes
are made to the database the changes are written to the redo log. If data were
log, we could recover the lost changes by replaying the redo logs just like we’d
replay a VxFS journal on an inconsistant filesystem. Redo logging is enabled
by default, but can be turned off if you choose by enabling the NOLOGGING
parameter. There are typically 3 or more redo logs, which are written to in a
round-robin fashion. Each one fills up untill all the logs are full and it begins
overwritting the first again.
On a related note that we won’t go into depth about, redo logs can be
archived. When a database is in ARCHIVELOG mode the redo logs can be
written out to archive logs and stored elsewhere. The upside is that you could
replay weeks of transactions back into the database if you wanted to. The down-
side is that if the, so called, archive log destination (directory where archived
redo logs get stored) becomes full or unwrittable the instance will shutdown!
Typically a cron or backup job is written to backup or move the archived redo
logs to tape or a permanate storage location on a regular schedual to ensure the
archive destination never fills up.
Lets break down the admin files and directories.
The bdump directory is an important directory because both trace files and
alert logs are stored here. If you have a problem with your database the first
place you’ll want to look is in the alert log.
instance will have a pfile in it’s admin directory. An init.ora will exist in the
$ORACLE HOME/dbs/ directory. In the pfile directory of each instances ad-
min directory you also find an init.ora.
The parameter files contain a variety of Oracle tunables including the database
block size (db block size), database cache size (db cache size), number of open
cursors (open cursors), the database name (db name) and domain (db domain),
resource limits (proccesses), size of all the various pools (large pool size, etc),
and the location of the control files (control files). The paramter files is read by
Oracle when you start an instance, as the name ”initialization” implies. Once
this file is read and proccessed the control files will point the instance to the
rest of the datafiles.
More and more you hear about spfile’s. Unlike your init.ora pfile, you can’t
(well, you shouldn’t anyway) hand edit an spfile. Oracle has been making more
and more parameters dynamically changable. Apparently in older releases of
Oracle changing parameters would involve shutting down the database, modify-
ing the paramter in the pfile and then restarting. Now many of these paramters
can be change with an ALTER statement and take effect immediately without
a downtime. The problem was that if you changed these dynamic paramters the
changes wouldn’t be persistant across database restarts, so the DBA would have
be careful to always update the pfile after making the change. Obviously this
became a problem quickly as careless DBAs would simply forget. So to combat
the problem the spfile was made avalible where dynamicly changed parameters
would be recorded in the ”binary” spfile and thus make tunable paramters per-
sistant. To use an spfile you actually need to explicitely create one by converting
your existing pfile into a pfile (eg: ”CREATE SPFILE ’spfileSID.ora’ FROM
PFILE=’initSID.ora’;”). You can look in the v$parameter system view to see
where your spfile is. In 10g it seems like an spfile is created on your behalf,
whereas in previous releases it had to be manual created as noted above.
NAME
--------------------------------------------------------------------------------
VALUE
--------------------------------------------------------------------------------
spfile
/u01/app/oracle/product/10.1.0/db_1/dbs/spfiletest.ora
When databases are created using dbca they use an spfile by default and are
located in $ORACLE HOME/dbs.
this book to cover the topic, it makes the most sense from a sysadmin point of
view, so lets dive in.
When Oracle starts an instance it reads the spfile or pfile to determine the
initialization paramters. It uses these paramters to allocate the SGA and create
background proccesses. All this is done without associating a database to the
instance! At this point the instance is started but not mounted, or as some say
”Started in no mount mode”. They say that because you can reach this state
by using the SQL*Plus command ”startup nomount”.
related files to the running instance. If you are missing files this is where you’ll
get your error. If you started your instance using nomount you can’t use the
startup command again, but you can use alter database statements to change
the state of your instance.
Lets quickly look at what happens when you mount your database with the
instance already running but with the all the data and control files missing
(renamed data directory):
SQL> alter database mount;
alter database mount
*
ERROR at line 1:
ORA-00205: error in identifying controlfile, check alert log for more info
SQL> quit
# tail /u01/app/oracle/admin/test/bdump/alert_test.log
alter database mount
Wed Oct 13 14:28:12 2004
ORA-00202: controlfile: ’/u02/oradata/test/control01.ctl’
ORA-27037: unable to obtain file status
SVR4 Error: 2: No such file or directory
Additional information: 3
Wed Oct 13 14:28:12 2004
Controlfile identified with block size 0
Wed Oct 13 14:28:12 2004
ORA-205 signalled during: alter database mount...
#
Notice that it complains about the first controlfile and not the datafiles.
Thats because the parameter file has a listing of all the controlfiles and the
controlfile is responsable for storing information about all the other datafiles
and resources used by the database. If the controlfile can’t be read the database
doesn’t know what else exists! This is why you should be careful to keep good
backups of your controlfiles using plain ol’ system backups. This is also why
Oracle maintains multiple copies (typically 3) of the control file for safety.
Lets put all the datafiles back and try mounting the database again.
# mv test.HOLD/ test
# sqlplus sys/passwd as sysdba
SQL*Plus: Release 10.1.0.2.0 - Production on Wed Oct 13 14:36:09 2004
Copyright (c) 1982, 2004, Oracle. All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production
With the Partitioning, OLAP and Data Mining options
Looking at the proccesses on the system, you’ll notice that after mounting
the database no change has occured to the proccesses.
Once an instance is started using a pfile and the mount proccess has used
the controlfile(s) to associate the datafiles with the instance we need to open
the database. Untill a database is opened it is not accessable. It’s equivilent
to starting a system in single-user mode. Some ammount of interaction with
the databse is avalible at this stage but it’s limited to fixed tables and views.
The fixed tables and views are those in the data dictionary (Oracle’s internal
configuration tables).
But here’s the confusing part, the normal data dictionary tables (ALL USERS,
for example) will give you an error, but most of the V$ tables, which are sup-
posed to be the dynamic tables, work fine! What exactly ”fixed” is supposed to
mean in the case I dunno.
STATUS
------------
MOUNTED
SQL>
To open the database for normal access, we can alter the database again.
The other set of files created during install is the Oracle Inventory, found
according to the OFA in /u01/app/oracle/oraInventory. The Inventory is used
by the Oracle Universal Installer to record what products have been installed,
where the were installed, and how. The Oracle Inventory doesn’t impact databases
in any way and only impacts the installer. You can see a list of all the products
and options you have installed in the oraInventory/Components directory.
Chapter 6
Security and Permissions are, I think, probly the most confusing topics pertain-
ing to Oracle. The line between the UNIX user (oracle) and the Oracle users
(sys, etc) gets really blurred. Just getting logged into SQL*Plus can be a major
task because you aren’t sure whether it wants UNIX or Oracle user names and
passwords. I’ll try and demystify this a bit.
SYS The SYS user owns all base tables and user-accessable view of the data
dictionary (Oracle configuration information). No Oracle user should ever
alter (update, delete, or insert) any rows or schema objects conatained
in the SYS schema, because such activity can compromise data integrety.
The security administrator must keep strict control of this central account.
33
CHAPTER 6. USERS AND PERMISSIONS 34
SYSTEM The SYSTEM user is used to create additional tables and views that
display administrative information, and internal tables and views used by
various Oracle options and tools.
SYSMAN The SYSMAN user represents the Enterprise Manager super admin
account. This EM admin can create and modify other EM admin accounts
as well as admin the database instance itself.
DBSNMP The DBSNMP user is used by EM to monitor the database. EM
uses this account to access performance stats about the database. The
DBSNMP credentials sometimes referred to as the monitoring credentials.
In addition to these users, a user can connect with diffrent levels of privileges,
namely SYSDBA and SYSOPER. When you connect using ”connect sys/passwd
as sysdba” your connecting as the SYS user and requesting SYSDBA privs.
Because the SYS user is the Oracle equivilent to the UNIX root user Oracle
makes you specify the amount of control you have, which is why you’ll get an
error if you try to connect without specifying the privs:
The big diffrence between SYSDBA and SYSOPER privs is that SYSDBA
can do anything (just like root). The SYSOPER privs allow you just about the
same amount of control but won’t allow you to look at user data. Both privs
allow you to ALTER DATABASE, CREATE SPFILE, STARTUP or SHUT-
DOWN, ALTER DATABASE ARCHIVELOG, and includes RESTRICTED
SESSION privs. However, only SYSDBA can CREATE or DROP DATABASE,
and the ALTER DATABASE RECOVER options for SYSOPER are limited to
complete recovery only.
Naturally these are all administrative accounts and therefore shouldn’t be
used for general database usage. (We used sys in our basics chapter because its
already there and I wanted to focus on the basics without jumping straight into
authentication).
User created.
Grant succeeded.
User altered.
SQL>
So here, as SYSDBA we’ve created the user ”ben” with the default profile
identified by the password ”passwd”. The users default tablespace is users and
temp tablespace is temp and the account is unlocked. In the second statement
we grant the ”connect” role to user ben. And in the third statement we alter
the quota on the users tablespace by user ben.
Now lets login with the user...
ERROR at line 1:
ORA-01950: no privileges on tablespace ’USERS’
SQL>
Wait? Even though the user is added the user has no privs? This is indeed
lame. The user wasn’t defined with any roles. Each user must have one or more
security role assigned to them. You’ll notice that even though in the creation of
the user our second SQL statement was to grant the ”CONNECT” role to the
user, but that wasn’t enough. By default in 10g a new user has no privs at all,
so we need to just keep piling on the roles. Lets spend a minute sorting out the
diffrence between privileges, roles, and profiles.
So we can assert a good ammount of control over the user here, by bundling
privileges into roles and then granting those roles to user accounts, and then
further controlling the resource usage of the account with a profile. In almost
all cases the ”default” profile will be used, so lets look at roles in more depth.
Lets list some of the predefined roles that Oracle makes avalible to us:
ROLE PASSWORD
------------------------------ --------
CONNECT NO
RESOURCE NO
DBA NO
SELECT_CATALOG_ROLE NO
EXECUTE_CATALOG_ROLE NO
...
SQL> select * from DBA_ROLE_PRIVS;
Like we used when creating the user, we can use the GRANT SQL statement
to grant new roles to a user. We can also use the REVOKE statement to remove
a role from the user.
SQL>
1 row created.
FIRST SECOND
---------- ------------------------------
1 Some data
SQL>
WTF? I can update a table, and I have the CONNECT role granted to my
user but I can’t write due to a quota? I thought that using the ”default” profile
would keep this sorta thing from happening!
I removed the user from the RESOURCE role, and as soon as I did I lost
the ability to create tables, even though the CONNECT role explicitely allows
CREATE TABLE... and why a quota error and not a permissions error?
....
CHAPTER 6. USERS AND PERMISSIONS 39
User altered.
Chapter 7
The Listener
The listener is the Oracle componant that (duh) listens for connections. It
allows remote connection to the database, and naturually a database that can
only be used locally isn’t very interesting. Its part of the larger Oracle Net
Services framework.
Just an FYI: In the past Oracle also used the marketing terms ”Net8” and
”SQL*Net” too. It’s the same basic thing. Some diffrences exist but very few.
See the diffrences here: http://www.orafaq.com/faqnet.htm
There are 3 diffrent interfaces to managing Oracle network configuration:
Enterprise Manager, the Oracle Net Configuration Assistant GUI (the binary
is netca), and the CLI tools: lsnrctl the Listener Control Utility and cmctl the
Oracle Connection Manager Control Utility.
At a high level you need to do two things: configure and start the listener
and then configure name resolution on the clients. Both of these are easily done
using netca or EM, but we’ll look at the plain files so you can do it without
these tools.
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 10.10.0.130)(PORT = 1521))
)
)
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
40
CHAPTER 7. THE LISTENER 41
(ORACLE_HOME = /u01/app/oracle/product/10.1.0/db_1)
(SID_NAME = test)
)
)
The first section is labeled ”LISTENER”, this is the name of the listener
itself, and can be anything you like although ”LISTENER” is the traditional
name. Then we have some nested configuration parameters, the most important
of which is the address section, which in this case specifies the listener to use
TCP, on host address 10.10.0.130 port 1521. Port 1521 is the traditional default
port, but again you can use anything you like.
The SID LIST LISTENER defines our essential parameters, namely the
SID NAME (same as $ORACLE SID) and ORACLE HOME (same as $ORA-
CLE HOME). The name ”SID LIST LISTENER” actually is derived from the
LISTENER name, so if you did actually change the listeners name to ”MYLIS-
TENER”, for instance, your second section would be ”SID LIST MYLISTENER”.
If you wanted to have multiple databases specified you could nest more
SID DESC parameters in the SID LIST. In the same way, if you wanted to
listen on diffrent IP addresses you could use multiple DESCRIPTION sections
in the DESCRIPTION LIST. For example:
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 10.10.0.130)(PORT = 1521))
)
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = 10.20.0.10)(PORT = 1522))
)
)
SID_LIST_LISTENER =
(SID_LIST =
(SID_DESC =
(ORACLE_HOME = /u01/app/oracle/product/10.1.0/db_1)
(SID_NAME = test)
)
(SID_DESC =
(ORACLE_HOME = /u01/app/oracle/product/10.1.0/db_1)
(SID_NAME = anotherdb)
)
)
For complete details on syntax, please check out the Oracle Database Net
Services Reference Guide:
http://download-west.oracle.com/docs/cd/B12037 01/network.101/b10776/toc.htm
CHAPTER 7. THE LISTENER 42
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.10.0.130)
(PORT=1521)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for Solaris: Version 10.1.0.2.0
Start Date 11-OCT-2004 15:42:55
Uptime 0 days 0 hr. 0 min. 0 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File /u01/app/oracle/product/10.1.0/db_1/network/
admin/listener.ora
Listener Log File /u01/app/oracle/product/10.1.0/db_1/network/
log/listener.log
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.10.0.130)(PORT=1521)))
Services Summary...
Service "test" has 1 instance(s).
Instance "test", status UNKNOWN, has 1 handler(s) for this service...
The command completed successfully
bash-2.05$
Don’t worry about the status being unknown. Thats normal. (Not 100%
sure why, but it is.)
CHAPTER 7. THE LISTENER 43
testdb, syslogdb =
(description =
(address_list =
(address =
(protocol = tcp)
(host = 10.10.0.130)
(port = 1521)
)
)
(connect_data =
(sid = test)
)
)
Ok, it looks alittle strange, I admit. It’s just a lot of nested statements, and
actually reminds me alot of Solaris Zones configuration.
Whats important here? First line is the name of the database, followed by
all the aliases you want. It’s important to note that you can use any name
you want! When you use a client to connect to the database it’ll look for
the name of the database you supply in the tnsnames.ora, and when it finds
that name it’ll use the information associated with it. Because the SID is
specified in the description the name is completely arbitrary. Name the database
”mysqlsbetter” if you want.
Inside the description is the important stuff, namely the ”host” which I
recommend as being the IP address unless you’ve got a good reason not too.
The port will almost always be the default Oracle Listener port 1521. In the
connect data section of the description we supply the all important SID.
You can have as many databases listed in the tnsnames.ora as you like, they
all follow the above format. But please note that the file is read completely each
time it’s accessed so if you make a syntax error on line 15, line 16 and beyond
won’t get proccessed. If something just won’t work, maybe it’s a database
description earlier in the file.
CHAPTER 7. THE LISTENER 44
For complete details on syntax, please check out the Oracle Database Net
Services Reference Guide:
http://download-west.oracle.com/docs/cd/B12037 01/network.101/b10776/toc.htm
Connected to:
Oracle Database 10g Enterprise Edition Release 10.1.0.2.0
With the Partitioning, OLAP and Data Mining options
COUNT(*)
----------
903
SQL> quit
[benr@nexus benr]$
If you had a full client installed you would need to make sure your $ORA-
CLE HOME was set before starting SQL*Plus but it’d work the same way. As
mentioned before, $HOME /.tnsnames.ora is just one of several places you can
put it. Something to be aware of is that if the client can find a sqlnet.ora, it
won’t look for the tnsnames.ora file!
For more details on net services, please check out the Oracle Database Net
Services Administrator’s Guide:
http://download-west.oracle.com/docs/cd/B12037 01/network.101/b10775/toc.htm
a more appropriate tool. When you can’t find a database via TNS it’s pretty
handy for figuring out why.
Oracle Programming
The point of a database is to store and retrieve data. These basic utilizations of
a database are essentially application specific. Your not generally gonna interact
with your database by firing up SQL*Plus every time you need to get a phone
number from your address book.
Oracle provides a wide variety of diffrent methods of interacting with the
database. There is obviously SQL*Plus for traditional SQL interaction via CLI.
We can also use PL/SQL for scripting purposes. PERL can be used via the
DBI/DBD interfaces. There is a C API called the OCI (Oracle Call Interface)
which is used by most Oracle tools. There is a C++ interface called OCCI
(Oracle C++ Call Interface). Plus there is a full compliment of Java, .Net,
OLE, blah blah blah interfaces if your into that sorta thing. Your C and C++
apps can also utilize Pro*C and Pro*C++ precompilers for embedding SQL and
PL/SQL in your code.
Lets take a look at some of the interfaces. We’ve already used SQL*Plus in
the last chapter so we’ll skip that one.
You can find documentation on these interfaces in the Oracle Documentation
Library, where you should particularly have a look at Application Developer’s
Guide - Fundamentals to get started:
http://download-west.oracle.com/docs/cd/B14117 01/nav/portal 5.htm
8.1 SQL
SQL can be ”scripted” in the purest sense of the word by simply dumping all
your SQL statements into a flat file, naming it something.sql and then running
it. There is no logic, just SQL as you’d enter it in SQL*Plus. Comments can
be added by prefixing them with ”–”.
You can execute your SQL in one of two ways, via the SQL*Plus command
line, by proceeding the filename with an and leaving off the implied .sql exten-
sion, or via SQL*Plus’s non-interactive mode, ala: sqlplus user/passwd script,
leaving off the .sql just as with the interactive form.
46
CHAPTER 8. ORACLE PROGRAMMING 47
Here’s an example:
oracle@nexus6 PLSQL$ cat sample1.sql
-- Sample of a simple sql script
-- Non-PL/SQL
CREATE TABLE test (
i int,
s char(10)
);
I S
---------- ----------
1 foobar
SQL> drop table test;
Table dropped.
8.2 PL/SQL
PL/SQL is a basic scripting language for Oracle dialect of SQL (based around
SQL99). Along with all the typical SQL-eque things you can do there is added
a helpful dose of basic logic handling and data constructs to let you do all the
normal things you’d expect. It’s very similar to ADA in its design.
A PL/SQL script contains 1 to 3 sections. At the least you need a BEGIN
section, and optionally DECLARE and EXCEPTION sections. Variables use
CHAPTER 8. ORACLE PROGRAMMING 48
-- PL/SQL Example
DECLARE
acct_balance NUMBER(11,2);
acct CONSTANT NUMBER(4) := 3;
debit_amt CONSTANT NUMBER(5,2) := 500.00;
BEGIN
SELECT bal INTO acct_balance FROM accounts
WHERE account_id = acct
FOR UPDATE OF bal;
IF acct_balance >= debit_amt THEN
UPDATE accounts SET bal = bal - debit_amt
WHERE account_id = acct;
ELSE
INSERT INTO temp VALUES
(acct, acct_balance, ’Insufficient funds’);
-- insert account, current balance, and message
END IF;
COMMIT;
END;
You can see that in the DECLARE section we initialize 3 variables, and then
in BEGIN we process some SQL using PL/SQL provided logic. PL/SQL code
is executed just like SQL statements in a file, as seen in the last section.
You’ll notice that variables are assigned values with ”:=”. In fact, if you
haven’t looked at any ADA lately, I’ll toss in an ADA example, look a little
familiar?
Put(Index, 8);
New_Line;
end OneInt;
-- Result of execution
-- The value of Index is 23
-- The value of Index is 35
PL/SQL itself is a big subject, and we won’t bother to touch it here. Damn
near everything an SA could want to do can be done in a plain ol’ SQL file.
Any SA would likely rather use PERL than PL/SQL, but there are piles and
piles of books devoted to PL/SQL out there.
Find more PL/SQL information in the PL/SQL User’s Guide and Reference:
http://download-west.oracle.com/docs/cd/B12037 01/appdev.101/b10807/toc.htm
#include <stdio.h>
#include <sqlca.h>/* SQL Communications Area */
int main(){
return(0);
}
Things of interest to note here. SQL is executed by using the ”EXEC SQL”
statement prior to the SQL command. Notice that for the SQL statement we’re
using SQL variables using the SQL VARCHAR datatype. Probly the most
tricky thing to get used to is the mixing of C and SQL variables in the same
source. C variables are refered to as ”Host Variables” in the documentation.
All SQL variables are prepended with a ”:” when deferenced.
It should be noted that you don’t need to capitolize everything, just like in
SQL*Plus, but it’s a good idea to help you keep SQL vs ”real” C code seperated
in your mind.
If your like me, your probly looking at that example code above and won-
dering whats up with ”username.len”. Well, VARCHARs are handled in a
wierd way, the Pro*C precompiler is actually replacing those statements with
structs. Each VARCHAR (and VARCHAR2) struct has two elements, arr and
len. Thus...
VARCHAR username[20];
becomes....
struct
{
unsigned short len;
unsigned char arr[20];
} username;
You’ll find several, shall we say, interesting little tidbits like this.
To run the precomipiler on your code, use the proc binary with at least 2
arguments, the input source and the output filename.
bash-2.05$ wc -l connect*.c
215 connect-pro.c
24 connect.c
239 total
bash-2.05$
Once you’ve successfuly precompiled with Pro*C you can compile your code
as usual. Make sure that you link it against the SQLLIB libraries (found in
$ORACLE HOME/precomp/).
Because of all the odd ins and outs of Pro*C, I wouldn’t recommend it as a
database management interface for common tasts, PL/SQL is much better and
easier for that sort of thing. However, if you really want to get down and dirty
Pro*C is probly an easier method than using the OCI directly... just make sure
you expect to spend more time learning and experiementing than coding.
To get the full scoop on Pro*C, read the Pro*C/C++ Programmer’s Guide:
http://download-west.oracle.com/docs/cd/B14117 01/appdev.101/a97269/toc.htm
/* .... */
$ export LD_LIBRARY_PATH=/u01/app/oracle/product/10.1.0/db_1/lib32
$ export PERL5LIB=/u01/app/oracle/product/10.1.0/db_1/perl/lib/site_\
perl/5.6.1/sun4-solaris/:/u01/app/oracle/product/10.1.0/db_1/perl/lib/5.6.1
If you do, however, forget to set LD LIBRARY PATH you’ll notice interest-
ingly that the Oracle DBD uses the OCI.
Once you’ve got things setup, you can use PERL and the DBI like you’d
expect. If your new to the DBI I’d strongly suggest picking up the excellent
book Programming the PERL DBI from O’Reilly. (Insidently, Tim Bunce who
co-wrote Programming the PERL DBI is also the author of the Oracle DBI.)
Here’s a simple example of using the PERL DBI provided with Oracle10g:
CHAPTER 8. ORACLE PROGRAMMING 53
#!/u01/app/oracle/product/10.1.0/db_1/perl/bin/perl
# Example PERL DBI/DBD Oracle Example on Oracle 10g
use DBI;
if($dbh){
print("Connected as user $user\n");
} else {
print("Failed to connect!\n");
exit;
}
$sth->execute();
#### Disconnect
if($dbh->disconnect){
print("Disconnected\n");
} else {
print("Failed to disconnect\n");
}
In the above script we’re grabbing 3 columns from the Data Dictionary’s
ALL TABLES system table. We connect, grab the rows and output them, and
then disconnect from the database when we’re done.
If you have trouble connecting to the database, remember that you need to
connect through the listener (you can connect locally, but it’s pretty figity) and
ensure that you can properly tnsping the database before freaking out about
your script.
CHAPTER 8. ORACLE PROGRAMMING 54
The output looks like this (several rows removed for clarity):
bash-2.05$ ./example.pl
Connected as user ben
All tables - Got rows:
Owner TableName NumRows
----- --------- -------
SYS DUAL 1
SYS SYSTEM_PRIVILEGE_MAP 173
SYS TABLE_PRIVILEGE_MAP 23
...
SYS PLAN_TABLE$
SYS OLAPTABLEVELS
Select Done!...Disconnected
bash-2.05$
For more information on usign the DBI please refer to CPAN and/or Pro-
gramming the PERL DBI.
http://search.cpan.org/t̃imb/DBI-1.45/DBI.pm
http://search.cpan.org/t̃imb/DBD-Oracle-1.15/Oracle.pm
Chapter 9
SQL*Loader
You might wonder, why in this guide do I want to talk about the SQL*Loader...
I mean, isn’t this an SA centric paper? Why care about DBA utilities. Well, I
discuss the programming interfaces and SQL*Loader for two reasons. First, as
an SA the DBAs are gonna bug you when they break, and we know more about
general programming and parsing techniques than the DBAs do (hopefully).
Secondly, as an SA I’m really concerned about recovering the database if the
system gets dumped/destroyed for some reason. I don’t really care about recov-
ering a table or an index, thats stuff the DBAs can handle using their normal
backups via RMAN hooked into our awsome NetBackup server. In order to look
at recovery systems in the following chapters we need to actually put data in the
databases so that we can verify we actually did recover the database properly.
Thus, PL/SQL and SQL*Loader in particular are good ways to automate some
additions to the database so we can later recover databases with some feeling
that we really got it all back. Sitting around doing SQL INSERTs all day ain’t
my idea of fun.
SQL*Loader is essentially a fatty parser. It can take delimited input data
files and parse and sort them into the tables we want them in. This is useful
for taking output data from some other system (a firewall log? apache logs?
offsite tape report?) and loading it into Oracle tables. So, basically, it is what
it sounds like.
You can interface with SQL*Loader using the sqlldr command line utility
or using PL/SQL. Obviously you first need to start by seting up a table for
the data to go. Next you’ll create a SQL*Loader control file. The control file
describes the data, how to load it and to where to put it. Then we can actually
go and run the loader on our data and put it in the database.
55
CHAPTER 9. SQL*LOADER 56
Connected to:
Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production
With the Partitioning, OLAP and Data Mining options
SQL> create table sys_log_tbl (
2 timestamp date,
3 hostname varchar2(12),
4 message varchar2(1024)
5 );
Table created.
SQL>
Ok, tables ready. Now the control file for SQL*Loader to use.
charrectors occupying charrenctors 17-21 of the input line, and finally message
is a string of charrectors that extends from the 23rd charrector out to 1024
charrectors.
There are a variety of diffrent parsing methods avalible other than using
fixed proccessing, but in this case it works well. We could tune this even more
including the use of conditionals to better parse the input but thats beyond the
scope of this book.
And now we can actually run SQL*Loader using our config file.
Now that it’s done, lets look at the table to see if it all ready went where it
was supposed to.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production
With the Partitioning, OLAP and Data Mining options
05-OCT-04 vixen
genunix: [ID 723222 kern.notice] 00000000fff63cc0 unix:sync_handler+12c
CHAPTER 9. SQL*LOADER 58
05-OCT-04 vixen
genunix: [ID 179002 kern.notice] %l0-3: 0000000000000001 0000000000000001
000000000001 00000000fff789b8
.......
This should give you some good ideas about how to quickly load data into
your database. SQL*Loader is generally found to be the fastest method avalible
for loading data into Oracle, followed closely by Data Pump imports.
For more information on SQL*Loader, please refer to Part II of the Oracle
Database Utilities guide.
http://download-west.oracle.com/docs/cd/B14117 01/server.101/b10825/toc.htm
For reference while composing parsing translations in your control files keep
a copy of the Oracle Database SQL Reference handy.
http://download-west.oracle.com/docs/cd/B14117 01/server.101/b10759/toc.htm
Chapter 10
Oracle, like other RDBMS’, has the ability to import and export databases. In
Oracle10g this system was significantly overhauled and dubbed ”Data Pump”.
More can be found about this in the Oracle Database Utilities manual.
Data Pump provides the ability to export in several modes, including Full
Export, Schema, Table, Tablespace, and Transportable Tablespace. Exports
are ”logical backups”, which means the essence of the instance is exported but
not the frame work.
As an SA, exports feel like a real ”pack your shit and go” operation. Think
of leaving an office, you don’t take the desks or drawers (tablespaces, control
files, etc), you just empty the contents into a big container (dump file) and
leave. The result of an export is a dump file. The file is binary and effectivly
just contains a pile of INSERT statements that when imported updates the
instance. Because of this you can’t import a dump without a database instance
ready to accept it, just as you can’t unpack your stuff into a new office unless
it has a desk and drawers similar to the one you just left. Therefore you can’t
really look at an export as a serious backup method. It’s a great way to cover
your ass or to move data from one place to another, but it’s not much diffrent
than just writting a PERL or PL/SQL script to output every table into a flat
file and then using SQL*Loader to CREATE and INSERT everything back into
tables. ”Recovering” a database would invole creating a new instance of the
database from scratch (using dbca for instance) and then importing into that
new instance.
With the limits of Data Pump exports understood, there are some advan-
tages to exports. Because you are importing data into an existing instance you
can easily move tables, tablespaces, schemas, etc into other databases. Further-
more, because the data is fairly generic, it provides a solid method of migrating
from one version or Oracle to another (if needbe). I’ve seen several DBAs take
exports just before applying major patches, just as a failsafe.
59
CHAPTER 10. EXPORTING DATABASES WITH DATA PUMP 60
SQL> quit
Now that the directory is ready and Oracle can write to it we can actually
do the export. There are two binaries for exports: the traditional exp export
utility and the Data Pump version expdp. Both work the same way but Data
Pump offers significantly more features and performance than the traditional
tool. (For instance, you can pause import or exports using Data Pump... hit
Control-C while it’s running and poke around. It won’t stop the operation.)
There are more options avalible than we’ll use here, but we’ll be performing
a FULL export to the specified DUMPFILE and direct logging to the noted
logfile. Notice that we write the path in the form ”directory:filename.dmp”,
where ”directory” is the Oracle reference name to the directory we setup in the
previous step.
bash-2.05$
SQL> quit
Notice that you need to create a directory refernce. It doesn’t matter what
directory or referance name you use, but if you don’t create the refence you’ll
get errors from Data Pump.
Moving onwards, lets do the actual import using the impdp command.
oracle@nexus6 DUMPS$
Ok, the import completed sucessfully. You’ll notice all the errors (6877 of
them!) due to duplication. This isn’t a problem, we could have imported with
”TABLE EXISTS ACTION=APPEND” parameter to avoid these.
Finally, lets test the import. Remember, this is a clean instance. All I’ve
done to the database is to create it with dbca, start it, create a directory reference
and done the import. I never created the user ”ben”. So, if the import worked
properly I should be able to log in as my old user (ben/passwd) can access the
”sys log tbl” table that we created in the SQL*Loader chapter.
05-OCT-04 vixen
pseudo: [ID 129642 kern.info] pseudo-device: devinfo0
05-OCT-04 vixen
genunix: [ID 936769 kern.info] devinfo0 is /pseudo/devinfo@0
SQL> quit;
Disconnected from Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - Production
With the Partitioning, OLAP and Data Mining options
oracle@nexus6 DUMPS$
And it works!
CHAPTER 10. EXPORTING DATABASES WITH DATA PUMP 64
Using RMAN
65
CHAPTER 11. USING RMAN 66
LOG_MODE
------------
NOARCHIVELOG
############################
# Archive Log Destinations -benr(10/15/04)
############################
log_archive_dest_1=’location=/u02/oradata/cuddle/archive’
log_archive_start=TRUE
Note that we’re not actually required to specify the location of the log desti-
nation, but if you don’t it’ll end up in strange places (in my test it went to $ORA-
CLE HOME/dbs making a mess). You can specify as many as 10 diffrent archive
log destinations by using the paramters log archive dest 1 through log archive dest 10.
Remember, if you run out of space in your archive log destination the database
will shut down!
Now we can startup the database in mount mode and put it in archivelog
mode.
You can see here that we put the database in ARCHIVELOG mode by
using the SQL statement ”alter database archivelog”, but Oracle won’t let us
do this unless the instance is mounted but not open. To make the change we
shutdown the instance, and then startup the instance again but this time with
the ”mount” option which will mount the instance but not open it. Then we
can enable ARCHIVELOG mode and open the database fully with the ”alter
database open” statement.
There are several system views that can provide us with information re-
guarding archives, such as:
V$LOG HISTORY Contains log history information such as which logs have
been archived and the SCN range for each archived log.
Using these tables we can verify that we are infact in ARCHIVELOG mode:
LOG_MODE
------------
ARCHIVELOG
Learn more about managing archive redo logs in the Oracle Database Ad-
ministrator’s Guide:
http://download-west.oracle.com/docs/cd/B14117 01/server.101/b10739/archredo.htm
RMAN> quit
Recovery Manager complete.
[oracle@vixen oracle]$
This is the most basic backup you can do with RMAN. We didn’t tell RMAN
how or where to backup the database, just simply to do it.
The rman command is passed 2 arguments: the first ”nocatalog” tells
RMAN that we aren’t using a recovery catalog database and the second ”target
/” is similar to a SQL*Plus connect statement, with information that RMAN
requires to connect to the target database. The target is the database we wish
to backup.
Notice that RMAN returns some interesting information prior to giving us a
prompt. It confirms that RMAN is connected to the target and lists that target.
The DBID seen after the target database SID can be very important for later
recoveries and it is recommend that you write it down somewhere for future
use. RMAN then confirms that because we aren’t using a recovery catalog to
store backup metadata that it will instead store the data in the target databases
control files.
The RMAN command backup database; sends RMAN on its merry way back-
ing up the database. Notice that we didn’t tell it where or how to backup the
data. By default the backup peices will be placed in the $ORACLE HOME/dbs
directory. This can get very messy since your system PFILES are in there too,
and therefore we recommend that you don’t use this location for your normal
backups.
Two backup peices were created. The first contains the datafiles holding the
tablespaces including the undo tablespace. The second backup peice contains
the current SPFILE and curent controlfile.
Lets stop and think carefully for just a moment. Now, we’ve opted to use
ARCHIVELOG mode which means we can do hot backups. However, we didn’t
want the hassle and administrative overhead of maintaining a recovery catalog.
So here is the rub: recall that you need a PFILE/SPFILE to start an instance
and you need the controlfile to point to all the files to be mounted. If the
database were completely destroyed we would certainly need both the SPFILE
and the Controlfile to access the backup peices made by RMAN.... but they are
inside the backup we just made! Nice little loop of confusion huh? We’ll talk
CHAPTER 11. USING RMAN 70
Okey, there is our disaster. Lets connect to RMAN and look for suitable
backups to recover.
RMAN>
CHAPTER 11. USING RMAN 71
We can see that we have good and current backups of this database avalible.
Lets now try to recover in the basic way.
RMAN>
Here, because the controlfiles and spfile are in tact, we can simply tell RMAN
to restore the missing datafile, specifying which datafile by it’s fully qualified
path (which you can also see in your ”list backup;”).
Once the datafile is restored, we can recover it to ensure it’s consistant.
Once your done, you’ll either want to bring the datafile and tablespaces
online using alter statements, or at the very least use SQL*Plus to verify that
the tablespaces are online by looking at the Oracle data dictionary.
TABLESPACE_NAME STATUS
------------------------------ ---------
SYSTEM ONLINE
UNDOTBS1 ONLINE
SYSAUX ONLINE
TEMP ONLINE
USERS ONLINE
CHAPTER 11. USING RMAN 72
In this above case the tablespace is online but we find the datafile is offline.
Lets just fix that up by using an alter statement:
We didn’t need to alter the tablespace because it was already online, but I
did it any way to demonstrate. Once you’ve successfully altered the database to
bring both the datafile and the tablespaces online you’ll want to run the queries
above again to double check.
RMAN>
Here we can see 2 backup pieces, the first contains the datafiles for the
”cuddle” database, is 441MB in side, was made to disk and took 1 minute
and 23 seconds to make. We aslo see the peices tag (notice the tag is the
same for both peices). Notice also that each datafile in the backup peice has a
Checkpoint System Change Number (Ckp SCN) associated with it (SCNs were
covered earlier). The second peice is 2MB in size, took 2 seconds to backup and
was done to disk. Notice that the second peice lists the modification time for
the SPFILE and the SCN for the Controlfile.
The list command has a number of argument that can allow you to tailor
the output to just about any way you want to see it. A nice and consice output
is seen using ”list backup summary”.
See a complete list of options to the RMAN list command in the Oracle
Database Recovery Manager Reference manual:
http://download-west.oracle.com/docs/cd/B14117 01/server.101/b10770/toc.htm
CHAPTER 11. USING RMAN 74
run {
allocate channel d1 type disk;
backup full database format ’/export/rman/rman_%n_%T_%s_%p.bus’;
}
In this run block we’re simply allocating a disk channel and preforming a
backup to the /export/rman directory using a specific naming convension for
the output backup set.
This run block can be run directly from the RMAN prompt by entering it
line by line or calling the script. However, the more appropriate way to execute
it is from a standard command line where it can be wrapped in a script and/or
controlled from cron.
Here the rman executable is called as it would normally be, but we supply
the location of an RMAN script to run with the cmdfile argument and a place
to output the logging information with the log argument.
When RMAN is executing it will output the RMAN prompts but nothing
else. This can be useful for debugging, but should probly be redirected for
cleanliness when used from a script or cron.
Comments can be put in RMAN scripts using a hash (#).
More details on command line options can synatex for run blocks can be
found in the Oracle Database Recovery Manager Reference:
http://download-west.oracle.com/docs/cd/B14117 01/server.101/b10770/
CHAPTER 11. USING RMAN 75
RMAN> quit
Recovery Manager complete.
[oracle@vixen oracle]$
Ok, the instance is started and we can now preform the first part of our
recovery. If you recall from earlier discussions you need the PFILE or SPFILE
in order to properly start and instance, and we need the database controlfile
in order to access the RMAN backup information it contains because we’re not
using a recovery catalog. Since both the SPFILE and controlfile are inside the
backup set we’ll need to use the PL/SQL RMAN interface to specifically point
RMAN in the right direction.
Here is the PL/SQL you’ll need to use (restore foundation.sql ):
DECLARE
v_dev varchar2(50); -- device type allocated for restore
v_done boolean; -- has the controlfile been fully extracted yet
type t_fileTable is table of varchar2(255)
index by binary_integer;
v_fileTable t_fileTable; -- Stores the backuppiece names
v_maxPieces number:=1; -- Number of backuppieces in backupset
BEGIN
-- Initialise the filetable & number of backup pieces in the backupset
-- This section of code MUST be edited to reflect the customer’s available
-- backupset before the procedure is compiled and run. In this example, the
-- backupset consists of 4 pieces:
v_fileTable(1):=’/export/rman/rman_TESTINGx_20041108_4_1.bus’;
v_fileTable(2):=’/export/rman/rman_TESTINGx_20041108_3_1.bus’;
v_maxPieces:=2;
v_dev:=sys.dbms_backup_restore.deviceAllocate(type=>null, ident=>’d1’);
<<all_done>>
-- Deallocate the device
sys.dbms_backup_restore.deviceDeallocate;
END;
/
The parts of this code you’ll need to edit are the array elements of the
v fileTable array including the number of v maxPieces as the number of ele-
ments. Then the deviceAllocate() function tells RMAN we’re using disk instead
of tape. But the most important lines are the restoreControlfileTo() and re-
storespfileto() functions. The arguments supplied to both will indicate where
RMAN should put the controlfile and SPFILE.
Run this PL/SQL code by putting it in a file named restore foundation.sql
and execute it like this (it’ll ask for a value, just enter 1, this doesn’t mean
anything):
Connected to:
Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Production
With the Partitioning, OLAP and Data Mining options
CHAPTER 11. USING RMAN 78
SQL> quit
Disconnected from Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - 64bit Producti
With the Partitioning, OLAP and Data Mining options
[oracle@vixen RMAN]$ cd /u02/oradata/testing
[oracle@vixen testing]$ ls -l
total 5618
-rw-r----- 1 oracle oinstall 2867200 Nov 9 15:19 control01.ctl
-rw-r--r-- 1 oracle oinstall 857 Nov 9 15:19 spfile
[oracle@vixen testing]$
Now we have the neccisary files to start an instance to restore from prop-
erly. cat the spfile to deterime what paths need to be created for proper startup,
namely the dump directories. Once the directories are created you should du-
plicate the controlfile so that there are the typical 3 copies. And finally, you
must create a password file for the instance. Moving the spfile into $ORA-
CLE HOME/dbs isn’t neccisary, but a good idea.
Now we’ve got the meat of our instance ready to be utilized for a real restora-
tion of the datafiles. If the instance is currently started, shut it down (shutdown
abort;) and restart the instance using the proper SPFILE. The database will be
started in mount mode which will start the instance and read the controlfile(s)
but not actually open the datafiles.
RMAN>
If everything has gone well so far, you can now list the backups avalible and
restore the database.
RMAN>
RMAN> restore database;
CHAPTER 11. USING RMAN 80
RMAN>
RMAN>
With the restoration and recovery complete all the datafiles will be in the
proper place. You can now shutdown the current instance and startup the
database properly. Once the database is mounted you’ll need to reset the logs
to open the database.
database dismounted
Oracle instance shut down
RMAN> quit
Recovery Manager complete.
[oracle@vixen testing]$ echo $ORACLE_SID
testing
[oracle@vixen testing]$ sqlplus / as sysdba
SQL*Plus: Release 10.1.0.2.0 - Production on Tue Nov 9 15:31:45 2004
Copyright (c) 1982, 2004, Oracle. All rights reserved.
SQL> quit
And your done! You can test our your database by querring a couple ta-
bles and connecting as various diffrent users. If you don’t want to be bugged
with specifying the pfile during startup you’ll just need to symlink the spfile to
$ORACLE HOME/dbs/init(SID).ora.
After the database is back up, you’ll want to ensure that you either restore
from filesystem backups or recreate the listener configuration.
Please note that the PL/SQL interface we used above is undocumented and
Oracle will not assist you in using it. It also (supposedly) changes between
releases. Unfortunetly, this is the only way. The only documentation that even
mentions it is avalible only if you have a MetaLink account, in DocID 60545.1.
Chapter 12
Loose Ends
This chapter contains information that I don’t think fits anywhere else in this
book but that I none-the-less would like to cover. More information on all of
these topics can be found at Oracle.com.
82
CHAPTER 12. LOOSE ENDS 83
reclaim space immediately when you drop an object, however you can forcably
purge objects from the recyle bin using the ”PURGE” SQL statement.
The componants needed for Flashback have actually been in database for
awhile to facilitate OLTP. All OLTP changes need to be atomic (discussed later)
so when a transaction is modifying the database and for some reason fails (or in
dba speak ”throws an exception”) the transactions that were uncommited are
rolled back. Rollback Segments, now called undo segments, provided the nec-
cisary historical information to allow for this. All this is leveraged, repackaged
and dubbed ”Flashback”.
Before you get started playing with flashback, there is one little catch you
need to be aware of: it doesn’t work on the system tablespaces. This means
that if you connect to Oracle as sys (who uses the system tablespace by default)
and create a table, drop it, and then try to flashback it, it will fail. Flashback
works great on the non-system tablespace, but if you blow away a system table
your going to take more extreme measures, not just flashback restore it.
The easiest way to enable flashback is to enable it during database creation
with dbca. And, as usual, Enterprise Manager makes everything a snap. We’ll
discuss it’s setup here in case you want to enable it on existing databases using
the SQL*Plus interface.
In order to utilize Flashback you’ll need to put your database in ARCHIVELOG
mode. Then you can set the DB FLASHBACK RETENTION TARGET pa-
rameter that defines the period of time which we want to retain flashback logs,
and finally turn Flashback on with an ALTER DATABASE statement. Lets
look at the setup.
Okey, Flashback is now enabled for this database. We’ve defined a flasback
retension of 4320 minutes (or 72 hours), a recovery file size of 512MB and defined
the location for the file recovery area (FRA) as /u02/fra.
Lets see Flashback in action now. You can look at the contents of the recyle
bin by querying select DBA RECYCLEBIN the table.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - Production
With the Partitioning, OLAP and Data Mining options
Table created.
1 Ben Rockwood
2 Tamarah Rockwood
3 Nova Rockwood
4 Hunter Rockwood
Flashback complete.
ID NAME
---------- ------------------------------
1 Ben Rockwood
2 Tamarah Rockwood
3 Nova Rockwood
4 Hunter Rockwood
SQL>
For more information about Flashback check out the book Oracle Database
10g High Availability with RAC, Flashback and Dataguard and the Oracle Database
Backup and Recovery Advanced User’s Guide manual:
http://download-west.oracle.com/docs/cd/B14117 01/server.101/b10734/rcmflash.htm
12.3 OLTP
Databases tend to get split up into a variety of diffrent catagoies based on
their application and requirements. All of these diffrent catagories naturally get
nifty buzz words to help classify them and make distinctions in features more
apparent. The most popular buzz work (well, acronymn anyway) is OLTP or
Online Transaction Proccessing. Other classifications include Descision Support
Systems (DSS), Data Warehouses, Data Marts, etc.
OLTP databases, as the name implies, handle real time transactions which
inherently have some special requirements. If your running a store, for instance,
you need to ensure that as people order products they are properly and effiently
updating the inventory tables while they are updating the purchases tables,
while their updating the customer tables, so on and so forth. OLTP databases
must be atomic in nature (an entire transaction either succeeds or fails, there
is no middle ground), be consistant (each transaction leaves the affected data
in a consistant and correct state), be isolated (no transaction affects the states
of other transactions), and be durable (changes resulting from commited trans-
actions are persistant). All of this can be a fairly tall order but is essential to
running a successful OLTP database.
Because OLTP databases tend to be the real front line warriors, as far as
databases go, they need to be extremely robust and scalable to meet needs as
they grow. Whereas an undersized DSS database might force you to go to lunch
early an undersized OLTP database will cost you customers. No body is going
to order books from an online book store if the OLTP database can’t update
their shopping cart in less than 15 seconds.
The OLTP feature you tend to hear most often is ”row level locking”, in
which a given record in a table can be locked from updates by any other proccess
untill the transaction on that record is complete. This is akin to mutex locks
in POSIX threading. In fact OLTP shares a number of the same problems
programmers do in concurrent programming. Just as you’ll find anywhere,
when you’ve got a bunch of diffrent persons or proccesses all grabbing for the
same thing at the same time (or at least the potential for that to occur) your
going to run into problems and raw performance (getting your hands in and out
as quick as possible) is generally one of the solutions.
Several other factors come into place with OLTP databases, and the Ora-
cle10g documentation library even has a whole section dedicated just to OLTP.
Find more information in the Oracle10g docs:
http://www.oracle.com/pls/db10g/portal.portal demo3?selected=18
RAC Real Application Clusters, formerly Oracle Parallel Server (OPS). Allows
for cluster databases.
OLAP Online Analytical Processing, ”provides valuable insight into business
operations and markets”
CHAPTER 12. LOOSE ENDS 89
All of these features (and more) are included in Oracle Enterprise Edition,
with the exception of RAC (and RAC extensions) which are Options. RAC is,
however, present in the Standard Edition of Oracle. The basic breakdown of
Oracle editions is:
Lite Edition Complete software for building, deploying, and managing mobile
database applications.
Personal Edition Full-featured version for individuals, compatible with the
entire Oracle Database family. The features of Personal are identical to
the Enterprise Edition.
All of these prices are for perpetual licenses, meaning they are good forever.
Oracle doesn’t say CPU, they say ”proccessor”, but CPu is more fitting because
it doesn’t matter if you use 8 single CPU systems or 1 8-way system, it’s the same
cost. Because of this distiction the idea of running on small X86 systems using
RAC isn’t as attractive because you can get more work out of Sun UltraSparcIV
or IBM POWER5 than you can out of small proccessor and therefore reducing
the true total cost of your Oracle enviroment.
Obviously, the prefered way to buy Oracle is based on named users and to
simply reduce the number of named users you create. Named users are defined
by Oracle as:
I called Oracle to clarify this and I was told that they consider a ”named
user” as any person (physical human) or resource (automated proccess) that
touches the database. An in this way (so they say) you can no buy named users
for a database that will be used with a webserver because each visitor to the
site is a ”user” of the database, even if you only have 5 webservers that actually
talk directly to the database.
In addition, when buying per user, you must adhear to Oracle set ”User
Minimums”. For instance, when purchasing Oracle Database Enterprise Edition
the Named User Plus Minimum is 25 Named Users per Proccessor. So if you
plan to install Oracle EE on an 8 way system you need to buy 200 named users,
at $800 per user bringing your total cost to $160,000!
Now, on the plus side, Standard Edition has a minimum of 5 named users
and it’s not per processors, but the edition is limited to 4 proccessors. So you
could buy Oracle Standard Edition with 5 named users for $1,500 and use it on
either a 4 way box, or because RAC is included, in a 4 node RAC configuration.
CHAPTER 12. LOOSE ENDS 91
Also, Oracle can sell you CD Packs, if you don’t want to download all the
media. The packs tend to cost less than $100. You can actually buy printed
manauls, but they are $75 per manual.
To tie it all together, lets assume you were going to buy Oracle Enterprise
Edition for your Sun V1280 with 12 CPUs. Thats gonna run $40,000 per CPU
bringing the software cost to $480,000, 22% of that for 1 year of support trans-
lating to $105,600 (per year), $100 for the media kit, and $25 for a Polo Shirt
making the grand total cost $585,725. Consider that the V1280 with 12 USIII
CPUs at 1.2Ghz and 24Gb of memory only costs you $139,995.00.
If you’ve gotten this far in the book you are probly aware of two things: 1)
SQL*Plus sucks, and 2) Enterprise Manager makes everything easy. Rs an SA
I tend to avoid Enterprise Manager simply because I don’t want to allow myself
to become dependant on it. You never know when you’ll need to work on a
system that doesn’t use EM, and I don’t want to be lost because I don’t have
my precious EM. However, if you’ve used it you know that it makes Oracle feel
really simple and managable. On the other side of things, SQL*Plus can give
you a migrane due to it’s shear stupidity. When you consider the two of them,
it’s hard to imagine that Oracle could put so much effort into EM but not add
something as simple as Readline support into SQL*Plus. But then again, it
seems like the Korn Shell is the prefrence of most DBA’s so they just might not
know any better.
There are two Open Source tools that will make the hurt go away and make
Oracle a heck of alot easier to manage, explore and interface with: TOra and
YaSQL.
13.1 YaSQL
SQL*Plus sucks. You can’t really debate the point, it just does. Especially
for those of us who have been spoiled with BASH and ZSH’s nifty completion
and history editing features it’s almost unbearable to be stuck in the confines
of SQL*Plus. But thanks to some thrifty coders the madness can end by using
YaSQL.
YaSQL is Yet Another SQL*Plus replacement. It’s a GPL app written in
PERL by Jon Nangle and Nathan Shafer and is copyright Ephibian, Inc.
So what is SQL*Plus really missing? History editing is probly the big one.
After typing out a long query and then screwing up a line you don’t want to cut
and paste the whole damned thing back in. PostgreSQL like listing would be
kool too to quickly see a list of all tables, indexes, etc. Better output formatting
is a must, since SQL*Plus table output is essentially unreadable. And how
92
CHAPTER 13. TOOLS TO LESSEN THE PAIN 93
about bounding! When I look at a big table (or one that i think might be big)
it would be nice to only see the first 10 lines, or last 10 lines, or whatever instead
of the whole thing, especially when you just want to see acouple rows to craft a
better query. Well, good news! YaSQL does all this and more!
Here’s an example that’ll sell you instantly.
COUNT(*)
--------
24
In this example you can first see a standard SQL statement that counts the
rows of the all users table and finds 24 rows. In the next statement I query
for all rows, but append a ”5” after semicolon telling YaSQL to only show me
the first 5 rows of output. Then I use the ”show” YaSQL command to list
all the avalible tables to me (remember my rant about not having this ability
like PostgreSQL?). And in the last two statements I run a select but redirect
output to a file and then use ”!” to run a system command to read it from
within YaSQL.
Thats just a taste of the power of YaSQL. This is a professional grade in-
terface that is easy to use, flexable, and won’t leave you wondering why DBAs
seem to enjoy needless suffering. It’s anything but ”Yet Another”.
Grab a copy and make sure to mail the authors and tell them how much
you value it. There are lots of SQL*Plus replacements, but trust me: look no
further.
You can download YaSQL from its SourceForge project page:
http://sourceforge.net/projects/yasql/
13.2 TOra
TOra was written by Henrik Johnson and is now owned by Quest Software. It’s
an open source tool that is avalible on SourceForge. UNIX versions are avaliable
at no cost, but the Windows version requires a license beyond 30 days (although
not inforced). It’s written in C++ and based on Qt.
CHAPTER 13. TOOLS TO LESSEN THE PAIN 95
Oracle Proccesses
Oracle is a big beast, to say the least. It’s composed of a variety of diffrent
componants. Each database is run as an instance. A database server can run
multiple instances at a time. Each instance is made up of diffrent componants.
We can see these as seperate procceses at the system level.
All these procceses make up the instance of the database BEN running on
this machine. Lets break it down.
pmon The process monitor performs process recovery when a user process fails.
PMON is responsible for cleaning up the cache and freeing resources that
the process was using. PMON also checks on the dispatcher processes
(described later in this table) and server processes and restarts them if
they have failed.
96
APPENDIX A. ORACLE PROCCESSES 97
cjq0 Job queue processes are used for batch processing. The CJQ0 process
dynamically spawns job queue slave processes (J000...J999) to run the
jobs.
d000 Dispatchers are optional background processes, present only when the
shared server configuration is used.
s000 Dunno.
qmnc A queue monitor process which monitors the message queues. Used by
Oracle Streams Advanced Queuing.
APPENDIX A. ORACLE PROCCESSES 98