hora – a tutorial for dba`s
Transcription
hora – a tutorial for dba`s
© KeepTool GmbH 2005 4 INTRODUCTION INTRODUCTION The idea for this Guide came from a series of discussions focusing on our desire to make the KeepTool software a more useful and more convenient offering to the Oracle community. Many of our users have asked us for a quick introduction to the software in a portable format. This book hopes to provide that overview of KeepTool. We have designed the three chapters entitled A Quick Tour so that each one could be read and understood in a few minutes, even by someone who might not have a computer at hand. Through these chapters, we hope that we can give someone with no prior knowledge of Hora, PL/SQL Debugger, or ER Diagrammer a feeling for what our products do. Our basic premise, which we have always come back to when introducing our products to the public, is that they are easy to use, even for people who haven’t had time to read the online Help or this manual. However, we hope that browsing through the Guide and trying the examples will make you feel even more comfortable when trying them out. If you’re a new KeepTool user, we’d like to hear whether you have benefited from the Guide. What’s even more important – we’d like to hear what we might be able to do better in a future version. We have created a new KeepTool Forum, entitled Getting Started Guide, where you’ll be able to read the opinions of other users and add your own. Or, if you wish, just email [email protected]. We look forward to hearing from you. At the same time, we thought that the best way to understand software is to actually use it. Accordingly, you’ll find several chapters with Tutorial in their name. These build on the Quick Tours and take you into new areas. As of the present writing (April, 2005), only the tutorials entitled Hora – a Tutorial for Developers and Hora – A Tutorial for DBA’s have been completed. The tutorials for PL/SQL Debugger and ER Diagrammer are still under development, and will be available in a future version of the Guide. Dr. Jan Dieckmann Rolf Grünewald Holger Heidenbluth Managing Directors April, 2005 5 CONTENTS CONTENTS Introduction 5 Contents 7 How to Use This Guide Introductory tours Supplementary Chapters Tutorials 9 9 9 9 Installing KeepTool Downloading the trial version Which product to install? Downloading via HTTP or FTP Installing from the CD-ROM Using the InstallShield Wizard Licensing options The single workstation license The floating license Off-site usage feature Registering your KeepTool products Registering a single workstation license Registering a floating network license Significance of the Hora_User role Installing KeepTool updates 10 10 11 11 12 12 14 14 14 15 15 16 16 17 18 KeepTool Help and Support The Online Help file Obtaining technical support from KeepTool Support form Email Frequently Asked Questions KeepTool Forums 19 19 Hora – A Quick Tour First steps Connect dialog 23 23 23 20 20 21 21 21 Navigation system SQL Workbench The Tables Page Tabbing beyond the Overview Using the context menu to navigate and make changes Some Features of Interest to DBA’s Navigation and the Sessions Page Finding out more about a session Drill-down example The Data Dictionary and the HORA_USER role. Summing up 24 24 25 26 26 27 27 28 28 29 30 PL/SQL Debugger – A Quick Tour Introducing FIND_DAY_OF_WEEK Hora’s Interface Starting debugging Screen highlights 31 31 32 33 33 ER Diagrammer – A Quick Tour Generating the default diagram Creating a subset What the symbols mean Modifying layout options Printing and saving the diagram Summing up 35 35 36 37 38 38 39 Hora – A Tutorial for Application Developers The Connect dialog Navigation features Tables Page Creating a table Inserting a row into the table Creating a sequence Creating a trigger Exploring the Data Contents window Commit and Rollback 41 41 43 43 43 44 46 47 48 49 Packages Page Creating the package SQL Workbench The File Explorer The SQL Repository The Query Builder The Data Contents Browser Tools Bundled with Hora SQL Editor File Menu Query menu Search Menu Reverse DDL Engineer HTML Documentation Generator Available options Batch invocation 49 49 52 53 54 55 58 63 63 65 65 67 67 68 69 70 Hora – A Tutorial for DBA’s Data Dictionary Tablespaces Page Increasing the size of a datafile Shrinking a tablespace Moving segments to another tablespace Database Page NLS Parameters Initialization parameters Creating a new role Creating a new profile Creating a user Granting system privileges and object privileges to a user Dropping a user Dropping objects, but not the user SGA page Other pages 71 72 73 74 74 75 76 77 77 79 80 80 81 82 82 83 84 7 8 HOW TO USE HOW TO USE HOW TO USE THIS GUIDE Welcome to our new publication, Getting Started With KeepTool. It has been designed as both a printed (hardcopy) publication and as a PDF file that you can read online. In either form, you can read through it with or without a computer at hand, but we recommend that you keep a computer ready if you can do so, since that may help to make the examples more clear. Introductory tours The publication includes a quick overview of all three principal products: Hora, PL/SQL Debugger, and ER Diagrammer – all entitled A Quick Tour. These can probably be read in a few minutes each. Supplementary Chapters You’ll also find a few supplementary chapters like this one. For example, if you’ve just removed this document from the box and haven’t yet installed the software, you should take a look at the chapter entitled Installing KeepTool. u Hora: A Tutorial for Application Developers (This includes the bundled tools: SQL Editor, Reverse DDL Engineer and HTML Documentation Generator.) u Hora: A Tutorial for DBA’s u PL/SQL Debugger: A Tutorial (currently under development) u ER Diagrammer: A Tutorial (currently under development) You’ll find each of these written in such a way that you can look at the database, create new objects in it, and make a few changes – all in a logical progression. The tutorial chapters are intended for you to follow with a computer at hand. However, if you should find yourself without one – for example, if you’re commuting to work, we’ve tried to include sufficient illustrations to let you understand the examples and to get a feel for what will happen when you actually try them out. If you don’t have the necessary privileges to try something – or would just rather not – you should also be able to follow along. Tutorials The most important information in this publication is contained in four Tutorial chapters. At the current time, only the first two of these are available. The tutorials for PL/SQL Debugger and ER Diagrammer will be released at a later date, and will be available on the KeepTool website. 9 INSTALLATION INSTALLING KEEPTOOL Currently, KeepTool products are available both by download from www.keeptool.com, and on a CD. As of 2005, the CD is also available as a boxed version that also includes a printed copy of this Guide. The CD contains the following items: u the executable setup program u the KeepTool help file in CHM format (same as the Windows help file embedded in the products themselves) u a PDF version of the Getting Started Guide u video presentations of the major features of the three products u a setup file for Acrobat Reader Through one of our promotional efforts, including attendance at an Oracle event, you may have received a copy of our CD that will also install the trial version. Since we update the downloadable version of KeepTool, on the average, every three to four weeks, and produce only a few CD’s each year, there is a good chance that the downloadable trial version will contain newer features than those on the CD. But if you don’t currently have Internet access, or are just trying to get a “feel” for the product, and it doesn’t matter to you if you have every last feature, then you might want to install the software from the CD. Once you have obtained a license, you will be able to download new versions as they are released, approximately once a month. Downloading the trial version Even if you purchase KeepTool’s boxed version, we recommend that you first download the 30-day free trial version of our products. 10 Therefore, it’s clearly advisable to have some kind of Internet access available. INSTALLATION ! Which product to install? Downloading via HTTP or FTP By default, the setup program installs all three major products. Even if you don’t think you are interested in all three of them, you may still want to install the others in case you later change your mind. You can delete them at any time. A given setup file will contain the most recent version of Hora, PL/SQL Debugger, and ER Diagrammer. By installing the trial version, you will be able to use each of them for 30 days, with their complete functionality. There is no additional functionality that is enabled by licensing KeepTool. Licensing permanently removes the expiration date – you can then use the product for as long as you like. As long as you do not upgrade your Oracle server version, any KeepTool product will keep working – and chances are, it will continue to work with future versions of the server – although this is cannot be guaranteed. You will find a link to our download area on the KeepTool home page, under the support menu. At any given time, the link will automatically download the latest edition of the setup file, which will include the latest version of each of our software products. The name of the file will be KeepTool6.n.exe, where the “n” represents a digit, 6.2 as of this writing. You will see the actual 4-place version number, such as “6.2.4.35” on the left side of the web page, as in the following illustration. ! Once you click the link, you may see a security warning like the following one, produced by a popular browser. @ @ 11 INSTALLATION You will also have the option of downloading from our FTP site, ftp://ftp.keeptool.com. Here, you will again have the ability to download our current release, which always has a name such as KeepTool6.n.exe. You will also be able to download other older releases, and sometimes, a newer release that may still be undergoing Beta testing. Of course, we make no claim that any Beta version will suit your needs. Generally, Beta versions are made available for customers who have reported problems, or who have asked for enhancements, so that they can evaluate a proposed solution. For example, in screenshot §, where the list of setup files has been sorted by date, you can see both an older release and a Beta version on either side of KeepTool6.2.exe. Once you have downloaded the file, double-click on it in Windows Explorer to start the setup process. § 12 $ Installing from the CD-ROM $ If you choose to install from the CD-ROM instead of downloading the setup program, you should see the above dialog, assuming that you have the Autorun feature enabled. (If not, just start Windows Explorer, right-click the CD-ROM icon, then autorun.exe on the context menu.) Click the first option button, Install KeepTool 6. Using the InstallShield Wizard Regardless of whether you install KeepTool from the downloaded file or the CD-ROM, the remainder of the procedure is the same. KeepTool uses the standard InstallShield Wizard that you may already be familiar with from installing various other Windows products. You will see a series of dialog boxes similar to the one below that ask you to make a series of choices. % % INSTALLATION Among these choices are: u Whether you accept the license agreement, which you can read by scrolling in a window. The Next button is disabled until you accept the agreement. u Your name, and your company’s name, if any – also, if you have more than one user defined for your computer, you are asked if KeepTool should be made available only for you, or for all users. u Where the software should be installed. By default, this location is C:\Program Files\KeepTool\KeepTool 6\ in the English-language version of Windows. A Change button is made available if you do not want to accept the default. u The type of setup: Typical, Minimal or Custom. This will further refine the decision that you made earlier about which products to install. If you are installing the trial version for the first time, we recommend the Typical setup. & & If you asked for a Custom setup instead, the following screenshot shows some of the choices that would be available for each installed product. / u A confirmation window, which asks if you are ready to go ahead with the installation. If you want to modify some of your choices, this will give you another chance to use the Back button to modify them. The installation program will then do the following: u Copy all KeepTool files to the destination directory u Create KeepTool start menu icons u Enable Microsoft HTML help on your system (if you already have the most recent version, a message to this effect will be displayed.) u Upgrade the Microsoft Common Control library (comctl32.dll) to version 5.0, if necessary. If the installation was successful, you will be asked to click the Finish button. / 13 INSTALLATION Licensing options KeepTool makes available individual user licenses (single licenses) and licenses for use within a network (floating licenses). Each KeepTool product (Hora, ER Diagrammer, Debugger) is licensed separately. The price of either type of license is the same. The single workstation license: The single workstation license is linked directly to the hardware. A hardware code required for registration is specifically defined for a single personal computer and is displayed when registering the program. This kind of licensing lends itself to the following situations: u the client software and the database server reside on the same computer u the client software is used to access a remote computer, which is not on a Windows network, but can be accessed through TCP/IP. 14 u only one license is purchased (the network licensing option is not available for only one license) The floating license: KeepTool’s floating license option is designed to maximize our customers’ return on investment. A floating license can be used concurrently by two or more users on the same network. Licensing is tied to the network, rather than to an individual computer. The licensing information is stored on a single computer in the network that has been designated to hold the licensing file. A licensed program can be used simultaneously on as many computers as provided by the license. There is no limit to the number of machines on which the software is installed and registered – only on the number of concurrent users. INSTALLATION Off-site usage feature With each floating license, KeepTool offers the ability to remove a computer from the network and use it off-site for up to 30 days. This feature is particularly beneficial for staff who sometimes work both in the office and at home, or those who work off-site some of the time. As soon as the off-site computer is reconnected to its “home” network, it is again counted as one of the users of a floating license. It can then again be removed from the network for up to 30 days from the time at which it was reconnected. The process can be repeated indefinitely. In effect, it means that a license can serve as many off-site users as on-site users – effectively doubling the value of each license. shown automatically. The following illustration explains the three options: Register, Try it for Free, and Decline. ( You will then be asked to choose between two licensing options: the floating network license and the fixed single workstation license. In the example below, you’ll see an explanation of the floating license option. ) If you press the Single workstation button, you will see the following explanation instead: Registering your KeepTool products The registration dialog can be started from the Help Menu of Hora, ER Diagrammer, or PL/SQL Debugger. In certain cases, such as when your trial period has expired, it is ( ) 15 INSTALLATION Registering a single workstation license: Registering a floating network license: Registration a single-user license is a two-part process. Registration of a network license also involves generating a unique code, the network code, and entering a license key provided by KeepTool. u Prior to starting KeepTool’s registration dialog, you must first choose a location for the network folder where the licensing file will be installed. Each KeepTool user must have read/write access to this folder, because it is used to track the number of current users. A UNC address (beginning with "\\") must be assigned to this network location. u Next, start the registration dialog and enter the UNC address that you have selected in the first dialog window shown below. BM The first step is to have the software generate a hardware code based on the properties of the PC. Please send this to KeepTool (or your reseller), either in the Remarks field of our online order form (when ordering) or later by email to [email protected]. You will then receive a registration key, normally within two working days. (In the meantime, you can press the Back button to go on using the trial version.) u Next, complete the registration dialog by entering the registration key in the lower text box. The software will then be permanently unlocked. BL When you click the Register Network button, you will then see the next dialog, which displays the generated network code. BN BL 16 BM INSTALLATION Please send the network code to KeepTool (or your reseller), either in the Remarks field of our online order form (when ordering) or later by email to [email protected]. You will then receive a registration key, normally within two working days. (In the meantime, you can press the Back button to go on using the trial version.) u When you receive the key, log on to one of the computers where the KeepTool software is installed, and complete the registration dialog by entering the key in the lower box. The software will then be permanently unlocked on this computer. u For all other computers that will be using the network license, you need only enter the UNC of the folder that was selected to hold the licensing file. At that point, the software will automatically be registered for that machine, and you will no longer see the registration dialog. BN Significance of the Hora_User role You may have noticed that the button labeled “DBA” on the Sidebar is disabled for certain users. These users will receive the following warning the first time that they try to log on (and every subsequent time, if they don’t select the check box at the lower left). BO This limitation was built into Hora to allow administrators a convenient way either to allow or prevent users from viewing certain information about the database – most of which comes from the DBA_ data dictionary views. The HoraUser.sql script, located in the folder in which KeepTool was installed, defines the HORA_USER role and grants it to SYSTEM. The script can be modified to grant HORA_USER to other users at the same time; the role can also be granted later on, on a user-by-user basis. If a user has been granted either the HORA_USER role or the SELECT ANY DICTIONARY system privilege, Hora can query the data dictionary to determine whether a trans- BO 17 INSTALLATION action has just been completed. At these times, the Commit and Rollback buttons, located at the top left of all of Hora’s pages, are disabled. They are automatically re-enabled when a new transaction begins. On the other hand, if a user does not have either HORA_USER or SELECT ANY DICTIONARY, the buttons are always enabled. This means that a COMMIT or ROLLBACK statement can be generated at any time – even at times when there is no work to be committed or rolled back, and the command would have no practical effect. Installing KeepTool updates KeepTool releases a new installable setup file approximately every one or two months, for each new minor release. New features that have been added to release can be found on the KeepTool website, under the Products menu, at 18 http://www.keeptool.com/en/releasenotes.php. You may want to take a look at this page from time to time to see if these features are important to you. As a license holder, you are entitled to all updates within a major version, such as KeepTool 6. To update, you will need to first remove the current version using Windows’ Control Panel, then download the new setup file, and double-click it to execute it. When the InstallShield Wizard finishes, you will be ready to use the new version. You will automatically be recognized as a registered user. SUPPORT KEEPTOOL HELP AND SUPPORT KeepTool’s customer support system has several different aspects. To begin with, there is this Guide, which is intended to smooth the way for you to install the product(s) and take your first steps with them. u u The Online Help file Our Online Help is packaged with the products, and is implemented with Macromedia RoboHelp. In practice, it is a standard Windows help file. In All of our tools, the Help menu will bring up the familiar Context, Index and Search tabs. The Table of Contents consists of several high-level books, which you can expand. Some expand into other books, and others directly into topics. All second-level books then expand into topics: u Getting Started u Hora 1 Hora’s Work Environment 1 The “Standard” Page u u u u u 1 The “Additional” Page 1 The “DBA” Page Modal Dialogs ER Diagrammer 1 Graphical Representation 1 Working With ER Diagrammer PL/SQL Debugger SQL Editor HTML Documentation Generator Reverse DDL Engineer Contacting KeepTool Once you drill down to a topic in the online help, you will also find browse sequences that lead you forward to the next topic, or back to the previous topic, so that you don’t have to go back to the Contents. You’ll also find Back and Forward buttons to retrace your steps or follow them again – just as in a web browser. 19 SUPPORT The online help is not only available through the three tabs mentioned above – there is also context-sensitive help available by pressing the F1 key from most windows. The help file is also available on our website, so that you may also access it from a computer that doesn’t have any of the products installed. We recommend that you fill in the online form on the KeepTool website for most support requests. You’ll find it through the Support menu, or directly at http://www.keeptool.com/en/support.php (English), or http://www.keeptool.com/de/support.php (German), or http://www.keeptool.com/fr/support.php (French). The WebHelp is available through the Support menu on www.keeptool.com, and it opens in a popup window. If you’d like to browse it as a standard browser window, just enter www.keeptool.com/webhelp/AboutKeepTool.htm. The form will urge you to attach your System Environment. When you are running a KeepTool product, the Help menu will let you capture information about both your PC and your Oracle server, which you can copy to the clipboard, then paste into the support form. Obtaining technical support from KeepTool When you submit the Support Form, it will automatically generate an email that will be forwarded to the staff members who can address your inquiry. Technical support is included with your purchase of a license for a KeepTool product. 20 Support form: SUPPORT Our policy is to respond to all support requests within two business days of receipt. This won’t always be a definitive answer – but we will tell you what we already know, and if necessary, ask you more questions and dig deeper into your problem when the answer is not immediately apparent. A KeepTool staff member will normally respond to your request by email. We may also call you in those situations where it is more efficient, or when you ask us to call you. Email: Although we recommend that you use the Support Form, we will also accept your emails sent to [email protected]. For example, if you simply have a question about something that you have read in the help file, just send us an email. Frequently Asked Questions: In our Online Help, you will find a Frequently Asked Questions. Your question might be a common one, and you might find the answer there. The WebHelp version of this topic is available at www.keeptool.com/webhelp/FAQ.htm. KeepTool Forums: In 2003, we introduced our online discussion groups, the KeepTool Forums. There is one forum for each of our principal products, Hora, PL/SQL Debugger, and ER Diagrammer. Although anyone can read the postings in the Forums, participation requires registration. This is simply a matter of giving us a valid email address. Neither your email address of any other information that you give us is made public unless you allow us to. 21 SUPPORT If you have a question (or a complaint) about one of our products that isn’t keeping you from getting work done, you might want to let other users here about it by posting it in the Forums. This is advantageous to KeepTool, because other users may also have found and solved the problem – but if we know that several users are also experiencing the problem, or related problems, it helps us to pinpoint both the underlying cause and a possible solution. It is also our hope that users who find themselves discussing the same topic in the Forums will also network with each other in the future. For example, you may find that another KeepTool user is located not far away from you, and that you would both benefit from an “off-line” discussion about KeepTool – or something entirely unrelated. 22 A QUICK TOUR HORA – A QUICK TOUR First steps Let’s look at some of the features of Hora that would be of interest to both application developers and DBA’s. Please keep in mind that this material is also covered in much greater detail in our Tutorial chapters. Connect dialog Hora will ask you how you want to log on. You will need to enter an Oracle user, password, and connect string. Since Hora uses the Oracle Call Interface (OCI) to access the database, it will search for the file oci.dll within your Oracle Home. Usually, if you have only one Oracle Home, you’ll be all set at this point, because Hora will know how to find it. Otherwise, you may need to take some additional steps (see below). During the first part of this tour, we will use the SCOTT schema to illustrate several essential points. In the example below, you’ll see that we have chosen to log on as SCOTT with the connect string db10g. This entry has been stored from a previous logon. In the optional Session ! Tag String field, we have entered TEST*** 10g to remind us that we are working with a test database. (If you have left the password for SCOTT as the Oracle-supplied default TIGER, you will need to type in TIGER at this point.) ! Hora can also connect to an Oracle server through direct TCP/IP. This method does not require the Oracle client software – something you might want to keep in mind if you are at someone else’s PC, and you’d like to use Hora to show someone something. In that case, you can just download our trial version from http://www.keeptool.com/en/download.php, and be ready to access the database in a couple of minutes. Let’s go back and pick the first entry from the Recent Connections list, and see what happens. @ Take a look at the third box from the top, which formerly held the connect string "db10g." Here we’ve referenced the TCP/IP address of a machine, the listener’s port number and the service identifier used in the listener.ora file. @ 23 A QUICK TOUR Navigation system After successfully logging on as SCOTT, you’ll soon find yourself looking at a screen like this one. (Only the upper left corner is shown, because most of the screen will be empty.) Notice how the Session Tag String appears on the title bar and on the taskbar. §Initial Appearance of the SQL Repository Along the left side of your screen, you will see the Sidebar, the heart of Hora’s navigation system. It consists of four large rectangular buttons – Standard, Additional, DBA and Favorites, each of which contains several different icons. The first time that you log on, you will see the Favorites collection of icons, with the SQL icon selected by default. You can customize Hora to open up to any of several other windows instead of the SQL Workbench. What’s more, you can customize the Favorites collection to include any icons that you might want to choose from the other three groups. § 24 $ We’ll take a quick look at the SQL Workbench before moving on to the Tables page. SQL Workbench SQL Workbench lets you create, store and organize files containing SQL commands or PL/SQL blocks. When you first start Hora, SQL Workbench will contain a navigation window with SQL Repository and File Explorer, and a larger code window. The SQL Repository will show two nodes, Personal SQL and Team SQL, and the code window will be empty. The SQL Repository is designed to let you store SQL files logically by adding, changing, and removing items in a tree structure, each of which corresponds to a Windows file. By default, Personal SQL equates to a folder with that name underneath your My Documents folder (or the equivalent folder in other editions of Windows). Try typing “SELECT * FROM EMP” in the code window, then pressing the Execute Query button on the toolbar. Execute A QUICK TOUR Query presents results in a grid window, which can be further used in various ways. $ The File Explorer lets you navigate to any SQL file through an interface that is similar to Windows Explorer. You’ll find this handy, if for example, you want to execute a SQL file that already exists, such as one provided by Oracle or KeepTool. The example below shows that the user has navigated to the file C:\Program Files\KeepTool\KeepTool 6\HoraUser.sql – a script that will be discussed later in connection with Hora’s DBA collection. Many times, you will want to execute only a portion of the code, perhaps some commands that failed because an object was not found. In that case, you can just select the code that you want and press the Execute Script button on the toolbar. % % We’re not suggesting that SCOTT should execute this code, by the way. It’s a further illustration of the fact that code stored in the file system is accessible to any user who is logged on to the database. The Tables Page In the Favorites collection as it initially appears by default, you will also see the Tables icon Clicking it will take you to the Tables page. Here you’ll see an overview of SCOTT’s four tables: BONUS, DEPT, EMP and SALGRADE. & The Comments column may be wider on your screen. You can drag the borders of columns to manipulate their width. The date and time formats are based on your settings in Windows Control Panel. If you’re looking at a schema with a long list of tables, the 26 alphabetic buttons down the left side (shown above) will let you scroll the overview to that location in the alphabet. & 25 A QUICK TOUR Notice the tabs at the bottom. chever table was selected from the Overview. /Bottom Tabs Showing "Tables" Selected and Schema Selector Box By default, only SCOTT’s tables are shown. You could alternatively show SCOTT’s views or synonyms, or his most recently viewed objects. At the extreme bottom left of the screen is a schema selector box. This lets the user who has logged on see another user’s objects in the database – to the extent that his privileges allow. By default, the connected user’s schema is shown. Using the context menu to navigate and make changes Most of Hora’s grids offer a context menu that can be opened by clicking with the right mouse button. A context menu is available from almost all of Hora’s grids. As you navigate from one grid to the next, the toolbar with its buttons also changes. In general, the same options are available from the toolbar as from the context menu. (The Context Menu (right) and Toolbar (top) Tabbing beyond the Overview You’ll see the Overview Tables tab sheet highlighted in orange in Windows XP. Regardless of the which Windows version you are using, the active tab will always appear in front of the others. Clicking on the EMP table’s row in the Overview, then on the Data Contents tab, will show you the contents of the EMP table. Likewise, clicking on any of the other tabs at the top will show you other kinds of information about whi- / 26 ( Hora uses the same grids for both viewing and altering the database. Some of the context menu items help display information from the database – in this example: Next – and others allow changes to be made, for example, Insert. To make changes, you have all the privileges of the user whose credentials you used to log on. The concept of the Overview and drill-down tabs extends to almost all of Hora’s pages. A QUICK TOUR Some Features of Interest to DBA's Even if you’re not a DBA, the following pages will give you some more insight into the way Hora works. If you’d like to follow along, you’ll need a logon that has the SELECT ANY DICTIONARY privilege or HORA_USER role. (For a discussion of HORA_USER, see the Data Dictionary topic below.) Navigation and the Sessions Page Next, we’ll take a look at another one of Hora’s pages that looks the current state of your database, the Sessions page. To get there from the Tables page, click the DBA button on the Sidebar, and then the Sessions icon. This is about all there is to know about Hora’s navigation system. Since the Sessions page was probably not the one that you set as your startup page, please take a look at the Windows menu. Hora keeps all of its pages open until you close them. You can use the Windows menu to toggle, tile, or cascade windows. The toolbar will change according to which window ) has the focus. This can be seen quite dramatically when switching between Tables and Sessions! )Cascading Windows As you enter each new page, the Overview tab will be selected by default. BLOverview Sessions, Showing SID 146 Waiting for a Lock For Sessions, the Overview presents some basic information that is taken from the V$SESSION dynamic view. Chances are that if you’ve just logged on, you will see your Hora session as the highest-numbered AUD SID – in the example above, AUD SID 2019. If you click on it, the latest SQL executed by your session will appear in the lower-right portion of the window. For example, if you’ve just come to the Sessions page and selected your own session, in the bottom window you’ll see the code that produced the grid at the top. This illustrates how, on many of Hora’s pages, the contents of one grid will often be linked to a row that you have previously selected in another grid. BL 27 A QUICK TOUR Finding out more about a session As we saw earlier with the Tables > Data Contents sheet, a context menu is available by right-clicking on most of Hora’s grids. On Overview Sessions, you’ll see Kill Session as both a context menu and toolbar item. The Kill Session dialog will automatically be applied to the currently selected session – in the example below, it’s SID 146, which appears in red because it is waiting for a lock. Pressing the Kill Session button will first bring up a confirmation dialog. You’ll see one of these anytime that you are about to make a serious change to the database. BM Next, if SQL Preview is in effect, you will see the SQL that you are about to execute – giving you a chance to modify it, accept it, or reject it. SQL Preview is one of Hora’s key options: when activated, it will show any SQL statement that will alter the database. In this example below, the confirmation dialog has already BM 28 BN been dismissed, and the SQL Preview dialog is waiting for input: BNSQL Preview for Kill Session, Showing Active SQL for SID 146 Here, you can see that SID 146 has an UPDATE pending, and that SCOTT’s SID 150 is holding a lock. At this time, the DBA could choose to go ahead and kill SID 146, modify any of the code in the window, or choose not to execute it. Drill-down example Next to the Overview Sessions tabs, you will see other tabs that give you the opportunity to drill down to other sessionrelated data. For example, the Lock Wait Graph tab will show the following display for either of the two sessions involved with the lock. In this case, SID 146 is waiting for SID 150 to commit an update to the same row. BO By default, a portion of the Overview grid always remains displayed in the window at the left. The size of this view can be adjusted according to your preference. A QUICK TOUR The Data Dictionary and the HORA_USER role. You will find the functions that are of major interest to DBA’s concentrated on the DBA Sidebar. Within these pages are graphical interfaces for such things as taking tablespaces offline or dropping users, to cite just two examples with potentially even more impact than killing a session. Most Oracle shops are extremely cautious about granting the DBA role to users who don’t need it. Hora has therefore developed the HORA_USER role as a compromise. A user with this role has the ability to view not only the data dictionary, but all the grids on the DBA pages, which are constructed from data dictionary views – but not to make changes to objects other than his own. Let’s take another look at the special window that is displayed when someone first logs on as a non-privileged user. BP BO Hora unlocks the DBA Sidebar button only for users who have either the HORA_USER or SELECT ANY DICTIONARY privilege. The KeepTool install package ships with the HoraUser.sql script, which creates the HORA_USER role, which in turn consists mostly of SELECT privileges on Data Dictionary views. Installation of KeepTool only makes the script available. You can view the script, and modify it before executing it. For example, you may wish to uncomment the GRANT HORA_USER TO PUBLIC statement at the end of the script, and specify the grantees. Hora’s Data Dictionary page shows the contents of each data dictionary view, plus comments on each view and its columns. BP 29 A QUICK TOUR Summing up In the following example, we see the contents of USER_ALL_TABLES. If we decide to view only rows where NUM_ROWS is 1 or more, we can make use of a filter dialog to do so. BQ This particular view has 50 columns. In cases like this, once a row of interest has been found, you can click the Record View tab at the right, and view all of one row’s data. BR We have taken a very quick look at only a few of Hora’s facilities. The overview was intended primarily to explain the navigation system, sample some typical grids, and show how they can be used to make changes to the database. Please follow along with the Tutorial for Application Developers and the Tutorial for DBA’s, in both of which we will ask you to create some objects and some code, as well. However, you should be able to go ahead and try something that you are really interested in at this point. Please make sure that SQL Preview is in effect, though. It can be toggled on or off with the Extras menu. Secondly, please keep in mind that pressing F1 from any page will invoke the relevant online Help file. Help is also available through the Help menu on Hora’s main menu. Pressing the Table View tab at the right will take us back to the grid. BQ 30 BR DEBUGGER PL/SQL DEBUGGER – A QUICK TOUR KeepTool’s PL/SQL Debugger can be used to debug procedures, functions, packages and triggers, as long as they have been compiled with the DEBUG option, which allows the Debugger to access variables in memory. you use the wrong format, it will let you know, so that you can try again. Here is the source code (it can also be downloaded from ftp://ftp.keeptool.com/ktguide/find_day.sql): The Debugger relies on Oracle’s DBMS_DEBUG package, which can be installed from the pbload.sql script located in the ORACLE_HOME\RDBMS\Admin folder. /* Procedure FIND_DAY_OF_WEEK takes a character date expression as input, and displays the day of the week. It also displays the current value of NLS_DATE_FORMAT, in case the input format was To use the package with the 10g database, the user must also have been granted the DEBUG CONNECT SESSION privilege. incorrect. */ CREATE OR REPLACE PROCEDURE FIND_DAY_OF_WEEK( P_IN_DATE_STRING IN VARCHAR2, Introducing FIND_DAY_OF_WEEK To give a quick overview of the Debugger’s functionality, we will use the following procedure, which returns the day of the week for a given date. It expects you to supply the date in the format specified by NLS_DATE_FORMAT. However, if P_OUT_DAY OUT VARCHAR2, P_OUT_FORMAT OUT VARCHAR2) AS L_IN_DATE DATE; X_BAD_FORMAT EXCEPTION; 31 DEBUGGER -- Error ORA-01861 is "Date does not match format string" P_OUT_DAY := TO_CHAR(L_IN_DATE, ‘Day’); FINISH_UP; PRAGMA EXCEPTION_INIT (X_BAD_FORMAT, -01861); EXCEPTION -- Nested procedure: WHEN X_BAD_FORMAT THEN PROCEDURE FINISH_UP IS BEGIN BEGIN DBMS_OUTPUT.PUT_LINE (‘Input date ‘ || P_IN_DATE_STRING DBMS_OUTPUT.PUT_LINE(‘Current date format is: ‘ || || ‘ is invalid.’); P_OUT_FORMAT); P_OUT_DAY := ‘INVALID’; DBMS_OUTPUT.PUT_LINE(P_IN_DATE_STRING || ‘ IS A ‘ || P_OUT_FORMAT := ‘INVALID’; P_OUT_DAY); FINISH_UP; END; END; END; BEGIN SELECT VALUE INTO P_OUT_FORMAT FROM NLS_SESSION_PARAMETERS / WHERE PARAMETER = ‘NLS_DATE_FORMAT’; Hora’s Interface L_IN_DATE := TO_DATE(P_IN_DATE_STRING); Before debugging, we’ll use the Compile Debug menu item on Overview Packages. ! ! 32 @ § DEBUGGER The following SQL would accomplish the same thing: Starting debugging ALTER PROCEDURE OW.FIND_DAY_OF_WEEK COMPILE DEBUG After connecting to the database, we use Ctrl+A and Ctrl+V to replace the dummy code with the calling block from the clipboard: §Debugger window after inserting the calling block To debug stored PL/SQL, you need to supply a calling statement. Hora’s Packages page can generate this for you automatically. You just need to select the object, and click the Call Interface tab. @Calling block generated by Hora Hora generates assignment statements for input parameters, a calling statement, and DBMS_OUTPUT statements for output parameters. Be sure to replace NULL with a valid date string. In this example, we’ll replace it with ‘01-May-05’ and copy the code window to the clipboard using Ctrl+A and Ctrl+C. Then we’ll invoke PL/SQL Debugger from Hora’s Tools menu. $ Screen highlights The first button on Debugger’s Toolbar, Step into, lets us step through both the calling block and the procedure one line at a time. The window looks like this when we enter the procedure: $Debugger window after entering the procedure The Call Stack window shows us that we have entered the procedure at line 1, after leaving the anonymous block at line 12. The current line is always shown in green. We can use the context menu (right-click) for the Watch List window to set a watch for the variable L_IN_DATE. By % 33 DEBUGGER clicking line 43 (the END statement) and right-clicking, a breakpoint can be set there. The window now looks like this. breakpoint on line 43. %After setting a variable watch and a breakpoint At this point, we could single-step out of the procedure, and the displays at the end of the calling block would be generated. (Debugging completed Notice the red dot on line 43 of the code. Clicking the Step into button again will cause execution to be resumed, and the code window to be scrolled back to the top. We might now single-step through to line 31, and to decide to add a watch for P_OUT_DAY, an output parameter, as well. (By this time, L_IN_DATE has been populated.) &Getting ready to add an output parameter to the watch list Pressing OK at this point will show that the value of P_OUT_DAY is currently “Sunday.” Pressing the Run button on the Toolbar (a right-facing triangle) at this point will cause execution to halt at the & 34 / /Arrival at the breakpoint Once you see Debugging completed appear on the status bar, that is a signal that the Debugger is ready to run through the code again. At this time, you could change the input parameter. Once you reach the procedure, you can keep the same watches and breakpoints from last time, or set new ones. It is also possible to modify the value of variables to force the code down different paths. This and other Debugger features will be discussed in an upcoming chapter of this Guide to be entitled PL/SQL Debugger: A Tutorial. ( ER DIAGRAMMER ER DIAGRAMMER – A QUICK TOUR KeepTool’s ER Diagrammer reads the Data Dictionary for entries relating to tables, indexes, primary keys and foreign keys for a given schema, and generates an entity/relationship diagram showing the relationships between tables. More often than not, you’ll be starting the application be either logging on to the database and scanning a schema, although it is also possible to start by opening a saved diagram. ! The OW schema was developed by KeepTool for internal testing purposes. You can download a script to install the current version of it from ftp://ftp.keeptool.com/ow.sql. The user logging on can choose to view his own schema or another schema, and can specify a string denoting standalone tables that should not be included. Generating the default diagram The appearance of the diagram that is automatically generated will depend somewhat on layout options that were previously selected, but the following is a typical example. Here, we’ve logged on as user OW. @A typical default diagram ! @ 35 ER DIAGRAMMER Creating a subset The above picture was taken from a maximized window at 1024x768 resolution. Even though this makes the writing hard to read, there are still a few things worth mentioning about it: u Colors are used to group related tables. u Tables are positioned in such a way that tables referenced by a foreign key are always to the left or their dependent tables. u Foreign key names occupy the lines between tables. u Standalone tables are at the right of the diagram, and are shown in white. § 36 Even after the initial diagram is displayed, the standalone tables can still be excluded, as can the three tables at the top of the diagram that were created by the DBMS_PROFILER package. We will create a subset of the OW schema called OW_BUSINESS that will exclude these non-businessrelated tables by choosing Subset > New Subset from the menu. We are then able to specify the tables that will go into the subset. §Subset Definition dialog after all tables have been moved to the subset In the dialog, we have already moved all the Available Tables from the box at the left to the list of Tables in Subset at right by pressing the Select all button at the left, then Include Selection. The next step will be to click the unwanted tables: EMPLOYEE1, ENTITY_MV and the three PLSQL_ tables and press Exclude Selection, then OK. ER DIAGRAMMER The result is a slightly more readable diagram, which can then be zoomed to an even more comfortable level. $Subset before increasing zoom percentage to 80% What the symbols mean Once the OW Business subset zoom factor has been increased to 80%, we can take a look at how different types of relationships are depicted. % This illustration shows how ER Diagrammer has incorporated some of the terminology of the IDEF1X (information at http://www.idef.com/IDEF1X.html) standard: u Independent tables have square corners; dependent tables have rounded corners and a black dot at the right end of each foreign-key line. u Required columns have asterisks, nullable columns have circles. u Primary keys are shown above the line in each table. $ u A foreign key going to a diamond symbol in its master table shows that the relationship is optional, since it comes from a nullable column or columns of the child table; a foreign key going directly to the master table indicates a mandatory relationship. u A dashed line indicates a non-identifying relationship, where the foreign key column or columns are outside the child table’s primary key; a dotted line indicates an identifying relationship (such as the one between INVOICEITEM and INVOICE, where the INVOICE column is part of INVOICEITEM’s primary key, as well as being the foreign key to the INVOICE table). u A red line shows that the child table row will be deleted with its parent table row – in other words, all INVOICEITEMs will be deleted with their associated INVOICE. Also, a COMPONENT_PRICE table row will be deleted when either of its parents is deleted. You may also notice that we’ve dragged some of the tables % 37 ER DIAGRAMMER The Diagram tab allows you to turn on or off a background grid that makes it easier to move shapes to a new location. up or down to make some of the foreign-key names more legible. ER Diagammer lets you reposition a table anywhere you want in the diagram. Printing and saving the diagram Modifying layout options There are many more options available for customizing the appearance of the diagram. You can find them on the Extras menu, under Options, where the following dialog becomes available. & Most of these are fairly self-explanatory. The column at the left gives you various options for squeezing the diagram into a smaller space or expanding it to fill a page. Eliminating foreign-key names is another way of making the diagram more compact. The column type bitmap is a small image preceding the column name that identifies the datatype. & 38 / The File menu offers several options for putting the diagram to use, once it has been customized. / One of these is the Print dialog, which in addition to the usual Portrait and Landscape options, allows the diagram to be printed over several pages. (Printing over multiple pages The File > Save menu item allows for only one file type: DGR, which is the Diagrammer’s internal format. A DGR file can be opened by ER Diagrammer at the next startup. This is useful if you have begun customizing the layout, and would like to finish later. ER DIAGRAMMER Another option on the File menu is Copy to clipboard. You will find this useful for sharing the diagram with people who don’t have ER Diagrammer. As the clip shows, you could easily paste the diagram into any Windows application that accepts Clipboard data. For example, you could paste it into a word-processing document or save it in a graphics application. )A practical use for the Copy to Clipboard function Summing up ER Diagrammer provides an immediate and automatic method of understanding or documenting a database – one schema at a time. In this respect, it is similar to KeepTool’s HTML Documentation Generator product, which is discussed in Hora: A Quick Tour, elsewhere in this Guide. ( ) 39 40 TUTORIAL FOR DEVELOPERS In this chapter, you will have the opportunity to try out some of Hora’s developer-oriented facilities for yourself. Before you start out, you will need a user name and password that you can log on to. In the following examples, we have used the user KTGUIDE to illustrate some of the things that we’ll ask you to do. You’ll also need the RESOURCE role, or the CREATE SESSION, CREATE TABLE, CREATE SEQUENCE, CREATE TRIGGER and CREATE PROCEDURE privileges to try out all the examples. TUTORIAL FOR DEVELOPERS HORA – A TUTORIAL FOR APPLICATION DEVELOPERS If later you’d also like to try out the tutorial for DBA’s, you will also need the HORA_USER role or the SELECT ANY DICTIONARY privilege in order to view many of the graphic displays. The Hora installation folder on your PC includes a script that creates the HORA_USER role. It allows the grantee to view most of the Data Dictionary. Even if you’re not working in a DBA capacity now, becoming familiar with the database infrastructure, even in a test environment, is useful. Now, let’s connect to the database. The Connect dialog For a few of the examples, your schema will need to be able to SELECT rows from the SCOTT schema. If you don’t have the SCOTT schema available in your database, you can probably find it in your Oracle Home’s \rdbms\admin folder as scott.sql. You can also find a copy on KeepTool’s FTP server at ftp://ftp.keeptool.com/ktguide/scott.sql. ! You will probably need only a user name, password and net service name to connect to the database. If you get an error message such as ORA-012154 TNS: could not resolve the connect identifier specified click the Advanced button and make sure that Hora has found the correct oci.dll file. If you have more than one ! 41 TUTORIAL FOR DEVELOPERS Oracle Home, you can browse to the correct oci.dll and try logging on again. In the directory above the one containing the oci.dll file, there should also be a network/admin/tnsnames.ora file that contains the database name. Besides using the Oracle client’s oci.dll file, Hora also lets you bypass the client software and connect to the database using a direct TCP/IP connection. The Connect dialog shown below shows an example, where the host machine is called "toshiba-user." We could also have used its TCP/IP address instead of its name. The TCP/IP connection option supports almost all of Hora’s functionality @ The new SessionTagString field lets you enter an optional string that will appear in Hora’s title bar to make it easier to distinguish several sessions, or test and production databases. Try it by entering TUTORIAL here. @ 42 If, after using Hora for a while, you have logged in to various user accounts, or with various net service names, you may accumulate a list such as the one shown above. In that case, you can simply choose a connection from the list. To facilitate work in development databases where security is not a concern, Hora supplies a default password that is usually the same as the user name. For the users SYS and SYSTEM, the password defaults to the defaults supplied by Oracle. The first time that you use Hora, you will see the SQL Workbench page. This is a default setting. If you would like to change it, you need only go to Extras > Settings on the menu, and select the Startup Window box, where you’ll see a dropdown list and you can choose another page. §Choosing the startup window § TUTORIAL FOR DEVELOPERS Navigation features Let’s talk about some of the standard navigation features that you see on the Tables page, starting with the Sidebar on the left. Hora points you to various areas of the database through the icons on the Sidebar. Use the Tables icon now to go to your Tables page. If you had logged on as SCOTT, your Tables overview would look something like the picture below. But if you have just logged on for the first time to your own schema, you won’t see any tables listed. $ Click the Standard button, then a few of the other icons on it, and you’ll see other overviews that are designed to be very similar to Tables overview. However, the SQL page is totally different, as we’ll see in a little while. If you don’t have the HORA_USER role or the SELECT ANY DICTIONARY privilege, the DBA button will be disabled. $ % Next, right-click on the Sidebar to bring up the Customize menu, which lets you select the pre-installed icons that you use most often and group them together as your Favorites. Here you’ll see that the active check boxes represent the current contents of the Favorites collection. By default, these are the SQL and Tables pages when you start Hora for the first time. %Choosing favorites Now, let’s return to the Tables page. Tables Page Creating a table Let’s start at the beginning—by creating a table in our schema using Hora’s graphic interface. First make sure that you have the SQL Preview option on. When you click on Extras on the menu, make sure that SQL Preview has a check mark next to it. If it doesn’t, just click it. & & 43 TUTORIAL FOR DEVELOPERS On the Tables page, right-click on the Overview grid, then select the Create item. The dialog window shown below then appears. Name the table EMPLOYEE. By accepting the defaults, you will be creating a column named ID that will be the primary key column for the table. / Press the Append column button, and enter COMPANY_ID as the name of the second column. Tab to the right, type N…, and press Enter to accept the datatype of NUMBER. Continue by entering the following additional columns and datatypes. Fill in column comments if you like: u FIRSTNAME varchar2(30) u LASTNAME varchar2(30) not null u GENDER char(1) u EMAIL varchar2(30) u PHONE char(10) u EXTENSION char(5) u REMARKS varchar2(1000) / 44 ( Next, press the Add stamps button. Four additional columns are added that you can use to keep track of inserts and updates to the table. ( Press OK to end the table definition. Because you have activated SQL Preview, you will see the CREATE TABLE statement displayed. ) Click Yes in the SQL Preview window, and you will then have an opportunity to modify any column COMMENT statements that you may have entered, or that were automatically generated for you by the dialog as a result of Add Stamps. Inserting a row into the table Let’s start out by inserting some data into the table manually. It’s important to know whether changes to a table will be automatically committed or not. From Hora’s main menu, select Extras > Settings, then the Data Contents tab. ) TUTORIAL FOR DEVELOPERS Clear the Auto Commit box, if it’s checked. This means that any changes that you make in the grid will not be automatically committed – until you issue the COMMIT statement, or log off your session normally. If, at any time, you have Auto Commit off, and wish to back out your changes, you must issue a ROLLBACK. In this way, you always have the capability of undoing a change, with the benefit of seeing the database as it appears after a change. Next, make sure that EMPLOYEE is highlighted, and click the Data Contents tab on the Tables page. You’ll see an empty grid representing the table’s current contents. In the first row of the grid, fill in values of your choice for the columns that you just created (but not for the extra columns added by the Add stamps option). Please be sure to enter a number into the ID column, as it has been defined as the table’s primary key. Also, please remember that COMPANY_ID, if entered, needs to be a number. Keeping your eye on the orange Post Changes and Cancel buttons on the toolbar, click your cursor in the second row’s ID column, as if you were getting ready to add a second row. The two buttons become gray, showing that they have become deactivated. This demonstrates that navigating to a new row in the Data Contents grid automatically posts pending changes to the database. It’s the same as if you had just coded and executed a SQL INSERT statement for the first row. If you hadn’t moved the cursor out of the first row, you could have manually posted the INSERT by clicking the Post Changes button. (This is not the same as committing a change. We’ll talk more about that later.) At this point, you could manually insert a second row. Instead, click on the ID value that you entered in the first row, then on the red Insert Copy button . Another row will 45 TUTORIAL FOR DEVELOPERS be added to the grid, and the Post and Cancel buttons will again be activated. Note that an asterisk appears on the first line, indicating that it is the inserted row. If you are creating test data, you can now make whatever changes you like to the data in the new row. You might see something like this. In any case, you’ll need to click OK to clear the error message; then either click Cancel to back out the new row or manually give it a new ID value. Then press the Post button again. BLDuplicating a row Creating a sequence However, if you were to try to post the new row, you would see the following result. BM Creating a sequence to automatically generate a new key will show you more about how Hora works. Hora displays the corresponding Oracle error message, giving you the option to look it up. Press the Columns tab, then right-click and select Create Sequence. Choose a starting value that is greater than either of the ones that you have just entered manually. Otherwise, accept all the default values to create the sequence. Notice that it is called EMPLOYEE_SEQ. BN Even though you have created a sequence with the ID column highlighted, there is so far nothing in particular that links the sequence to the ID column or anything else. We’ll If you have an account with the Oracle Technology Network (OTN), you can then click Lookup Oracle Documentation and be taken directly to the error message in OTN’s online HTML documentation. If not, you might want to consider opening an account, which is free. BL 46 BM BN TUTORIAL FOR DEVELOPERS do something about that shortly. The sequence could also have been created, using the same dialog that you see above, by clicking on the Overview Sequences grid of the Sequences page. So far, you’ve seen a little of the Overview, Data Contents, and Columns tabs. Click now on the Indexes and Constraints tabs to see the information that is available there because you accepted the default choice to create a primary key along with the table. Then click the Triggers tab. Notice the defaults: Hora assumes that you want to create a BEFORE INSERT FOR EACH ROW trigger to be called EMPLOYEE_BIR. Since that is exactly what you want to do, click OK. If you’ve followed our suggestion to turn on SQL Preview, you’ll see the following skeleton code. BP If you click Yes, you’ll see the trigger added to the list with a status of VALID, and its skeleton code in the code window. Now, in the code window, replace the NULL; line with the following code: -- Use the sequence to generate a new value. SELECT EMPLOYEE_SEQ.NEXTVAL INTO :NEW.ID FROM DUAL; SELECT USER INTO :NEW.INSERTED_BY FROM DUAL; BO Creating a trigger SELECT SYSDATE INTO :NEW.INSERTED_AT FROM DUAL; Now that you’ve created a sequence, you’ll want to use it. Place your cursor on the empty grid of the Triggers tab, right-click, and select Create. (Please make sure that SQL Preview is on first). BO Press F9 to execute CREATE OR REPLACE TRIGGER with the newly added code. BP 47 TUTORIAL FOR DEVELOPERS If you’ve typed everything correctly, you’ll see the updated code, with the status remaining as VALID in the upper grid. If you’ve made an error, you may now correct it in the Triggers code window. Even if you haven’t made an error, right-click on the code window, and you will see CREATE OR REPLACE on the context menu, with the Toolbar button or F9 presented as alternatives. Recompiling the corrected code is as easy as pressing the button or the F9 key. Exploring the Data Contents window Now that you have successfully created the trigger to use the sequence, you should try entering another new row in Data Contents. Add a new, unique value of your choice for the ID. When you press the Post button, you’ll see the effect of the trigger’s execution: the next value from the sequence is used to override the value that you supplied – and the INSERTED_AT and INSERTED_BY columns will be filled in. To see the new table rows, you will need to click on the Data 48 Contents tab in order to refresh it. The Data Contents tab offers many special features. They are covered in detail in our online Help file for Tables > Data Contents. For now, try: u Clicking on the REMARKS column in the grid. You’ll see a button with an ellipsis. Click the ellipsis and you’ll see an expanded entry field where you can enter 1000 characters if you wish. u Click on a date. A down arrow will appear where you can visualize the date on a calendar page – and on which you can also update the date. u Click on the Text View button at the right to see an entire row at once. Click the button with rounded corners at the upper left of the grid . Try dragging a column name or clearing check boxes in the dialog that opens up. u Drag a column heading from the right to the left side of the grid. u Vary the width of a column in the display by dragging it. TUTORIAL FOR DEVELOPERS Commit and Rollback These two buttons appear in orange at the top of every one of Hora’s windows. If you have followed along with the suggested steps up to now, you may wish to click the Commit button to ensure that any inserts, updates, and deletes that you made are committed. They would normally be committed when you log off, but not if your session ends abnormally (as is the case also in SQL*Plus). Creating the package Again, please make sure that you have SQL Preview turned on. This can be done via the Extras menu item. You’ll find the Packages icon in the Standard collection of the Sidebar. Navigation between Hora’s pages is also possible without using the Sidebar. To see how, use the View menu to select Standard, then Packages. The Packages page is also used to view and manage standalone functions and procedures. Packages Page You will now create a package called EMPLOYEE_PKG in your schema to perform various operations on the EMPLOYEE table. The package will include the procedure GET_SCOTT that will read all rows in the EMP table of SCOTT and merge its EMPNO and ENAME columns into your EMPLOYEE table. Notice the four tabs at the bottom of the Overview grid. These will determine which objects are listed. Packages is selected by default when you enter the page. As a standard feature, most of Hora’s Overview grids have a Create button, featuring a plus sign, as the first button on the toolbar. Try pressing this button now. 49 TUTORIAL FOR DEVELOPERS Type EMPLOYEE_PKG as the name. CREATE OR REPLACE PACKAGE EMPLOYEE_PKG AS At this point, SQL Preview allows you the choice of creating an empty package and modifying it later, or entering the code while you create the package for the first time. For now, just click the Yes button to create the package. BQ END; Now, click the Package Body bottom tab, and create the package body in a similar manner. You now have a valid package and package body (that don’t do very much). Now, you’ll add the real code by clicking on the Source Code tab. You can edit the code in the Source Code window as follows. This will let you follow along with some more examples: Now, here is the package body: PROCEDURE GET_SCOTT; / Next, press F9 to compile the package specification. CREATE OR REPLACE PACKAGE BODY EMPLOYEE_PKG AS /* This procedure uses the merge statement to insert rows from SCOTT’s EMP table, using the EMPNO column as the ID for the Inserted row. Only the EMPNO and ENAME data will be used from SCOTT for ID First, here is the complete code that you need package. Note that if you don’t want to, or can’t copy and paste the source code, you will also find this code on the KeepTool FTP site at ftp://ftp.keeptool.com/ktguide/employee_sql. BQ 50 And LASTNAME. If the key already exists, LASTNAME will be updated from SCOTT’S ENAME. */ TUTORIAL FOR DEVELOPERS Please take a moment to see what the code does before proceeding. The comments should be adequate for this. Each time that Hora refreshes the code from the database, it is prefixed with a CREATE OR REPLACE statement and terminated with a forward slash. This allows you to save the code, including the CREATE OR REPLACE, as a file for storage outside of the database and later execute it. PROCEDURE GET_SCOTT IS BEGIN MERGE INTO EMPLOYEE E2 USING (SELECT EMPNO, ENAME FROM SCOTT.EMP) E1 ON (E2.ID = E1.EMPNO) WHEN MATCHED THEN UPDATE SET E2.LASTNAME = E1.ENAME WHEN NOT MATCHED THEN INSERT (E2.ID, E2.LASTNAME) To illustrate how this works, once you’ve gotten the code compiled correctly, right-click in the code window, select File…, then Save As…, create a new folder called KeepTool Guide, and save the package and package body as EMPLOYEE_PKG.PKS and EMPLOYEE_PKG.PKB, respectively. We’ll try one more thing before revisiting these files in Hora’s SQL Workbench: actually executing the GET_SCOTT procedure: With either the Package or Package Body bottom tab in effect on the Overview – click the Call Interface tab. You will see the following code generated for you. BR VALUES (E1.EMPNO, E1.ENAME); COMMIT; END; END; / Press F9 to compile the package body. If you find that you’ve made a mistake, use the error message and line number to find and correct it; then press F9 again. BR 51 TUTORIAL FOR DEVELOPERS 52 If there were more than one procedure or function in the package, you could use the top grid to select the one for which to generate the call interface. Hora generates a calling block based on the parameters (and the RETURNS clause in the case of a function). An assignment statement is created for each input parameter, and a DBMS_OUTPUT for each output parameter. Here, these are not needed, but you can see from the comments where they would be generated. Save the calling block as a file under the name GET_SCOTT.SQL. Test your procedure now by doing one of the following: u Selecting Query > Execute Query from the context menu u Clicking the Execute Query button on the toolbar u Using the keyboard shortcut Ctrl+E. Hopefully, you have arranged for access to SCOTT’s table, and you have copied and compiled the code correctly. If you have the DBMS_OUTPUT window activated on the View menu, it will open with the displays from the trigger that you created. SQL Workbench Now, you can move back to the Tables page to view the results of your merge by selecting Tables from the Windows menu, or by clicking on its icon in the Sidebar, then clicking the Data Contents tab. The SQL Workbench differs fundamentally from the rest of Hora’s page. Its navigation system consists of the SQL Repository and the File Explorer. Both of these are used in conjunction with the code window at the upper right, plus the SQL Results and DBMS_OUTPUT windows, which appear when needed. TUTORIAL FOR DEVELOPERS The File Explorer You could also further modify the package, recompile it or execute it from the code window. Click the File Explorer tab now. Use it to open the KeepTool Guide folder that you created for the package in the above section. When you click on a folder in the upper part of the File Explorer window, you will see all the files with extensions belonging to a customizable list. These include standard file extensions used by Oracle Designer for creation scripts, such as .pkb .pks, fnc. and .prc; and also .sql. The complete list may be found (and modified) from the Extras > Settings menu item, by clicking the SQL Page tab. Since the executable code in the package is fairly simple, try modifying it a bit. Click on the EMPLOYEE_PKG.PKB file, and it will appear in the code window. Let’s add a line between COMMIT and END: COMMIT; DBMS_OUTPUT.PUT_LINE(‘Finished GET_SCOTT procedure’); END GET_SCOTT; Here in the File Explorer, you can interface with your source code control system (also known as version control), if it is SCC-compliant. For example, you could right-click on the upper part of the File Explorer grid, then use the Connect and Add menu items to store your newly created package in the source code control system. Then use the context menu to select Query > Execute Script to execute the CREATE OR REPLACE statement. In general, you would use Execute Script to execute all the code in the window, or when you do not need to see the results of a SELECT statement. The selected code will turn blue if successfully executed, or pink if there is an error. Picture BS shows the File Explorer, displaying files within the selected BS 53 TUTORIAL FOR DEVELOPERS folder, source code, and the context menu opened to Execute Script, which will execute all the code in the window. If there is only one executable statement (or block) in the code window, it could also be executed with the Execute Query context menu item or button. Try this now by selecting GET_SCOTT.SQL from the file list (the script that actually executes the procedure), placing your cursor in the code window, and opening the context menu to Execute Query. You will see the effect of your recent code modification in the DBMS_OUTPUT window. The SQL Repository The SQL Repository is an alternate interface to Windows’ file system when writing and executing SQL in the SQL Workbench. Click on its tab now. If this is the first time that you’re using Hora, you’ll see a tree diagram with Personal 54 SQL and Team SQL and an empty code window. The SQL Repository is essentially a logical interface to the file system on your computer, specifically to two folders within Windows named Personal SQL and Team SQL within the My Documents folder. Hora provides Team SQL as a suggestion that you may wish to separate code that you are working on and unit testing from code that you have given to a workgroup for a higher stage of testing. You can change the actual file system location of Team SQL from the My Documents folder to a network share. In the SQL Repository, you may add, remove and change nodes. Nodes are represented physically by both a folder and a file in Windows. Thus, when the Repository opens up, you may type code in the code window while Personal SQL is the current node. When you navigate out of that node or close the SQL Page, your code will be saved as Personal SQL\Personal SQL.sql. TUTORIAL FOR DEVELOPERS However, it is advisable to create new nodes in order to organize your SQL files into a logical hierarchy. Adding a node will result in a name like Item 139. You can immediately rename it, and it will assume its correct place in the alphabetical list of nodes. In this example, you’ll see several nodes beginning with a “1” that are being used as temporary work areas. BT The Query Builder we had applied to the KTGUIDE schema represent the same information as in SCOTT’s EMP table. We’ll use the Query Builder to generate a query to display related data from both tables: Follow these steps to place SCOTT’s EMPNO and ENAME columns into the query: u Open the Query Builder. u Use the Owner selector box at the upper left to select SCOTT. u Check the tables box – only the EMP table will be visible if no other object privileges have been granted. u Press the Include Table/View button. u Check the EMPNO and ENAME columns. Now let’s try something a bit more involved to become acquainted with one of the SQL Workbench’s special features: the SQL Query Builder. Access it through the construction site button. Let’s say that we wanted to create a query to confirm that the inserts and updates that Now, add KTGUIDE’s ID and LASTNAME columns to the query: u Select KTGUIDE from the Owner list. u Select the EMPLOYEE table, and double-click it. In the node 10Scratch we’ve just typed in a very basic select statement and hit the Execute Query button. BT BU 55 TUTORIAL FOR DEVELOPERS The Query Builder dialog should now appear like this. BU The related ID and name columns have been selected. Now, let’s see what happens if we press the OK button. We leave the Query Builder environment and are brought back into the code window with. CL We’re going to select four columns from two tables, and you probably already know what the results grid will look like. Here it is, anyway. CM The classic Cartesian join, showing every possible combination of rows from the two tables. (Note: When you select several tables in Query Builder that are related through foreign keys, WHERE clauses with inner or outer joins are automatically generated. However, no such relationship exists with the columns selected here.) If we return to the Query Builder, we will find the scene just as we left it; so we can make a quick repair by adding a WHERE condition like this. CN We now get the following results. CL CN 56 CM CO CO TUTORIAL FOR DEVELOPERS The only thing that remains to be done is to supply more meaningful column headings to explain what EMPNO and ID represent. This can be done using the Column Header column in the Query Builder. We’ll go back and do that now, re-execute the query, and then press the Report button found at the top of the results grid. Notice that even without going to the Report Designer, several options are available for tailoring the report. CPQuery Builder modified to specify column headings, Results window, and Report window. Try changing the report title to “Old and New Employee Numbers,” then pressing OK. You will see the first column heading appear only as “Scott,” instead of “Scott Empno.” To fix this, close the Report window, press the Report button again, then increase “Number of Lines in Column Header” to 2. CP 57 TUTORIAL FOR DEVELOPERS Execute Script button to execute the entire contents of your code window: CQThis looks better, but what happened to the title? In order to left-justify it, you’ll need to use the Report Designer. CRThe Report Designer, showing the title left-justified CREATE TABLE COMPANY ( The Data Contents Browser ID NUMBER NOT NULL, This facility was recently added to Hora to facilitate continuous viewing of several tables or views. It makes it possible to navigate back and forth between these tables using tabs. NAME VARCHAR2 (100) NOT NULL, STREET VARCHAR2 (200), ZIP_POSTAL VARCHAR2 (10), CITY VARCHAR2 (50), STATE_PROV VARCHAR2 (100), Here, you will create a COMPANY table to go with the existing EMPLOYEE table using the SQL Workbench. First, open up a new node in the Repository and call it Company. COUNTRY NUMBER, PHONE VARCHAR2 (50), WEBSITE VARCHAR2 (100), REMARK VARCHAR2 (1000), Cut and paste the following code into the SQL Workbench (or download it from ftp://ftp.keeptool.com/ktguide/company.sql, then press the CQ 58 CR LINE NUMBER ) PCTFREE 10 TUTORIAL FOR DEVELOPERS INITRANS 1 ALTER TABLE COMPANY ADD MAXTRANS 255 ( TABLESPACE USERS CONSTRAINT COMPANY_PK STORAGE PRIMARY KEY ( ( ID INITIAL 4 K NEXT 4 K ) MINEXTENTS 1 NOT DEFERRABLE INITIALLY IMMEDIATE MAXEXTENTS UNLIMITED USING INDEX PCTINCREASE 0 PCTFREE 10 BUFFER_POOL DEFAULT INITRANS 2 ) MAXTRANS 255 NOCACHE TABLESPACE USERS NOPARALLEL STORAGE LOGGING ( / INITIAL 128 K NEXT 128 K MINEXTENTS 1 MAXEXTENTS UNLIMITED 59 TUTORIAL FOR DEVELOPERS MINEXTENTS 1 PCTINCREASE 0 ) MAXEXTENTS UNLIMITED ENABLE PCTINCREASE 0 BUFFER_POOL DEFAULT ) / ) CREATE INDEX EMPLOYEE_COMPANY_FK_IDX LOGGING ON EMPLOYEE / ( COMPANY_ID ALTER TABLE EMPLOYEE ADD ( ) PCTFREE 20 CONSTRAINT EMPLOYEE_COMPANY_FK INITRANS 2 FOREIGN KEY MAXTRANS 255 ( COMPANY_ID TABLESPACE USERS STORAGE ) ( REFERENCES COMPANY INITIAL 128 K NEXT 128 K 60 ( ID TUTORIAL FOR DEVELOPERS ) COMMIT; NOT DEFERRABLE INITIALLY IMMEDIATE DISABLE UPDATE EMPLOYEE SET COMPANY = ABS(MOD(DBMS_RANDOM.RANDOM,3)) + ) 1 WHERE COMPANY IS NULL; / COMMIT; INSERT INTO COMPANY(ID, NAME, STREET, ZIP_POSTAL, CITY, STATE_PROV, COUNTRY, PHONE, WEBSITE, REMARK, LINE) VALUES (1, ‘Oracle’, ‘500 Oracle Parkway’, ‘94065’, ‘Redwood Shores’, ‘CA’, 150, Null, Null, Null, Null); INSERT INTO COMPANY(ID, NAME, STREET, ZIP_POSTAL, CITY, STATE_PROV, COUNTRY, PHONE, WEBSITE, REMARK, LINE) VALUES (2, ‘Rien De Mieux’, ‘100, ouest boul. René-Lévesque’, ‘H2C 3A9’, ‘Montréal’, ‘QC’, 22, Null, Null, Null, Null); The result of executing this SQL will be that you will have created a COMPANY table with 3 rows of data, and a foreign-key relationship between the EMPLOYEE and COMPANY tables. (Incidentally, you might want to verify that the accented characters in the INSERT statement appear correctly. For the purpose of this exercise, it doesn’t really matter, but if globalization will someday affect your business, it’s certainly something to keep in mind!) INSERT INTO COMPANY(ID, NAME, STREET, ZIP_POSTAL, CITY, STATE_PROV, COUNTRY, PHONE, WEBSITE, REMARK, LINE) VALUES (3, ‘Keeptool ‘, ‘Schützallee 118’, ‘14169’, ‘Berlin’, Null, 30, Null, Null, Null, Null); Since the data obtained from SCOTT’s EMP table won’t have a COMPANY_ID, we have added some random data to the EMPLOYEE table’s COMPANY column. 61 TUTORIAL FOR DEVELOPERS new tab. An implicit Filter by Selection takes place, so that you see only the row of the COMPANY table corresponding to SCOTT’s company. You’ll see any filter that is in effect in the Filter box. CSThe Data Contents Browser, showing the implicit Filter by At this point, if you already have the Tables page open, you will need to click on the Overview tab to see the COMPANY table in the overview. Selection for Company 1 Now, let’s see how the Data Contents Browser works. From Overview Tables, highlight the EMPLOYEE table; then rightclick to bring up the context menu, and click on Data Contents Browser. A dialog box appears, asking which table or view you want to see. EMPLOYEE is already selected by default. If you would like to see the entire COMPANY table, click on the Clear Filter button at the top of the window. Navigate to another company, and right-click and select Go To Detail Table, then EMPLOYEE. Again, a filter will be set that shows only the rows of the EMPLOYEE table for that company. Click OK, and the entire EMPLOYEE table appears. If you had other foreign-key relationships in your schema, you could then continue this process until you had several levels of related tables. You could then navigate back and forth among all the levels simply by clicking one of the tabs at the top. Next, move the cursor to the row where the name SCOTT appears. Right-click, select Go To Master Table, then the master table COMPANY. You will then see the COMPANY table added to the Data Contents Browser’s display, with a CS 62 CT TUTORIAL FOR DEVELOPERS Once a table grid has been generated, no additional queries are sent to the database, unless you modify the filter that is currently in effect or refresh the data by clicking on the table’s tab. Instead of a simple filter by selection, you may also use the ellipsis button next to the Filter box (outlined in orange below) to graphically generate a filter, which may then replace or refine the filter that is currently in effect. You may also enter the new filter in the Filter box manually. CTGenerating a Filter Through the Dialog Box Tools Bundled with Hora: The KeepTool suite of tools consists of u Hora, u PL/SQL Debugger and u ER Diagrammer. The latter two will be covered in future tutorials. They are also priced and sold separately from Hora. When you obtain a license for Hora, you also receive three bundled tools: SQL Editor, Reverse DDL Engineer, and HTML Documentation Generator. Using the KTGUIDE schema, we will now take a look at each one of these. CUThe last 3 tools are bundled with Hora SQL Editor Hora uses an Editor component that we have already seen when coding and testing the EMPLOYEE_PKG package, coding the EMPLOYEE_BIR trigger, and in the SQL Workbench’s code window. When you right-click in any of these windows, you will see the same context menu, which breaks down the Editor’s functions into five categories: u File u Query CU 63 TUTORIAL FOR DEVELOPERS u Edit u Search u Format u Extras The SQL Editor can also be invoked as a standalone tool, both from the Start > Programs menu and from Hora’s Tools menu. From each of Hora’s code windows, it can also be invoked from the context menu item Open in separate editor. By the way, there is no limit to the number of times you can click Open in separate editor. You can then cascade or format these windows to facilitate work on several units of code at once. SQL Editor is unique in being the only KeepTool product that can be used without connecting to the database. You can open or create a file, edit it, and save it while commuting to work (on public transportation). However, using the SQL Editor while connected to the database lets you compile and 64 execute code directly from the editor, modify it, and even look up online documentation from Oracle Technology Network. Let’s look at an example. If you currently have a Hora session open, open SQL Editor from the Tools menu. Otherwise, use Start > Programs > KeepTool 6 > SQL Editor. Either way, you’ll end up with a blank SQL Editor window. Now use the Open icon to open the file EMPLOYEE_PKG.PKS that you created earlier to CREATE OR REPLACE the EMPLOYEE_PKG package. You don’t see it? Just use the drop-down box to select.pks files. By default, the Editor lists only files with a .sql extension. The code appears in the Editor window without your having been prompted to log on. The string [not connected] appears in the title bar. TUTORIAL FOR DEVELOPERS If you then try to execute it, KeepTool’s Connect dialog will appear. If you take a look at the Query context menu by right-clicking in the Editor window, you’ll find other things that can’t be done at this point – Explain Plan, for example. Any attempt to select one of them will cause the Connect dialog to be displayed. So let’s log on now as KTGUIDE and explore some of the Editor’s facilities, beginning with the File menu DL For each of these menus, by the way, you’ll see a corresponding section of the Toolbar with some of the same buttons; sections are separated with double vertical lines. You may recall seeing the File menu before – it appeared when you created the three files EMPLOYEE_PKG.PKS, EMPLOYEE_PKG.PKB and GET_SCOTT.SQL from the DL DM Packages page. Most of the File menu is self-explanatory – however, the Compare tool is worth mentioning. Please press the Compare button now. Its Open dialog asks you to open another file. Select the EMPLOYEE_PKG.PKB file that you created earlier, and that is in the same folder, so that you will be comparing the package spec with the package body. DM The Compare tool uses u White to show lines that are the same u Green to show changed lines u Blue to show insertions u Pink for deletions Query menu DN DN 65 TUTORIAL FOR DEVELOPERS The Query menu contains many powerful functions. They are described to some extent in our online Help file; so we won’t go into great detail here – but instead, concentrate on a few highlights. To see how this works, just open a new editor window using File > New or the Toolbar button: Save the file to the default name NEW_FILE if you are prompted to save the file. Then enter Execute Statement and Execute Script Both of these will execute code found in the editor window. select * from employee; Execute Statement executes only one SQL statement or PL/SQL block. If you have several of either in the window, you can highlight one before pressing the button; if you have only one, this is not necessary. Execute Statement also places the result set of a SELECT statement in a grid that allows further manipulation. Execute Script places output from SELECT and other statements in a DBMS_OUTPUT window. DO 66 and try executing this statement with first Execute Statement, then Execute Script. DB Object Browser Try pressing this button to see a list of data and PL/SQL objects in each schema to which you have access. DO TUTORIAL FOR DEVELOPERS Code Completion You need to have enabled this facility through Hora’s Extras menu. To see two examples of how it works, try typing each of the following strings into the editor window: If you don’t see this, it could because you haven’t signed up with Oracle Technology Network. In that case, please visit http://www.oracle.com/technology/index.html and consider the benefits of doing so. select employee. Reverse DDL Engineer begin employee_pkg. Reverse DDL Engineer is one of the two reverse-engineering tools bundled with Hora, along with HTML Documentation Generator (which will be covered below). It requires a new connection to the database, and generates DDL for any or all objects of the schema of the logged-on user. When you start the application, you will see the status bar being updated very quickly with the names of several kinds of database objects. This serves to make a list of all objects available through check boxes. You can engage a setting on the Options menu to determine whether all objects should initially be checked or not. DDL will be generated only for those items that are checked when you click Generate. DR Do this just as you see above: type the period, then wait, and you’ll see a list of either table columns or package members, in this case Search Menu DP Many of these items are self-explanatory; so we won’t consider them here. Oracle Help is a powerful new feature that was recently added to the Editor. To see it in action, just highlight the word SELECT in your SELECT statement, and select Oracle Help. Your web browser should then open to a page like the following one. DQ DP DQ DR 67 TUTORIAL FOR DEVELOPERS The default behavior is to generate all DDL for the schema, including the CREATE USER statement, the TABLESPACE clause and storage parameters for all objects, and all grants received and given—as you can see on the Schema tab above. Press the Generate button. The status bar will show you the kinds of objects that the Engineer is currently processing. When it finishes, you will be asked if you would like to view the generated file. Click Yes. Click on the Tables tab now to see a list of tables for KTGUIDE. Then right-click on the list at the left to bring up the Select/Unselect menu. DSThe Tables tab with “Select All” in effect Now click Unselect All and check only the Tables check box at the left. You will see that Reverse DDL automatically checks a few other boxes in addition to Tables. DTThe Tables tab after choosing "Unselect All" and checking “Tables” DS 68 DT This is Reverse DDL’s helpful way of suggesting that if you would like to replicate your tables in another database, you may want to generate the DDL for other objects that are closely associated with those tables. HTML Documentation Generator Like Reverse DDL Engineer, HTML Documentation Generator reads the Data Dictionary to provide data about the current schema in usable form. Instead of executable DDL, it produces an HTML summary of the schema that incorporates hyperlinks between the summary to the detail information, and between related objects. You can start the tool either from Start Programs, or from the Tools menu in any other KeepTool application. The Generator’s Connect dialog is a bit different from that of other KeepTool applications. Please fill in your user name DU TUTORIAL FOR DEVELOPERS and password and click the Start button, leaving all the default settings. DU After the Generator has finished, you will be asked if you wish to see the HTML file that it has created. Click Yes, and the page will appear in your browser. ELBeginning of the HTML document generated for the KTGUIDE schema The title was generated from the default settings of the Connect dialog. You can create your own title, optionally using variables for the schema name and the current date, if you wish. Although the schema that you have created does not have a great many objects in it, you can see that it is divided into a Tables Overview and a PL/SQL Objects Overview. From the Tables Overview, there are links to each table or view. If you scroll to the bottom of the information for the COMPANY table, you will find information for constraints, triggers, detail (child) tables, and PL/SQL objects that reference the table or view. EL EM Now, follow the link to the PL/SQL Objects Overview. EM The procedures A, B and C were created behind the scenes to give you an idea of how the Generator keeps track of dependencies among PL/SQL objects. Procedure B is called by C, and calls A. EN Available options Please take another look at the Generator’s Connect dialog, where you will see that you have the ability to specify various options at logon time: u Whether to include views in the Tables section u Whether to include PL/SQL objects at all u Whether to display visible borders in HTML tables You can also filter the tables to be included by tablespace name or table name. PL/SQL objects can be filtered by object type or object name. EN 69 TUTORIAL FOR DEVELOPERS Batch invocation HTML Documentation Generator supports two different types of batch invocation. Please create the following batch file to get an idea of how this works (file also available at ftp://ftp.keeptool.com/ktguide/ohyper.bat): rem This batch file invokes KeepTool’s HTML Documentation rem Generator in full batch mode Batch invocation uses keyword parameters, which are fully described in the online Help file. In this example, table names and PL/SQL objects have been filtered. The parameter batch=y indicates that the Generator should execute automatically. The alternative, batch=n, supplies the values to the Connect dialog, and requires the Generate button to be manually activated. ohyper.exe userid=ktguide/ktguide@db10g batch=y output=c:\temp\ohyper.html tabfilter="TABLE_NAME LIKE ‘%%COMP%%’" plsqlfilter="OBJECT_TYPE = ‘PROCEDURE’" lang=e If you’re not using KTGUIDE as your user name, or db10g as your connect string; or you don’t have a C:\temp folder, you’ll have to make the needed changes. You will see the Connect dialog pop up, display it status messages, and go away. You will need to manually open your browser to the output file. 70 Please note also that in a batch file, the "%" characters used in the LIKE expression must be doubled. We hope that you will find this tool to be helpful to document your database after a major project, or to update your documentation as requirements change. ! In this tutorial, we’ll focus on some Hora features of particular interest to database administrators. You will find all of them listed on the DBA collection of the Sidebar. We would encourage you, either before or after going through this tutorial, to take a look at the Hora tutorial for developers, as well. As a DBA, you will be interested in database objects such as indexes, constraints, and triggers – all of which are found on the Tables page of the Standard collection. That’s also where you’ll find information about public synonyms, jobs, and database links. ! To try the examples in this tutorial, you will also need the following roles: For the DBA Sidebar to be activated, a user needs to have either the HORA_USER role, which is provided with the KeepTool installation, or the SELECT ANY DICTIONARY system privilege. If he does not have either of these, the DBA Sidebar button will be disabled. @SQL Preview On TUTORIAL FOR DBA’S HORA – A TUTORIAL FOR DBA’S CREATE TABLESPACE u ALTER TABLESPACE u CREATE USER u ALTER USER Even if you don’t have all of these, you’ll still be able to follow the examples to the point where the code is generated. Then we’ll show you the actual results. @ 71 TUTORIAL FOR DBA’S Data Dictionary Hora uses the Data Dictionary views to populate all the grids that you will see when clicking one of the above DBA icons. It is KeepTool’s aim to present the most vital data about your database within two clicks that is, a click on one of the above icons, followed by a click on one of the tabbed sheets. There are times when you’re after something very specific and you know right where to go in the Data Dictionary to get it. For example, say you want to find out which database parameters might have been modified with an ALTER SYSTEM command, and you know that the answer is in V$PARAMETER. As you click on the Data Dictionary icon, you will see a listing of views probably beginning with ALL_ALL_TABLES. At the bottom of the grid will be five tabs, with the leftmost one activated, indicating that the current list includes all views. § § 72 The others let you browse only the views beginning with that particular prefix. But since you already know that you’re interested in V$PARAMETER, you can just start typing V$P… right on top of the grid. With each keystroke, you are positioned closer and closer to V$PARAMETER. This example shows the grid after typing only "V$P." The first alphabetic match will always be shown. At this point, since V$PARAMETER is clearly the next view in the list, you could press Enter, which will close the Search dialog, and click on V$PARAMETER, then click the Data Contents tab. $Navigating by typing on the grid The green toolbar icon that resembles the letter Y presents a filter dialog. If you are looking for parameters that have been modified by an ALTER SYSTEM, you can search for the value SYS_MODIFIED in the column ISMODIFIED of V$PARAMETER. If you know that the only other possible values are MODIFIED or FALSE, then just typing "sys" in $ TUTORIAL FOR DBA’S lower case will do, because the Partial match at beginning option is on, and case-sensitive is off. %Filtering for a string press the Clear button – or use Data Grid > Clear Filter on the context menu. beginning with "sys" or "SYS" in ISMODIFIED If you’ve just done an ALTER SYSTEM for nls_length_semantics (Hora’s Database page gives you a graphic interface to alter initialization parameters), you’ll see the following result. &Filtered view of V$PARAMETER In a case like this, where filtering has produced only one result, you will probably want to take advantage of the Record View by pressing the tab at the right of the grid. This will show you all the data for parameter 147, “nls_length_semantics,” as we see here. /Record view of V$PARAMETER Of course, if later you’d like to see the entire contents of V$PARAMETER, you’ll have to return to the filter dialog and % Tablespaces Page The Tablespaces page’s Overview grid starts with some basic information about tablespace size. In addition to the usual figures, you will see some graphs that render the percentages of free space usage and the percentage of auto-extend usage as bars with varying lengths of red and green. The current size of the TEMP tablespace will always be 100%, as there is no entry for it in DBA_FREE_SPACE view – and to be consistent with other tablespaces that are 100% full, its name will also always be shown in red. (SYSTEM Tablespace at 99.4% of capacity & / 73 TUTORIAL FOR DBA’S Increasing the size of a datafile Probably the next thing that you will notice, after TEMP, is that the SYSTEM tablespace is 99.4% full. By pressing the DDL button on the toolbar, you can see how it was defined. ) At this point, you may wish to stop following along on your own system (unless you have a similar situation), and just watch what happens. Two statements are generated from the dialog after the new value is plugged in. BMand BN Its initial allocation was 450 MB, and that is its size (460,800 KB) today. We could therefore wait for it to autoextend by another 10 MB, but if there is not too much going on at the time we are looking at the space usage, we could also increase it manually right now. This can be done on the Datafiles tab, using the Properties/Resize menu item. The dialog looks like this when it opens: BLForeground: the Datafile You could reply Yes to both of these, or just the first one. The result would be the same, since the NEXT amount is not being changed. Properties dialog; Background: the Datafiles tabbed sheet The percentage of space used has now declined from 99.4% to 97.5%. We can use the dialog to simulate the effect of an autoextend by changing the defined size from 450 MB to 460 MB, just by overtyping the value. When you finish, the tablespace is shown at its new size. BOSYSTEM tablespace at 97.5% of capacity Shrinking a tablespace Now, let’s take a look at the percentage of usage in the ( BL BM BN ) BN 74 TUTORIAL FOR DBA’S USERS tablespace in the previous illustration: 15.8%. If you know that there is very little likelihood that many new objects will be created in it, you might want to shrink its size by half. Pressing the DDL button shows us that the 80,640 KB was the initial allocation (provided by Oracle when the tablespace was created). BP By using Properties/Resize, we can see that the file can be shrunk down to a minimum of 13,828,096 bytes, or 13,504 KB. This amount is calculated when you press the Minimum Shrinkable Size from Highwatermark button. This means that by shrinking the datafile by half (down to 40,320 KB), we should still have three times as much space left for future expansion as the amount that is currently being used (12,736 KB). The following screenshot shows the USERS tablespace at its new size. BQThe percentage of usage for USERS has increased from 15.8 to 26.7%; its total size has been reduced by half. BO Moving segments to another tablespace One often hears that indexes should be located on another drive from their associated tables – assuming that you don’t have a hardware solution such as RAID that automatically reduces contention for read-write heads. The easiest way to accomplish this manually is to put them in a tablespace with datafiles on another drive. We will show an example or rebuilding indexes that you can follow along with. At the end, you will move the index segment back to its original tablespace and drop the new one. First, let’s create a very small tablespace called INDEX01. You will find CREATE TABLESPACE on the Toolbar and the context menu of Overview Tablespaces. On the Oracle server being used to provide examples for this tutorial, there is, unfortunately, only one drive, and as a result, we will create the new datafile in the same directory as the others listed in the drop-down box. The easiest way to do this is to BP BQ 75 TUTORIAL FOR DBA’S select one of the existing datafiles and overtype the last portion of its name. You, on the other hand, can create the tablespace on another drive and drop it afterwards. BR Now, click the Segments/Extents tab for the USERS tablespace. If you went through the Developer Tutorial, you will have an index segment called EMPLOYEE_PK. If not, select any one of your current index segments. Right-click on it in the lower-right grid, and choose Properties/Rebuild. Leave all the properties alone (or change them if you wish), then choose INDEX01 from the drop-down list. BSSelecting the rebuilt index back to the USERS tablespace, and drop the INDEX01 tablespace, using the Overview Tablespaces tab and the Drop button . For destructive operations that could have serious consequences, Hora inserts a confirmation dialog like this one. BU Be sure to check both the Including Contents and And Datafiles boxes if you want the datafile to be dropped by Windows. Although the tablespace has no logical contents as far as Oracle is concerned, you’ll need to check both boxes in order to generate a valid SQL statement. EMPLOYEE_PK segment Database Page SQL Preview will then generate an ALTER INDEX REBUILD pointing to the new tablespace. BT When the statement has executed, you will see the grid refreshed, with the moved segment no longer there. You can now use the same series of steps to move the BR 76 BS The page opens up to an overview with some basic data about the database. Here we will look at a few of the remaining tabs that you are likely to use quite often: u NLS Parameters u Initialization parameters BT TUTORIAL FOR DBA’S u Roles/privileges u Profiles byte semantics are being used. NLS Parameters Oracle can be made to behave in different ways in different locales. To accommodate local preferences, different languages, date formats, currency formats, and calendars – to name just a few examples – may be used. Even if your language is English, you might expect to see the same word spelled in different ways depending on your country, and Oracle is happy to accommodate. In the illustration below, you will see that many of the same parameters can be set on either a database, instance, or session basis. Values are taken from the NLS_DATABASE_PARAMETERS, NLS_INSTANCE_PARAMETERS, and NLS_SESSION_PARAMETERS views, respectively. CLThe database character set, AL32UTF8, allows for up to 4 bytes per character, but BU Please take a look at the values of NLS_LENGTH_SEMANTICS in your own database. The above illustration also shows us that even though the database character set is a multi-byte one that allows for characters between 1 and 4 bytes in length (AL32UTF8), NLS_LENGTH_SEMANTICS was set to BYTE for the database. However, suppose that we want to do an ALTER SYSTEM to change it to CHAR so that from now on, any user who creates a table column of VARCHAR2(30) will actually be allowing the column to contain 30 characters of data in the AL32UTF8 character set. Initialization parameters To see how Hora’s interface lets a DBA perform this change easily, let’s move to the Initialization Parameters tab, navigate to “nls_length_semantics” by simply typing on the CL 77 TUTORIAL FOR DBA’S grid, then right-click on the line to show the possibilities for modifying this parameter. CM Let’s choose Alter System Parameter to update the value to CHAR and add a comment. CN You can add a comment to record why the change is being made and specify whether the change should take place in memory for the instance, in the SPFILE for future startups, or both. In this case, we’ll choose both. CO The result, including the comment, is immediately shown on the both the Initialization Parameters and the NLS Parameters (under INSTANCE) sheets of the Database page. It also immediately appears in the Data Dictionary in NLS_INSTANCE_PARAMETERS. You may recall, though, that in this example, the SESSION value (found in NLS_SESSION_PARAMETERS) was BYTE. CM 78 That value is still in effect, and it takes precedence over both NLS_DATABASE_PARAMETERS and NLS_INSTANCE_PARAMETERS. In our example, that means that if you were define a new table column as VARCHAR2(30), it would still be allocated for 30 bytes, rather than 30 characters. The actual length in bytes of a table column can be found in the DATA_LENGTH column of the Dictionary view USER_TAB_COLS. Here is a quick exercise that you can do to see the effect of modifying NLS_LENGTH_SEMANTICS at the session level if you have a multi-byte character set such as AL32UTF8 or UTF8: u Determine the current session value of NLS_LENGTH_SEMANTICS u CREATE TABLE T1 (C1 VARCHAR2(30)); CN TUTORIAL FOR DBA’S u Use USER_TAB_COLS to find the length in bytes of C1. u Use Hora’s Initialization Parameters sheet to set the session value to its opposite. u CREATE TABLE T2 (C1 VARCHAR2(30)); u Use USER_TAB_COLS to find the length in bytes of C1. System Privileges tab is activated by default. Granting a system privilege or a role to a role is a simple matter of clicking the Grant button and checking the roles or privileges to be granted from the list. Creating a new role However, since we only want to grant object privileges to the role, we will instead select the second bottom tab, Granted Object Privileges, before clicking the Grant button. This will start a dialog where you can relate an object privilege to a specific owner and object name. CQGranting an object privilege to a role The Database page makes it easy to create a new role, using the Roles sheet. For example, suppose that quite a few users will need to have the SELECT privilege on KTGUIDE’s EMPLOYEE table, as well as EXECUTE on the new EMPLOYEE_PKG package. As a DBA, you can first create the GUIDEROLE role by clicking on the CREATE ROLE button, either on the Toolbar, or on the context menu: . The role appears in the Overview as soon as it is created. Now the role needs to have some privileges defined for it. Note that, of the four bottom tabs, the Granted Roles and CO CPGranting a system privilege or a role to a role You’ll need to specify both EMPLOYEE with SELECT and EMPLOYEE_PKG with EXECUTE. These will then be added to the grid. The grid will keep extending to the right to accommodate as many additional privileges as are needed. It will also extend downward as new owners and objects are added to the definition of GUIDEROLE. CR CP 79 TUTORIAL FOR DBA’S Creating a new profile Users Page Before creating a new user in the next section, we’ll use the Profiles tab of the Database page to create a profile called RESTRICTED_USER. It will set specific values for the following: u SESSIONS PER USER 1 u CPU PER USER 10 minutes, expressed as 60,000 hundredths of seconds u CONNECT TIME 1 hour, expressed as 60 minutes. Let’s take a look at the process of creating a new user, assigning a profile to him, and granting him some roles and privileges. You’ll see the Create Profile button on the toolbar as a profile with a + sign: . In the dialog, simply fill in the blanks, then press OK. CSWhen the CREATE PROFILE statement is generated, SQL Preview will assign default values to all the resources for which no value was specified. CQ 80 CR Creating a user Please make sure that you have first created the RESTRICTED_USER profile described in the Database page section. The new user will be defined as follows: u Name NEWUSER u Password NEWUSER u Default tablespace USERS u Temporary tablespace TEMP u Profile RESTRICTED_USER u Roles CONNECT, RESOURCE, HORA_USER, GUIDEROLE CS TUTORIAL FOR DBA’S From Overview Users, click the Create User button on the Toolbar, and fill in the dialog as follows. CTDefining or modifying come from? Although the definition of RESOURCE (i.e. its CREATE ROLE statement) does not include UNLIMITED TABLESPACE, granting RESOURCE automatically causes UNLIMITED TABLESPACE to be granted as well. a user Notice that the dialog is entitled User Properties. This indicates that the same dialog would appear if you later wanted to use Hora to alter a user. Granting system privileges and object privileges to a user CT Notice that the Granted Role and System Privileges bottom tab is active by default. To grant a new system privilege to NEWUSER, just click the grant button on the toolbar, or on the context menu, and the Grant dialog will open. You will grant a system privilege, CREATE PUBLIC SYNONYM, and an object privilege to NEWUSER. When you first click on the Roles/Privileges/Consumer Groups tab of the Users page, you will see the roles and system privileges granted to NEWUSER at creation time. CU Now, it’s just a matter of checking the box for the system privilege that you want to grant. There might sometimes also be cases where you would want to check the with admin option box, too. This option allows the grantee to grant a system privilege to others, and if checked, applies to all system privileges that have been selected. DLGranting a system The roll of film designates a role, and the hand in front of UNLIMITED TABLESPACE indicates a privilege. Where did it privilege (CREATE PUBLIC SYNONYM) to NEWUSER CU 81 TUTORIAL FOR DBA’S Now let’s see how to grant an object privilege to NEWUSER, for example, SELECT on SCOTT.EMP. First, click the bottom tab entitled Granted Object Privileges, then click the hand in the Toolbar (or right-click on the grid) to bring up the Grant dialog. You’ll see a list of object privileges with NEWUSER preselected as the grantee, since NEWUSER was selected in the Overview. DMGranting SELECT on SCOTT.EMP to NEWUSER All that remains is to choose an owner and an object name from the drop-down lists – and the new object privilege is then added to the grid. DN Dropping a user Dropping a user is as simple as pressing the red on the toolbar when Overview Users is active. If you want to drop a user who has objects, you should check the CASCADE DL 82 DM option, because the user cannot be dropped otherwise. However, if you think that all the user’s objects have already been dropped, but aren’t sure, then clearing the CASCADE check box before dropping the user is a good way to find out. DROP USER is one of several commands that allow you to drop multiple occurrences by selecting them with the Ctrl key. Dropping objects, but not the user On the other hand, if you would like to get rid of all the user’s objects, but not the user himself, you can use the Clear Schema item on the Schema menu to execute code to do that. You will receive two confirmation requests asking you to verify that you want to drop the objects from the schema pointed to by the schema selector box at the lower left of the screen; so be very sure that it is the right one. DO TUTORIAL FOR DBA’S SGA page Beyond the Overview tab, the next three tabs present information taken from V$LIBRARYCACHE, V$ROWCACHE, and V$BUFFER_POOL. Here, we will focus on the SQL Area tab, which captures data from V$SQLAREA. DP In this shot, the SQL text area at the bottom has been increased in size (by dragging the border between it and the upper grid) to give a better idea of what the SQL statement does. This is the query that populates the Overview Synonyms grid. It is the same statement that is highlighted in blue in the upper grid, which shows an abbreviated version of the text. As you click on other statements in the upper grid, the lower grid refreshes itself to show the complete SQL statement. Even if you do not click on another row in the upper grid, you can see more of each SQL statement there by hovering over the abbreviated version with the mouse. DN Notice the five tabs at the bottom of the upper grid. The first four each filter out a portion of the statements. Since Buffer gets (sum) is selected, the grid shows the statements with the highest values in BUFFER_GETS in V$SQLAREA. Dividing the number of buffer gets by the number of executions yields the average number of buffer gets per execution. Clicking on the second bottom tab, Buffer gets (avg.), will list the statements with the highest values for this average. In our example, this query placed first in both respects. Please try it on your system. First go to the Synonyms page to display the overview; then come back to the SQL area tab and use the vertical scroll bar to find it. You may not find this statement, but you may want to take note of what you do find. If you right-click on the statement in the bottom grid, and DP DO 83 TUTORIAL FOR DBA’S choose Query from the context menu, you can generate an Explain Plan for this query. The Explain Plan reveals that the statement does quite a few index reads and full table scans. DQ Other pages In the chapter entitled Hora: A Quick Tour in this guide, you can see examples of how the Sessions page and the SQL Workbench can be used by DBA’s. An in-depth discussion of the SQL Workbench may also be found in Hora: A Tutorial for Developers. DQ 84 TUTORIAL FOR DBA’S 85 KeepTool GmbH · Schützallee 118 · 14169 Berlin · Germany · www.keeptool.com