??xml version="1.0" encoding="utf-8" standalone="yes"?> The object of an effective coding style is to make the program more understandable and maintainable. Most programs will benefit from documentation which explains what is going on inside those programs. There are two forms of code documentation: external and internal. External documentation is descriptive information about a program which is written and stored separately from the program itself. Internal documentation, also known as inline documentation or comments, is placed within the program itself, either at the program level or the statement level. (For an introduction to inline documentation and the types of PL/SQL comments, see the section called "Comments" in Chapter 2.)
The best kind of internal documentation derives from your programming style. If you apply many of the guidelines in this chapter and throughout this book, you will be able to write code which is, to a great extent, self-documenting. Here are some general tips:
Do all these things and more, and you will find that you need to write fewer comments to explain your code.
Reducing the need for comments is important. Few developers make or have the time for extensive documentation in addition to their development efforts, and, more importantly, many comments tend to duplicate the code. This raises a maintenance issue because those comments will have to be changed when the code is changed.
While it is my hope that after reading this book you will write more self-documenting code, there is little doubt that you will still need to comment your code. The following example shows the use of single- and multiline comments in PL/SQL:
The first example uses the single-line comment syntax to include endline descriptions for each parameter in the procedure specification. The second example uses a multiline comment to explain the purpose of the FOR loop. The third example uses the double-hyphen to comment out a whole line of code. The last example embeds a comment in the middle of a line of code using the block comment syntax.
These two types of comments offer the developer flexibility in how to provide inline documentation. The rest of this section offers guidelines for writing effective comments in your PL/SQL programs.
It is very difficult to make time to document your code after you have finished writing your program. Psychologically, you want to (and often need to) move on to the next programming challenge after you get a program working.
You may also have a harder time writing your comments once you have put some distance between your brain cells and those lines of code. Why exactly did you write the loop that way? Where precisely is the value of that global variable set? Unless you have total recall, post-development documentation can be a real challenge.
The last and perhaps most important reason to write your comments as you write your code is that the resulting code will have fewer bugs and (independent of the comments themselves) be easier to understand.
When you write a comment you (theoretically) explain what your code is meant to accomplish. If you find it difficult to come up with that explanation, there is a good chance that you lack a full understanding of what the program does or should do.
The effort that you make to come up with the right comment will certainly improve your comprehension, and may also result in code correction. In this sense, good inline documentation can be as beneficial as a review of your code by a peer. In both cases, the explanation will reveal important information about your program.
What do you think of the comments in the following Oracle Forms trigger code?
None of these comments add anything to the comprehension of the code. Each comment simply restates the line of code, which in most cases is self-explanatory.
Avoid adding comments simply so that you can say, "Yes, I documented my code!" Rely as much as possible on the structure and layout of the code itself to express the meaning of the program. Reserve your comments to explain the Why of your code: What business rule is it meant to implement? Why did you need to implement a certain requirement in a certain way?
In addition, use comments to translate internal, computer-language terminology into something meaningful for the application. Suppose you are using Oracle Forms GLOBAL variables to keep track of a list of names entered. Does the following comment explain the purpose of the code or simply restate what the code is doing?
Once again, the comment adds no value. Does the next comment offer additional information?
This comment actually explains the purpose of the assignment of the global to zero. By setting the number of elements to zero, I will have effectively emptied the list. This comment has translated the "computer lingo" into a description of the effect of the statement. Of course, you would be even better off hiding the fact that you use this particular global variable to empty a list and instead build a procedure as follows:
PROCEDURE empty_list IS
BEGIN
:GLOBAL.num_elements := 0;
Then to empty a list you would not need any comment at all. You could simply include the statement:
and the meaning would be perfectly clear.
You shouldn't spend a lot of time formatting your comments. You need to develop a style that is clean and easy to read, but also easy to maintain. When you have to change a comment, you shouldn't have to reformat every line in the comment. Lots of fancy formatting is a good indication that you have a high-maintenance documentation style. The following block comment is a maintenance nightmare:
The right-justified vertical lines and column formatting for the parameters require way too much effort to enter and maintain. What happens if you add a parameter with a very long name? What if you need to write a longer description? A simpler and more maintainable version of this comment might be:
I like to use the following format for my block comments:
|| vertical bar to highlight the presence of the comment. Finally,
|| I place the asterisk-slash on a line all by itself.
On the negative side, the vertical bars have to be erased whenever I reformat the lines, but that isn't too much of an effort. On the positive side, those vertical bars make it very easy for a programmer who is scanning the left side of the code to pick out the comments.
I put the comment markers on their own lines to increase the whitespace in my program and set off the comment. That way I can avoid "heavy" horizontal lines full of delimiters, such as asterisks or dashes, and avoid having to match the longest line in the comment.
Inline commentary should reinforce the indentation and therefore the logical structure of the program. For example, it is very easy to find the comments in the make_array procedures shown below. I do not use any double-hyphens, so the slash-asterisk sequences stand out nicely. In addition, all comments start in the first column, so I can easily scan down the left-hand side of the program and pick out the documentation:
END LOOP;
The problem with these comments is precisely that they do all start in the first column, regardless of the code they describe. The most glaring example of this formatting "disconnect" comes in the inner loop, repeated below:
Your eye follows the three-space indentation very smoothly into the loop and then you are forced to move all the way to the left to pick up the comment. This format disrupts your reading of the code and therefore its readability. The code loses some of its ability to communicate the logical flow "at a glance," because the physical sense of indentation as logical flow is marred by the comments. Finally, you may end up writing full-line comments which are much longer than the code they appear next to, further distorting the code.
Your comments should always be indented at the same level as the code which they describe. Assuming the comments come before the code itself, those lines of descriptive text will initiate the indentation at that logical level, which will also reinforce that structure. The make_array procedure, properly indented, is shown below:
END LOOP;
END LOOP;
I propose the following simple rule for documenting declaration statements:
Does that sound excessive? Well, I must admit that I do not follow this guideline at all times, but I bet people who read my code wish I had. The declaration of a variable which seems to me to be perfectly clear may be a source of abiding confusion for others. Like many other people, I still have difficulty understanding that what is obvious to me is not necessarily obvious to someone else. Consider the declaration section in the next example. The commenting style is inconsistent. I use double-hyphens for a two-line comment; then I use the standard block format to provide information about three variables all at once. I provide comments for some variables, but not for others. It's hard to make sense of the various declaration statements: Let's recast this declaration section using my proposed guideline: a comment for each declaration statement. In the result shown below, the declaration section is now longer than the first version, but it uses whitespace more effectively. Each declaration has its own comment, set off by a blank line if a single-line comment:
PROCEDURE calc_totals (company_id IN NUMBER,--The company key
total_type IN VARCHAR2--ALL or NET
);
/*
|| For every employee hired more than five years ago,
|| give them a bonus and send them an e-mail notification.
*/
FOR emp_rec IN emp_cur (ADD_MONTHS (SYSDATE, -60))
LOOP
apply_bonus (emp_rec.employee_id);
send_notification (emp_rec.employee_id);
END LOOP;
-- IF :SYSTEM.FORM_STATUS = 'CHANGED' THEN COMMIT; END IF;
FUNCTION display_user
(user_id IN NUMBER /* Must be valid ID */, user_type IN VARCHAR2)
Comment As You Code
Explain the Why--Not the How--of Your Program
-- If the total compensation is more than the maximum...
IF :employee.total_comp > maximum_salary
THEN
-- Inform the user of the problem.
MESSAGE ('Total compensation exceeds maximum. Please re-enter!');
-- Reset the counter to zero.
:employee.comp_counter := 0;
-- Raise the exception to stop trigger processing.
RAISE FORM_TRIGGER_FAILURE;
END IF;
/* Set the number of elements to zero. */
:GLOBAL.num_elements := 0;
/* Empty the list of names. */
:GLOBAL.num_elements := 0;
END;
empty_list;
Make Comments Easy to Enter and Maintain
/*
===========================================================
| Parameter Description |
| |
| company_id The primary key to company |
| start_date Start date used for date range |
| end_date End date for date range |
===========================================================
*/
/*
===========================================================
| Parameter - Description
|
| company_id - The primary key to company
| start_date - Start date used for date range
| end_date - End date for date range
===========================================================
*/
/*
|| I put the slash-asterisk that starts the comment on a line all by
|| itself. Then I start each line in the comment block with a double
*/
Maintain Indentation
PROCEDURE make_array (num_rows_in IN INTEGER)
/* Create an array of specified numbers of rows */
IS
/* Handles to Oracle Forms structures */
col_id GROUPCOLUMN;
rg_id RECORDGROUP;
BEGIN
/* Create new record group and column */
rg_id := CREATE_GROUP ('array');
col_id := ADD_GROUP_COLUMN ('col');
/*
|| Use a loop to create the specified number of rows and
|| set the value in each cell.
*/
FOR row_index IN 1 .. num_rows_in
LOOP
/* Create a row at the end of the group to accept data */
ADD_GROUP_ROW (return_value, END_OF_GROUP);
FOR col_index IN 1 .. num_columns_in
LOOP
/* Set the initial value in the cell */
SET_GROUP_NUMBER_CELL (col_id, row_index, 0);
END LOOP;
END;
FOR col_index IN 1 .. num_columns_in
LOOP
/* Set the initial value in the cell */
SET_GROUP_NUMBER_CELL (col_id, row_index, 0);
END LOOP;
PROCEDURE make_array (num_rows_in IN INTEGER)
/* Create an array of specified numbers of rows */
IS
/* Handles to Oracle Forms structures */
col_id GROUPCOLUMN;
rg_id RECORDGROUP;
BEGIN
/* Create new record group and column */
rg_id := CREATE_GROUP ('array');
col_id := ADD_GROUP_COLUMN ('col');
/*
|| Use a loop to create the specified number of rows and
|| set the value in each cell.
*/
FOR row_index IN 1 .. num_rows_in
LOOP
/* Create a row at the end of the group to accept data */
ADD_GROUP_ROW (return_value, END_OF_GROUP);
FOR col_index IN 1 .. num_columns_in
LOOP
/* Set the initial value in the cell */
SET_GROUP_NUMBER_CELL (col_id, row_index, 0);
END;
Comment Declaration Statements
Provide a comment for each and every declaration.
DECLARE
-- Assume a maximum string length of 1000 for a line of text.
text_line VARCHAR2 (1000);
len_text NUMBER;
/*
|| Variables used to keep track of string scan:
|| atomic_count - running count of atomics scanned.
|| still_scanning - Boolean variable controls WHILE loop.
*/
atomic_count NUMBER := 1;
still_scanning BOOLEAN;
BEGIN
DECLARE
/* Assume a maximum string length of 1000 for a line of text. */
text_line VARCHAR2 (1000);
/* Calculate length of string at time of declaration */
len_string NUMBER;
/* Running count of number of atomics scanned */
atomic_count NUMBER := 1;
/* Boolean variable that controls WHILE loop */
still_scanning BOOLEAN ;
BEGIN
]]>
table level triggers: 是table改变Ӟ触发trigger。无论几个row改变都没影响, 比如Q?个row update触发1?,Q个row updateQ也触发1ơ?br />
Z转个教程
Before / for each row trigger
:new.field_name
) are stored in the table. That means that the new value can be changed in the trigger. create table t_update_before_each_row (
txt varchar2(10)
);
create table log (
txt varchar2(20)
);
create trigger update_before_each_row
before update on t_update_before_each_row
for each row
begin
:new.txt := upper(:new.txt);
insert into log values ('old: ' || :old.txt);
insert into log values ('new: ' || :new.txt);
end update_before_each_row;
/
insert into t_update_before_each_row values('one');
insert into t_update_before_each_row values('two');
insert into t_update_before_each_row values('three');
insert into t_update_before_each_row values('four');
update t_update_before_each_row set txt = txt || txt
where substr(txt,1,1) = 't';
select * from t_update_before_each_row;
one
TWOTWO
THREETHREE
four
select * from log;
old: two
new: TWOTWO
old: three
new: THREETHREE
drop table t_update_before_each_row;
drop table log;
After / for each row trigger
:new.field_name
because the value is, when the trigger fires, already written to the table. :new.field_name
, Oracle throws an ORA-04084: cannot change NEW values for this trigger type. create table t_update_after_each_row (
txt varchar2(10)
);
create table log (
txt varchar2(20)
);
create trigger update_after_each_row
after update on t_update_after_each_row
for each row
begin
-- :new.txt := upper(:old.txt); -- ORA-04084: cannot change NEW values for this trigger type
insert into log values ('old: ' || :old.txt);
insert into log values ('new: ' || :new.txt);
end update_after_each_row;
/
insert into t_update_after_each_row values('one');
insert into t_update_after_each_row values('two');
insert into t_update_after_each_row values('three');
insert into t_update_after_each_row values('four');
update t_update_after_each_row set txt = txt || txt
where substr(txt,1,1) = 't';
select * from t_update_after_each_row;
one
twotwo
threethree
four
select * from log;
:new
and :old
although it's not possible to assign something to :new
. old: two
new: twotwo
old: three
new: threethree
drop table t_update_after_each_row;
drop table log;
Table level trigger
for each row
. Consequently, both, the :new
and :old
are not permitted in the trigger's PL/SQL block, otherwise, an ORA-04082: NEW or OLD references not allowed in table level triggers is thrown. create table t_update_before (
txt varchar2(10)
);
create table log (
txt varchar2(20)
);
create trigger update_before
before update on t_update_before
begin
-- :new.txt := upper(:old.txt); -- ORA-04082
insert into log values ('update trigger');
end update_before;
/
insert into t_update_before values('one');
insert into t_update_before values('two');
insert into t_update_before values('three');
insert into t_update_before values('four');
update t_update_before set txt = txt || txt
where substr(txt,1,1) = 't';
select * from t_update_before;
one
twotwo
threethree
four
select * from log;
update trigger
update t_update_before set txt = txt || txt
where txt = 'no update';
select * from log;
update trigger
update trigger
drop table t_update_before;
drop table log;
Order of execution
]]>
正确格式?
可以用两U方式创?span>MySQL账户Q?/p>
· 使用GRANT语句
· 直接操作MySQL授权?/p>
最好的Ҏ(gu)是?span>GRANT语句Q因h_Q错误少。从MySQL 3.22.11h供了(jin)GRANTQ其语法?a title="13.5.1.3. GRANT and REVOKE Syntax" >13.5.1.3节,“GRANT和REVOKE语法”?/p>
创徏账户的其它方法是使用MySQL账户理功能的第三方E序?span>phpMyAdminx(chng)一个程序?/p>
下面的示例说明如何?strong>MySQL客户端程序来讄新用戗假定按?a title="2.9.3. Securing the Initial MySQL Accounts" >2.9.3节,“使初始MySQL账户安全”描述?默认值来讄权限。这说明Z(jin)更改Q你必须?span>MySQL root用户q接MySQL服务器,q且root账户必须?span>mysql数据库的INSERT权限?span>RELOAD理权限?/p>
首先Q?strong>MySQLE序?span>MySQL root用户来连接服务器Q?/p>
shell> MySQL --user=root MySQL
如果你ؓ(f)root账户指定?jin)密码,q需要ؓ(f)?strong>MySQL命o(h)和本节中的其它命令提?span>--password?span>-p选项?/p>
?span>rootq接到服务器上后Q可以添加新账户。下面的语句使用GRANT来设|四个新账户Q?/p>
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost'
-> IDENTIFIED BY 'some_pass' WITH GRANT OPTION;
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%'
-> IDENTIFIED BY 'some_pass' WITH GRANT OPTION;
mysql> GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
mysql> GRANT USAGE ON *.* TO 'dummy'@'localhost';
?span>GRANT语句创徏的̎h下面的属性:(x)
· 其中两个账户有相同的用户?span>monty和密?span>some_pass。两个̎户均U用戯̎Ph完全的权限可以做M事情。一个̎?span> ('monty'@'localhost')只用于从本机q接时。另一个̎?span>('monty'@'%')可用于从其它Lq接。请注意monty的两个̎户必能从Q何主Zmontyq接。没?span>localhost账户Q当monty从本接时Q?strong>mysql_install_db创徏?span>localhost的匿名用戯̎户将占先。结果是Q?span>monty被视ؓ(f)匿名用户。原因是匿名用户账户?span>Host列值比'monty'@'%'账户更具体,q样?span>user表排序顺序中排在前面?span>(user表排序的讨论参见5.7.5节,“讉K控制, 阶段1Q连接核?#8221;Q?span>?
· 一个̎h用户?span>adminQ没有密码。该账户只用于从本机q接。授予了(jin)RELOAD?span>PROCESS理权限。这些权限允?span>admin用户执行mysqladmin reload?strong>mysqladmin refresh?strong>mysqladmin flush-xxx命o(h)Q以?strong>mysqladmin processlist。未授予讉K数据库的权限。你可以通过GRANT语句d此类权限?/p>
· 一个̎h用户?span>dummyQ没有密码。该账户只用于从本机q接。未授予权限。通过GRANT语句中的USAGE权限Q你可以创徏账户而不授予M权限。它可以所有全局权限设ؓ(f)'N'。假定你在以后具体权限授予该账户?/p>
除了(jin)GRANTQ你可以直接?span>INSERT语句创徏相同的̎P然后使用FLUSH PRIVILEGES告诉服务器重载授权表Q?/p>
shell> mysql --user=root mysql
mysql> INSERT INTO user
-> VALUES('localhost','monty',PASSWORD('some_pass'),
-> 'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO user
-> VALUES('%','monty',PASSWORD('some_pass'),
-> 'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO user SET Host='localhost',User='admin',
-> Reload_priv='Y', Process_priv='Y';
mysql> INSERT INTO user (Host,User,Password)
-> VALUES('localhost','dummy','');
mysql> FLUSH PRIVILEGES;
当你?span>INSERT创徏账户时?span>FLUSH PRIVILEGES的原因是告诉服务器重L权表。否则,只有重启服务器后更改方会(x)被注意到。?GRANTQ则不需要?span>FLUSH PRIVILEGES?/p>
?span>INSERT使用PASSWORD()函数是ؓ(f)?jin)加密密码?span>GRANT语句Z加密密码Q因此不需?span>PASSWORD()?/p>
'Y'值启用̎h限。对?span>admin账户Q还可以使用更加可读?span>INSERT扩充的语法(使用SETQ?/p>
在ؓ(f)dummy账户?span>INSERT语句中,只有user表中?span>Host?span>User?span>Password列记录ؓ(f)指定的倹{没有一个权限列为显式设|,因此MySQL它们均指定?默认?span>'N'。这L(fng)同于GRANT USAGE的操作?/p>
h意要讄用户账户Q只需要创Z个权限列讄?span>'Y'?span>user表条目?span>user表权限ؓ(f)全局权限Q因此其?授权表不再需要条目?/p>
下面的例子创?span>3个̎P允许它们讉K专用数据库。每个̎L(fng)用户名ؓ(f)customQ密码ؓ(f)obscure?/span>
要想?span>GRANT创徏账户Q用下面的语句Q?/p>
shell> MySQL --user=root MySQL
shell> mysql --user=root mysql
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
-> ON bankaccount.*
-> TO 'custom'@'localhost'
-> IDENTIFIED BY 'obscure';
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
-> ON expenses.*
-> TO 'custom'@'whitehouse.gov'
-> IDENTIFIED BY 'obscure';
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
-> ON customer.*
-> TO 'custom'@'server.domain'
-> IDENTIFIED BY 'obscure';
q?span>3个̎户可以用于:(x)
· W?span>1个̎户可以访?span>bankaccount数据库,但只能从本机讉K?/p>
· W?span>2个̎户可以访?span>expenses数据库,但只能从Lwhitehouse.gov讉K?/p>
· W?span>3个̎户可以访?span>customer数据库,但只能从Lserver.domain讉K?/p>
要想不用GRANT讄custom账户Q?span>INSERT语句直接修改 授权表:(x)
shell> mysql --user=root mysql
mysql> INSERT INTO user (Host,User,Password)
-> VALUES('localhost','custom',PASSWORD('obscure'));
mysql> INSERT INTO user (Host,User,Password)
-> VALUES('whitehouse.gov','custom',PASSWORD('obscure'));
mysql> INSERT INTO user (Host,User,Password)
-> VALUES('server.domain','custom',PASSWORD('obscure'));
mysql> INSERT INTO db
-> (Host,Db,User,Select_priv,Insert_priv,
-> Update_priv,Delete_priv,Create_priv,Drop_priv)
-> VALUES('localhost','bankaccount','custom',
-> 'Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO db
-> (Host,Db,User,Select_priv,Insert_priv,
-> Update_priv,Delete_priv,Create_priv,Drop_priv)
-> VALUES('whitehouse.gov','expenses','custom',
-> 'Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO db
-> (Host,Db,User,Select_priv,Insert_priv,
-> Update_priv,Delete_priv,Create_priv,Drop_priv)
-> VALUES('server.domain','customer','custom',
-> 'Y','Y','Y','Y','Y','Y');
mysql> FLUSH PRIVILEGES;
?span>3?span>INSERT语句?span>user表中加入条目Q允许用?span>custom从各U主机用l定的密码进行连接,但不授予全局权限(所有权限设|ؓ(f) 默认?span>'N')。后?span>3?span>INSERT语句?span>user表中加入条目Qؓ(f)custom授予bankaccount?span>expenses?span>customer数据库权限,但只能从合适的L讉K?span>通常若直接修?授权表,则应告诉服务器用FLUSH PRIVILEGES重蝲授权表,使权限更改生效?/span>
如果你想要让某个用户从给定域的所有机器访?span>(例如Q?/span>mydomain.com)Q你可以在̎户名的主机部分用含‘%’通配W的GRANT语句Q?/span>
mysql> GRANT ...
-> ON *.*
-> TO 'myname'@'%.mydomain.com'
-> IDENTIFIED BY 'mypass';
要想通过直接修改授权表来实现Q?/p>
mysql> INSERT INTO user (Host,User,Password,...)
-> VALUES('%.mydomain.com','myname',PASSWORD('mypass'),...);
mysql> FLUSH PRIVILEGES;