Download Chapter 12 Generate Database Tables

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Open Database Connectivity wikipedia , lookup

SQL wikipedia , lookup

Oracle Database wikipedia , lookup

Concurrency control wikipedia , lookup

Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Functional Database Model wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Ingres (database) wikipedia , lookup

PL/SQL wikipedia , lookup

ContactPoint wikipedia , lookup

Clusterpoint wikipedia , lookup

Versant Object Database wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Relational model wikipedia , lookup

Database model wikipedia , lookup

Transcript
Chapter
1
12 Generate Database Tables
Generate relational table data definitions
We built the server model in Chapter 8. The server model is built using the information from the table
definitions. In Chapter 11, we show how the design editor is used to make modifications to the tables.
These included adding derived columns, audit columns, etc. Once we are satisfied with the design of the
database structure or schema, we are ready to generate the schema in a target database. The target database
where the tables reside can be any number of different choices.
1.1
Server Model
The Server Modeler is a graphical tool for modeling logical database designs. The database objects within a
schema and how they relate to one another are represented graphically on Server Model Diagrams.
Figure 1 Server Model Diagram
There are several approaches to creating a logical Server model in the Repository. Server Model Diagrams
support each of these approaches. You can generate a first cut Server model from analysis data, and use
Server Model Diagrams to view and edit the database design graphically. If you are developing a new
database, use Server Model Diagrams to create a new Server model from scratch. As you create elements
on the diagram, their definitions are stored in the Repository. Alternatively, capture the design of an
existing database into the Repository, and then use Server Model Diagrams to edit the design. For more
information about the different approaches to database design and generation, see Generating a database.
1.1.1
Create Server Model Diagrams
Do one of the following:

Choose File  New  Server Model Diagram.

From the Navigator, select the elements that you want to be displayed on the diagram and
drag them onto the workarea. The work area is on the right of the navigator window.

From the Navigator, position the cursor over the element that is to appear on a Server Model
Diagram, then press the Right Mouse button. This causes a popup menu to be displayed, from
which you must choose Show on New Diagram.
Each new diagram window created is untitled except for a default name "Untitled # " (displayed in the title
bar), where # is a number incremented by 1 each time a new diagram is created during the current session.
You can either accept the default name when you save the diagram, or assign a more meaningful name.
1.1.2
Server Model Diagram elements and notation
The conventions used to model a database schema using Server Model Diagrams are shown below.
Figure 2 SMD Elements
Each diagram element displays a summary of the properties of the element. The amount of detail shown
can be changed to your preferred layout using the options available from the Options menu. An ellipsis (...)
at the bottom of an element indicates that there is insufficient space on the element to display all properties
of the element.
Figure 3 Element Details
1.1.2.1
Title bar diagram element section
This identifies the name and type of the Repository definition that is represented by the diagram element.
For example, in the picture above, the button shows a table icon and the name of the table. The title bar
section also contains buttons that identify which secondary elements have been defined for the element.
These buttons are shown below:
Table 1 Buttons and Meaning
Button
Secondary element type
Triggers
Indexes
Synonyms
Primary key
Unique keys
Check constraints
Foreign keys
Oracle object type methods
Note:
If a button is dimmed then no secondary elements of that type exist for the primary element.
The title bar buttons can be used to display or hide secondary element details. Title bar buttons can also be
used to create secondary elements, by clicking the right mouse button over the appropriate button.
Column/attribute details diagram element section
This shows the columns/attributes that are defined for the element, e.g. the columns for a table. You can
specify which columns/attributes are shown in this section.
Secondary element section
This shows the secondary elements that are defined for the element, e.g. the indexes that are defined for a
table. You can show and hide secondary elements.
1.1.3
Tips, tricks and shortcuts for Server Model Diagrams
1.
You can create a Server Model Diagram that is based on existing Repository definitions, e.g.
tables, by dragging the definitions from the Navigator onto the workarea.
2.
You can include existing Repository objects on a diagram, by selecting them from the Navigator,
other Server Model Diagrams, the Repository Object Navigator or the Matrix Diagrammer, and
dragging them onto the required diagram.
3.
To create secondary elements, i.e. primary keys and foreign keys, click the right mouse button
over the appropriate title bar button on the diagram element. When using these buttons you can
create customized elements rather than the default ones. For example, using this option to create a
foreign key allows you to specify Delete and Update rules as the foreign key is being created.
4.
Change the name of a diagram element by selecting the diagram element name and then doubleclicking on that name. A box is displayed around the name to show that it can be edited.
5.
Use the right mouse button to display a popup menu that lists the valid actions that can be
performed for a diagram element. To display the popup menu, position the cursor over the
required element and click the Right Mouse button. For example, if the cursor is positioned over a
column name, the popup menu shows actions that are valid for columns only.
6.
To delete elements to which references have been made by other elements, use Utilities  Force
Delete. Cutting from the diagram does not remove it from the repository!
7.
Maximize the size of the diagram window before creating or including any elements.
8.
Minimize the amount of detail displayed on the diagram, by suppressing the display of column
names, primary key indicators and foreign key names etc. To do this, select Edit  Preferences
and in the Preferences dialog box, deselect the items in the View group.
9.
When creating a complex diagram using existing data, include only a few elements at a time. You
can then position elements on the diagram in logical groups, and add to it gradually.
10.
When including (Edit  Include) several elements at a time, suppress the display of foreign keys
in the Include dialog box. You can then position the elements on the diagram before including
foreign keys.
11.
To tidy up a cluttered diagram, choose Edit  Select, click on the Foreign Keys node and close
the dialog box. Select Edit  Cut to remove the foreign keys from the diagram. Reposition
diagram elements to the required layout. Select Edit  Include and check the Also include
Foreign Keys to include the foreign keys.
12.
Create dog-legs to bend connectors around other items on the diagram, to make it easier to read.
13.
To quickly display the properties of an element, select the element and press the ENTER key on
the numeric keypad.
14.
Display the grid so that you can draw items to a specific size. You can also change the size of the
grid cells to the required height and width by choosing Options  Layout.
15.
After moving a diagram element, you may also need to reposition the foreign key connectors. To
do this, select all of the foreign keys connected to the diagram element (by holding down the
CTRL key and clicking on the connectors). Then click to autolayout the selected connectors.
16.
To add a column (that has already been defined for a table) to the table's primary key, do the
following
17.
1.
Show the primary key in the secondary usage section of the diagram element.
2.
Drag the column from the column/attribute section, onto the primary key in the secondary usage
section. A primary indicator (#) is displayed next to the column to show that it is now part of the
primary key.
Change the order in which columns/attributes are displayed on Server Model Diagram elements by
dragging and dropping them.
Note: If a diagram element does not show all of it's columns/attributes, e.g. you have specified that only
mandatory columns should be displayed, you cannot use drag and drop to reorder the displayed
columns/attributes.
1.2
Generating database
Oracle Designer uses the database generator to convert the table definitions stored in the repository to
physical designs. The physical designs may be directly implemented in an Oracle database or a batch script
file may be created. To generate the physical design select Generate Database from Server Model from the
Generate menu in the Design Editor.
Figure 4 Generating Database Specification
1.2.1
Generating DDL scripts
You can generate data definition language (DDL) scripts in the syntax appropriate for your target database,
based on all or part of your database design. The generated scripts can then be run against the target
database using a separate tool. To generate a DDL script:
1
2
In the Design Editor, select at least one object definition you want to generate in the Navigator.

Select objects on the Server Model view to generate the base object.

Select objects on the DB Admin view to generate objects tailored for a specific user.
You must select an object definition rather than a node in the tree.
Select Generate  Generate Database from Server Model.
Alternatively, click on the Generate DDL button
.
3
On the Target tab, select the DDL Files Only option. Do not create tables directly into Oracle.
Only experienced DBAs should choose to create tables directly into an online database!
4
From the Type drop-down list, select the type of DDL syntax to be generated.
If there is no corresponding database type for the target you require, select ANSI 92 to generate
ANSI-compliant syntax. In our example we use Oracle8 as the database type.
5
In the File Prefix field, enter the name of the script to be generated. The script files will be named
using the string you provide. Use names that you can easily remember!
Alternatively, select the name of a file you generated previously from the drop-down list.
6
[Optional] In the Directory field, enter the path where the script is to be generated.
You can select the paths used during previous runs of the utility, or you can use the Browse
facility to choose a different drive and directory. If you omit the path, the script is written to the
current working directory. For later retrieval it is preferable to set the path to a removable storage
device (e.g., zip disk or diskette). Do not create a deep directory path.
7
Select Stop on error to terminate the generation if an error is detected during generation.
Figure 5 Creating DDL Scripts
8
Select the Objects tab.
9
Choose the objects you want to generate, by moving them to the Generate list box. You can click
on the >> icon to move all objects to the Generate list.
Figure 6 Select Objects to Generate
Figure 7 Set Generate Options
10
(Optional) Select the Options button to specify your preferred generation options.
11
Select Start to begin generation.
During the generation process progress information is displayed in the Messages Window. If any
errors occur, correct the errors and then generate the DDL again. To avoid overwriting existing
files, enter a new prefix for these files.
Use the toolbar buttons
to scroll through the error messages. For each message, cause
and action information can be displayed and where applicable, navigation options are displayed
which allow you to navigate to the source of the error.
Figure 8 Message Window with Generation Result
12
To review the content of generated DDL files:

Click

Double-click the file name to view the content.
on the Messages Window toolbar.
Figure 9 Script Files Generated
1.2.2
Validation checks performed during database generation
During generation, Server Generator validates Repository definitions selected for generation. An error is
reported to trap the following conditions:

Table definitions without columns

Index definitions without key components

Primary keys without key components

Unique keys without key components

Foreign keys without key components

Check constraints without a PL/SQL statement

Data structures without a data structure item

Clusters without cluster columns
In most cases you will not be working with data structures and clusters as these are advanced features.
2
Build database schema in target system
In order to build a physical database schema in the target database you need to execute the SQL scripts
produced in the previous section. At the end of generation, you can browse through the DDL script files
that the Server Generator has produced. These files contain the commands that will create the database
when you execute them. You can run a generated DDL script from within the Design Editor or directly
from the SQL*Plus prompt. You can build a database incrementally, or in a single step. To execute a script
file, in SQL*Plus type Start ‘c:\sql\cdsddl’. But, verify that the command scripts will do what you intended
to do before executing them. Once Oracle objects are created in the system it is difficult to make changes!
2.1
Incremental Build
Run the DDL scripts one by one to build the database in a controlled fashion. This incremental method of
implementing the database is recommended for all but the simplest designs because of the
interdependencies of the DDL scripts.
When you build the database incrementally, make sure you execute the DDL scripts in a logical order: For
example:

First, execute the .db file to create the database.

Next, execute the .tab file to create database tables.

Then, execute the DDL scripts for snapshots, views, PL/SQL, indexes, and finally triggers.
All these objects depend on the existence of tables.
If you are not sure the order in which files should be executed, refer to the master command .sql file. This
file lists individual script files in the correct order. Also, if the script files were written to a subdirectory,
then you need to add the path descriptor to each of the script file in the command file. See example below.
Figure 10 Modified Command File
2.2
One-Step Build
Select and run the master command .sql file.
This file contains entries to run each of the other script files that Server Generator has produced. Therefore,
if you execute this file you will create your database system in a single step.
2.3
Implementation
Once you have run the DDL scripts, you will have an implementation of a database that you have defined
in the Repository. Now you can use the database for Oracle applications, such as generated forms and
reports.
2.4
Altering the database design after generation
If changes are made to your server model, you will have to generate DDL for all or part of the model again
in order to alter the design on the database. If your database is online (Oracle or ODBC), a Reconcile
Report (<File_Prefix>.lis ) is generated detailing the objects that need to be created or altered on the
database. You can view the Reconcile Report to check through the changes that are required, or implement
the changes directly on the target database. Only when you generate directly to an Oracle database these
files are produced.
Note:
2.4.1
If you generate DDL to a script file, no cross-referencing/reconciliation can take place.
Altering existing objects on a database
If you try to generate a database object directly on an online database and the object already exists, the
DDL necessary to alter the existing object is generated.
Note:
2.4.2
The user must have suitable ‘Alter’ privileges.
Altering database administration objects
DDL cannot be generated to alter database administration object definitions.
2.4.3
Renaming objects on a database
Database objects cannot be renamed during generation.
2.4.4
Deleting objects on a database
Database objects are not dropped from the database automatically. This includes any columns already in
the table. In fact, Oracle does not allow a column to be deleted from a table! You must drop the table and
recreate the table without the column in question.
Constraints cannot be dropped using the ALTER TABLE command. However you can disable them
instead of dropping them.
2.4.4.1
Enabling and disabling constraints
By default, the following types of constraint are automatically enabled on the server when they are
generated.

primary key

unique key

foreign key

check constraint
However, it is possible to disable a constraint by setting the Enabled property of the constraint to No.
Note: A primary key constraint must be enabled if referenced by a foreign key, which must also be
enabled.
2.4.5
Altering a table that contains no data
The restrictions are as follows, you cannot:
2.4.6

change a column/attribute from optional to mandatory

add a mandatory column/attribute, only optional columns/attributes

drop a constraint, but you can disable it
Altering a table that contains data
The restrictions are as follows, you cannot:
2.4.7

drop columns/attributes

change the column/attribute datatype

change the maximum length of columns/attributes
Deleting columns/attributes from tables containing data
Columns/attributes cannot be dropped using the ALTER TABLE command. Create a new table omitting
the redundant column and then insert data from the old table into the new one.
2.4.8
Removing comments
Set the Comment property to ' ' (double quote).
3
3.1
Generate Table API
Table API
The Table API provides PL/SQL packages, known as table handlers, that client applications can call to
perform DML operations on tables. Each table handler contains PL/SQL procedures that the application
can call to:

insert a new row in a table

update a row in a table

delete a row in a table

lock a row prior to an update or delete
The Table API validates the data provided by the calling application and generates default values when
appropriate before the table is modified.
Before a row in a table is inserted or updated, the Table API performs the following checks:

validates constraints

auto-generates the following column values:

unique and sequential values for columns that derive their values from a sequence definition

pre-defined default values

change history information for AutoGen Type columns (Created by, Modified by, Date Inserted, Date
Modified)

converts column values to uppercase

maintains journaling information

maintains denormalized columns
When you generate table handlers, you can also generate an accompanying set of database triggers that call
the table handler procedures when a DML statement is issued against the table outside of the application.
Note:
The Table API is only supported on Oracle7.3 database and above.
3.2
Constraint validation performed by the Table API
Most types of table and column constraint will, by default, be validated on the server. The exception to this
is foreign key Nullify and Default rules, which can be validated only on the client. Additional validation
can also be performed on the client to provide more immediate user feedback.
The Table API provides validation for the following types of constraint:

primary key constraints

unique key constraints

foreign key constraints:

nullify update and delete rules

defaulted update and delete rules

arcs
Generated table handlers and triggers enforce these constraints on the server when the Validate In property
of the constraint is set to Server or Both.
3.2.1
Validation of primary key constraints
When a Table API call is made to update a record in a primary key column, the Update procedure first
checks whether the primary key can be updated. A primary key can be updated if the Update? property of
the primary key constraint is set to Yes. If the primary key can be updated, the record in the primary key
column is updated. If the primary key cannot be updated, an error is raised and, if defined, the exception is
written to an exceptions table.
A pre-update trigger is fired if an attempt is made to update a record in the primary key outside the Table
API.
3.2.2
Validation of unique key constraints
Before a record in a unique key column is updated via the Server API, checks are made to ensure that the
column can be updated and to check whether the column can contain NULL values. A unique key can be
updated if the Update? property of the unique key constraint is set to Yes. The unique key column can
contain NULLs if the column's Optional property is set to Yes. If the column cannot be updated, or if the
column is mandatory (Optional property = No) but no value is provided, an appropriate error is issued and
is written to the associated exceptions table.
A pre-update trigger is fired if an attempt is made to update a record in the unique key outside the Server
API.
3.2.3
Validation of foreign key constraints
When a Table API call is made to update a foreign key column, checks are made to ensure that the column
can be updated and to check whether a value must be provided for the column. If an error is detected, an
appropriate error message is raised and is written to the associated exceptions table, if defined.
Note: Foreign key Restricted and Cascade rules are always enforced on the server as part of the table
structure.
3.2.4
Nullify update and delete rules
If a foreign key constraint is defined with Nullify update or delete rules, and the Validate In property of the
constraint is set to Server or Both, generated pre-update and pre-delete triggers are fired to enforce these
rules on the server.
Nullify on update
Before a row is updated in the parent table, a pre-update trigger is fired which sets the dependent
rows in the foreign key to NULL.
Nullify on delete
Before a row is deleted from the parent table, a pre-delete trigger is fired which sets the dependent
rows in the foreign key to NULL.
3.2.5
Defaulted update and delete rules
If a foreign key constraint is defined with Defaulted update or delete rules, and the Validate In property of
the constraint is set to Server or Both, generated pre-update and pre-delete triggers are fired to enforce
these rules on the server.
Default on update
Before a row is updated in the parent table, a pre-update trigger is fired to set the dependent rows
to the default value.
Default on delete
Before a row is deleted from the parent table, a pre-delete trigger is fired to set the dependent rows
to the default value.
3.2.6
Arc validation
A foreign key can be defined in the Repository as being in an arc. The arc provides a way of defining
mutually exclusive columns whose values depend on the existence of values in another table.
Validation of foreign key arcs is enforced by the Table API using pre-insert and pre-update triggers.
Checks are made to ensure that the arc is valid, that a value is provided in at least one of the columns in the
arc, and that the value provided exists in the referenced primary key column.
An error is raised if the arc definition is invalid or if any of the arc conditions are violated.
3.3
Generating the Table API
You can generate a set of PL/SQL packages, known as table handlers, to perform inserts, updates, deletions
and locks on database tables. When you generate table handlers, you can also generate a set of database
triggers to provide additional validation on the server if a DML statement is issued against the base tables
outside of the calling application.
You can generate table handlers to one of the following targets:
an Oracle database, via a native Oracle SQL*Net connection
an Oracle script file that you can execute at a later stage
Note: You must create the table handlers on the same database as the tables that will be accessed by the
application.
3.3.1
To generate the Table API:
1.
Ensure that the table definitions and associated sequence definitions are stable and complete. If
you subsequently change table and sequence definitions in the Repository, you should regenerate
the Table API.
2.
In the Design Editor, select the Server Model view in the Navigator.
3.
Select one or more Relational Table Definitions for which a table handler is to be generated. At
least one table must be selected.
4.
Choose Generate  Generate Table API.
5.
On the Target tab, choose one of the following generation targets:
6.
7.

File - to generate a script containing the commands to create the table handlers

Oracle - to create the table handlers on an Oracle database
Do one of the following:

If you chose File, enter the name and path of the script to be generated. The names and paths
of previously generated files can be selected from the drop-down list. If you omit the path, the
file is generated to the current working directory.

If you chose Oracle, enter the Username, Password and Connect string to log on to the
database.
To generate database triggers to provide additional validation on the server, ensure that the
Generate Table API Triggers checkbox is selected.
Figure 11 Generating Table API
8.
Select the Objects tab.
9.
Move all tables that require a table handler to the Generate list box.
10.
Select Start.
Once the generation is started, a message window pops up displaying the progress of the generation. If
there are problems with generation then either error messages or warning messages will be displayed. In
either case, no packages will be created.
3.3.2
Warning
Current implementation of the Designer 6 requires you to run the following scripts to enable the generation
of the packages and triggers. Locate on your client machine the following files
c:\orawin95\cgens71\sql\cdsaper.pks
c:\orawin95\cgens71\sql\cdsaper.pkb
These two files contain the SQL scripts for creating packages. These are to be run in the sequence shown
.pks first and .pkb second. The files on an NT machine will be in the Oracle Home Directory, orant. The
scripts must be executed in the account where you have implemented the tables (not where the repository
tables are). To run these scripts, start SQL*Plus and at the prompt, type
START c:\orawin95\cgen71\sql\cdsaper.pks
to create the package definition and
START c:\orawin95\cgens71\sql\cdsaper.pkb
to create the package body. These files contain the definitions and algorithms needed to create all of the
packages and triggers.
Figure 12 Selecting Objects
In our example, we will generate the API directly to the database. We can of course examine the scripts
created by the system should an error or warning is produced during compilation of the API Once the
generation is completed successfully you should see a message window as shown below.
Figure 13 Results Window
If you are generating Form modules whose blocks are based on stored procedures, your next step is to
generate the Module Component API.
3.4
How the Table API maintains denormalized columns
When designing tables, you might decide to denormalize, or duplicate, some columns in order to improve
performance. Denormalization can potentially speed up queries that involve several tables, because the
queried column can be duplicated on a single table, reducing the need to perform a join. More...
The Table API will automatically generate values for a column that is denormalized, provided that the
following conditions are met:
the column Validation property Server Derived is set to Yes
a foreign key constraint is defined between the denormalized tables
If a row is inserted or updated outside of the Table API, pre-insert and pre-update triggers are fired that call
the Table API procedures to maintain the denormalization.