Introduction to Database System (Chapter 5)-Database Integrity

The integrity of the database refers to the correctness and compatibility of the database. Correctness means that it conforms to the semantics of the real world and reflects the current actual situation; data compatibility means that the data of the same object in the database in different relational tables is logical. The integrity of the database is to prevent incorrect data in the database, and the security of the database is to prevent malicious destruction and illegal acquisition.

In order to maintain the integrity of the database, the database management system must be able to achieve the following functions:

  • Provide a mechanism for defining integrity constraints
  • Provide integrity check method
  • Proceed with breach of contract

1. Entity integrity

Define entity integrity

Defining entity integrity means setting the primary key for the table, that is, defining the primary key when creating the table.
example

-- 第一种 列级定义
create table table_name(
	id int primary key,
	name varchar(10),
	address varchar(50)
)
-- 第二种(可以定义多个)  表级定义
create table table_name(
	id int,
	name varchar(10),
	primary key(id,name)
)

Add a primary key to an existing table

alter table_name add constraint pk_table_name primary key('field')

Entity integrity check and default handling

After primary keydefining the main code of the relationship with a phrase, whenever the user program inserts or modifies the corresponding data operation on the basic table, the relational database system will perform the following checks in accordance with the entity integrity:

  • Check if the main code is unique, if not, refuse to insert or modify
  • Check whether each attribute of the main code is empty, as long as one is empty, refuse to insert or modify (this personal feeling is not like the current database, like SQL defines a non-empty constraint, if it is empty, it refuses to insert or modify)

The only way to check whether the master code is to scan the entire disk and check the master code of each record in turn. However, a full table scan is very time-consuming. In order to avoid a full scan, the relational database system generally automatically builds an index on the master code (such as a B+ tree index). It will greatly improve whether the master code already exists in the lookup table through the index. effectiveness.

2. Referential integrity

Define referential integrity

Defining referential integrity is actually adding foreign key constraints to the table. Use foreign keyphrases to define which classes are foreign codes, and use referencesphrases to indicate which table of main code
examples these foreign codes refer to .

create table table course(
	id int primary key,
	name varchar(10)
)
create table stu(
	id int not null,
	name varchar(10),
	cId int,
	foreign key(cId) references course(id)
)

Add a foreign key to an existing table

create table table course(
	id int primary key,
	name varchar(10)
)
create table stu(
	id int not null,
	name varchar(10),
	cId int
)
alter table stu add constraint stu_cId_fk_course_id foreign key(cId) references course(id)

Referential integrity check and illegal handling

Referential integrity links the corresponding tuples in the two tables. Therefore, adding, deleting, or modifying the referenced table and the reference table may destroy the referential integrity, so checks must be performed to ensure the compatibility of the two tables.
Taking the above creation of definition integrity as an example (stu is the reference table, course is the referenced table), there may be four situations that may destroy referential integrity:

  • A student is added to the student table (stu), but the course the student has learned is not in the course table.
  • Modify the course Cid in the student table (stu), but the course table (course) does not have a corresponding id
  • Delete a course in the course table, causing the Cid in the student table to have no id equal to it in the course table.
  • Modify the id of the course table so that the Cid in the student table does not have the same id in the course table.

When the above-mentioned situations occur, the system can adopt the following strategies to deal with:

  • Reject ( NO ACTION) execution: the default strategy
  • Cascading ( CASCADE) operation
    When deleting or modifying a tuple of the referenced table (course) results in inconsistency with the reference table (stu), delete or modify all inconsistent tuples in the reference table.
  • Set to a null value
    When deleting or a source of the referenced table (course) causes inconsistency with the reference table (stu), set all inconsistent attributes in the reference table to a null value.

For referential integrity, in addition to defining the outer code, it should also define whether the outer code is allowed to be null

3. User-defined completeness

User-defined integrity is a semantic requirement that the data for a specific application must meet.

Attribute constraints

While create tabledefining attributes in, you can define constraints on attributes according to requirements, that is, attribute value restrictions. Generally, there are:

  • Column value is not null (not null)
  • The column value is unique (unique)
  • Check whether the column value meets a certain conditional expression (check phrase, mysql does not support)

Constraints on tuples

Similar to the constraint condition of the attribute, the create tablecheck phrase is used in the sentence to define the constraint condition on the tuple.

Example. Define the student table, when the student is "male", its name cannot start with "Ms".

create table stu(
	id int,
	name varchar(20),
	sex char(2),
	check(sex='女' OR name not like 'Ms.%')
)

4. Integrity constraint naming clause

The integrity naming clause is actually the use of CONSTRAINTkeywords to define integrity constraints.

Integrity naming clause

CONSTRAINT <完整性约束条件名> <完整性约束条件>

Integrity constraints include NOT NULL, UNIQUE, PRIMARY KEY,FOREIGN KEY

Example. To create a student registration form stu, the student ID is required to be between 90000 and 99999, the name cannot be empty, the age is less than 40, and the gender can only be "male" or "female"

create table stu(
	sno int constraint c1 check(sno between 90000 and 99999),
	sname char(20) constraint c2 check not null,
	sage int constraint c3 check(sage<40),
	sex char(2) constraint c4 check(sex in("男","女")),
	constraint pk_stu primary key(sno)
)

Modify the integrity restrictions in the table

Modifying the integrity restriction in the table means deleting the restriction or adding the restriction.

Remove restrictions
alter table stu drop constraint c4 
Add restriction
alter table add constraint c4 check(sex in("男","女"))

It should be noted that mysql does not support check constraints, If you want to use checkconstraints, please use Sqlserver or other relational databases.

5. Integrity restrictions in the domain

Generally, a domain is a group of collections with the same data type. SQL supports the concept of domains. You can use CREATE DOMAINstatements to establish a domain and the integrity constraints that the domain satisfies.
Create a domain and declare the value range of the domain:

CREATE DOMAIN generderDomain char(2) constraint gd check(value in ("男","女"))

Use the domain created above when creating the table:

create table stu(
	id int,
	name varchar(10),
	sex generderDomain 
)

6. Affirmation

In SQLmay be used database definition language CREATE ASSERTIONstatements to specify more general assertion by declarative constraint. It can be simply understood as a check and judgment before an operation is executed. If the result is true, it can be executed, and if the result is false, the execution is rejected.

Create assertion

create ASSERTION <断言名> <check 子句>

Example. Limit the database courses to 60 students as electives

create ASSERTION ASSE_SC_DB_NUM
CHECK(60>=(select count(*) from Course,Sc where Sc.no = course.cno and course.cname = '数据库'))

Here Scis the table of the relationship between students and course selection, Coursethe course table, and nothe student ID

Delete assertion

DROP ASSERTION  <断言名>

If the assertion is very complex, the system has a higher overhead in detecting and maintaining the assertion, which should be paid attention to in the use of assertions (mysql does not support assertions for the time being).

7. Trigger

A trigger is a special event-driven process defined by the user on the relational table. Once defined, the trigger will be stored in the database server. The server automatically activates the corresponding triggers for any user's addition, deletion, and modification operations, and centralized integrity control is performed at the core layer of the relational database system. Triggers are similar to constraints, but are more flexible than constraints, and can implement more complex checks and operations.
Triggers were written into the SQL standard after SQL 99, but many relational databases have supported triggers a long time ago, soDifferent relational databases have different grammars for triggers, which are complementary and compatible

Define trigger

Triggers are also called event-condition-action rules. When a specific system event occurs, the conditions of the rules are checked, and if the conditions are met
, the actions in the rules are executed , otherwise the actions are not executed.

grammar:
 CREATE TRIGGER <触发器名>    
       {BEFORE | AFTER} <触发事件> ON <表名>    --指明触发器激活事件是执行触发事件的前或后
       REFERENCING NEW|OLD ROW AS<变量>   -- REFERENCING 指出引用的变量
       FOR EACH  {ROW | STATEMENT}					-- 定义触发器的类型,指明动作执行的频率
       [WHEN <触发条件>]<触发动作体>
Grammar description
  • Only the owner of the table, that is, the user who created the table, can create triggers, and a table can only create a certain number of issuers.
  • Trigger name The
    trigger name can contain the pattern name or not. In the same mode, the trigger name must be unique, and the trigger name and table name must be in the same mode.
  • Table name
    Triggers can only be defined on the base table, not on the view. When the data of the basic table changes, the corresponding trigger defined on the table will be activated, so the table is also called the target table of the trigger.
  • Trigger events
    triggering event may be INSET, , DELETE, UPDATEit may be a combination of these events. It can also be UPDATE OF<trigger column, …>, that is, it further specifies which columns are modified to activate the trigger. BEFORE | AFTERIt is the timing of the trigger, which AFTERmeans that the activator is triggered after the operation that triggers the event is executed, and the trigger is activated BEFOREbefore the triggering event is executed.
  • Trigger type
    Triggers can be divided into row-level triggers (FOR EACH ROW) and statement-level triggers (FOR EACH STATEMENT) according to the interval size of the triggered actions.

Example. Create an AFTER UPDATE trigger on the TEACHER table. The trigger event is an UPDATE statement:
UPDATE TEACHER SET Deptno=5;
Assuming that the table TEACHER has 1000 rows.
If it is a statement-level trigger, then after the statement is executed, the trigger action only occurs Once
if it is a row-level trigger, the trigger action will be executed 1000 times

  • Trigger condition When the
    trigger is activated, the trigger action body will only be executed when the trigger condition is true, otherwise it will not be executed. If omitted when, the trigger body will be executed immediately when the trigger is activated.
  • Trigger action body The
    trigger action body can be either an anonymous PL/SQLprocess block or a call to a created stored procedure. If it is a row-level trigger, the user can use NEWand OLDreference the new value after the event and the old value before the event in the procedure body ; if it is a statement-level trigger, it cannot be used NEWor OLDreferenced in the trigger action body ; if triggered If the execution of the action body fails, the event that activates the trigger will terminate execution, and the target table of the trigger or other objects that the trigger may affect will not change.

Example 1. When modifying the Grade attribute of table SC, if the score increases by 10%, record this operation in the following table:
SC_U (Sno, Cno, Oldgrade, Newgrade)
where Oldgrade is the score before modification, Newgrade Is the revised score.

CREATE TRIGGER  SC_T							--创建触发器,触发器名SC_T
	AFTER UPDATE OF Grade ON SC		-- 触发事件的操作执行之后激活触发器,即表SC的grade属性修改后再触发下面的规则
     REFERENCING										--新值和旧值
	      OLD row  AS  OldTuple,
	      NEW row AS  NewTuple
	FOR EACH ROW 									-- 触发器类型为行级触发器
	WHEN (NewTuple.Grade >= 1.1*OldTuple.Grade)		-- 触发条件
	    INSERT INTO SC_U(Sno,Cno,OldGrade,NewGrade)    --触发动作体插入操作
VALUES(OldTuple.Sno,OldTuple.Cno,OldTuple.Grade,NewTuple.Grade)

Row-level triggers (FOR EACH ROW) can use OLD and NEW to refer to new and old values, If it is not a row-level trigger, you can use NEWTABLEand OLDTABLEto represent the original content and the new content.

The following two examples apply to mysql:

Create a trigger with only one execution statement
CREATE TRIGGER 触发器名 BEFORE|AFTER 触发事件 ON 表名 FOR EACH ROW 执行语句;

For example, a trigger named trig1 is created. Once there is an insert action in the work table, it will automatically insert the current time into the time table

CREATE TRIGGER trig1 AFTER INSERT
ON work FOR EACH ROW
INSERT INTO time VALUES(NOW());
Create a trigger with multiple execution statements
CREATE TRIGGER 触发器名 BEFORE|AFTER 触发事件
ON 表名 FOR EACH ROW
BEGIN
        执行语句列表
END;

Example, define a trigger, once there is a delete operation that meets the conditions, the statements in BEGIN and END will be executed

CREATE TRIGGER trig2 BEFORE DELETE
ON work FOR EACH ROW
BEGIN
  INSERT INTO time VALUES(NOW());
   INSERT INTO time VALUES(NOW());
 END

Activation trigger

The execution of the trigger is activated by the trigger event and executed automatically by the database server. There may be one or more triggers on a data table. When they are activated, they follow the following execution sequence:

  • Execute the BEFOREtrigger on the table
  • The SQLstatement that activates the trigger
  • Execute the AFTERtriggers on the table.
    Generally speaking, if there are multiple BEFOREtriggers on a table , then the execution order rule is "who creates first, who executes first". But some relational databases execute triggers in alphabetical order of trigger names.

Delete trigger

The syntax is as follows:

DROP TRIGGER <触发器名> ON <表名>

The trigger must be an already created trigger and can only be deleted by a user with corresponding permissions.

Guess you like

Origin blog.csdn.net/qq_41262903/article/details/106116473