Как физическая, так и логическая целостность часто имеют много общих проблем, таких как человеческие ошибки и недостатки проектирования, и оба должны соответствующим образом обрабатывать параллельные запросы на запись и извлечение данных, последний из которых является полностью самостоятельной темой.
Если в секторе данных есть только логическая ошибка, его можно использовать повторно, перезаписав его новыми данными. В случае физической ошибки затронутый сектор данных навсегда становится непригодным для использования.
Базы данных
Типы ограничений целостности
Целостность данных обычно обеспечивается в системе баз данных с помощью ряда ограничений или правил целостности. Три типа ограничений целостности являются неотъемлемой частью реляционной модели данных: целостность объекта, ссылочная целостность и целостность домена.
Если база данных поддерживает эти функции, она несет ответственность за обеспечение целостности данных, а также за модель согласованности для хранения и извлечения данных. Если база данных не поддерживает эти функции, приложения несут ответственность за обеспечение целостности данных, в то время как база данных поддерживает модель согласованности для хранения и поиска данных.
Наличие единой, хорошо контролируемой и четко определенной системы целостности данных увеличивает
Современные базы данных поддерживают эти функции (см. Сравнение систем управления реляционными базами данных ), и де-факто ответственность за обеспечение целостности данных стала возложена на базу данных. Компании и многие системы баз данных предлагают продукты и услуги для переноса устаревших систем на современные базы данных.
Примеры
Примером механизма целостности данных являются отношения между родителями и потомками связанных записей. Если родительская запись владеет одной или несколькими связанными дочерними записями, все процессы ссылочной целостности обрабатываются самой базой данных, что автоматически обеспечивает точность и целостность данных, так что ни одна дочерняя запись не может существовать без родительской записи (также называемой осиротевшей) и что ни один родитель не теряет свои дочерние записи. Это также гарантирует, что никакая родительская запись не может быть удалена, пока родительская запись владеет какими-либо дочерними записями. Все это обрабатывается на уровне базы данных и не требует проверки целостности кода в каждом приложении.
Файловые системы
Это магическое словосочетание — Data Integrity
Если не у всех, то у очень многих сейчас на слуху это чарующее воображение словосочетание Data Integrity- целостность данных. Это интуитивно осознаваемое понятие стремительно ворвалось в фармацевтический обиход по мере выхода в последние годы достаточно большого количества руководств, посвященных этому вопросу:
В феврале 2019-го появилось русскоязычное Руководство по Целостности данных и валидации компьютеризированных систем от ГИЛС и НП, разработанное при участии специалистов PQE. Это уникальный в своём роде русскоязычный документ (ведь все остальные документы, упоминаемые в этом контексте, англоязычные и/или зарубежного происхождения). Помимо целостности данных это Руководство увязывает описанное словосочетание, собственно, с валидацией компьютеризированных систем, потому что трудно представить эти понятия в отрыве.
Нет, я, конечно, замечу, что понятие «целостность данных» в фарма касается в т.ч. и бумажных документов. Вместе с тем, позволю себе два оценочных суждения: 1) целостность данных в бумажном виде – это то, к чему нужно стремиться, но на практике это практически утопия, если подходить к этому вопросу со всей строгостью и пытаться с доказательной базой наперевес продемонстрировать следование принципам ALCOA & ALCOA+; 2) число программных решений в рамках автоматизации бизнес-процессов почти ультимативно выводит нас на обсуждение целостности данных в разрезе компьютеризированных систем и их валидации. Так что Руководство ГИЛС и НП появилось очень своевременно и сгруппировано оно весьма полезным образом. Ведь если брать зарубежные аналоги, они ведь лишь дополняют разного рода базовые руководства калибра GAMP 5, PIC/S, OECD, EDQM и т.п.
Адресуясь к этому Руководству, хочу затронуть лишь один, достаточно инновационный аспект. Принципы ALCOA & ALCOA + таковыми в нашем стремительно меняющемся мире уже не являются. Именно они как раз и понимаются интуитивно и, по сути, лишь консолидируют требования GMP на этот счет, «размазанные тонким слоем» по всему тексту GMP. Ведь Прослеживаемость (Attributable), Читаемость (Legible), Своевременность (Contemporaneous), Подлинность (Original) и Точность (Accurate)), а также (Полнота (Complete), Последовательность (Consistent), Устойчивость (Enduring) и Доступность (Available) – это и есть составляющие вышеупомянутых акронимов, смысл которых раскрыт не только в Руководстве, но и в ряде других, предшествующих ему документов.
Мне, как автору данного очерка, гораздо более серьезным показался следующий пассаж в Руководстве, возникший, впрочем, не случайно, а присутствующей в т.ч. в новейшем Руководстве по целостности данных от MHRA. Это акроним DIRA (dataintegrityriskassessment). В эпоху, когда только ленивый не упоминает об оценке рисков к месту и не к месту, данный пункт (6.2 Руководства ГИЛС и НП) можно воспринять, как дежурный. Однако вчитаемся в следующую фразу:
Примером приемлемого подхода является оценка риска целостности данных (data integrity risk assessment — DIRA), при которой процессы, производящие данные, или в результате которых получены данные, картируются, критические воздействия идентифицируются, а присущие риски документируются
Что же подразумевается под «картированием процессов»? Кто-то ясно себе представляет, как это будет выглядеть на практике? В MHRA изложено тоже самое практически буквально:
An example of a suitable approach is to perform a data integrity risk assessment (DIRA) where the processes that produce data or where data is obtained are mapped out and each of the formats and their controls are identified and the data criticality and inherent risks documented
Впрочем, подсказки присутствуют буквально сразу же по соседству:
Оценка рисков должна быть сосредоточена на бизнес-процессе, например: производство, контроль качества
Дело в том, что индустрия не «картирования», а моделирования бизнес-процессов развита очень хорошо примерно с 60-х годов прошлого века, а в 90-е годы уже появились программные решения, которые позволяют выполнить это моделирование «не пешком». В 1960-е годы развивался подход функционального моделирования (SADT = structured analysis and design technique), в 90-е родилось семейство стандартов IDEFx. Помимо этого, развивались другие нотации моделирования бизнес-процессов – ARIS, DFD и т.п. В настоящее время на авансцену довольно мощно вышла методология BPMN 2.0 – вот краткий очерк применительно к фарма в отношении указанных методологий. Объединяет их все одно общее свойство – это своеобразный «костыль для мозга», ведь сформулировать хотя бы на уровне требований информационную модель к будущей компьютеризированной системе без специальных инструментов практически невозможно. Точнее как, попытаться можно, но это только бумажные СМК успешно «преодолевают» нестыковки и коллизии, которые стерпит бумага. Попытка информатизировать «захламеленный» бизнес-процесс приведёт к тому, что на выходе получиться «мертворожденное» приложение, например, в части либо документооборота, либо учета лабораторной деятельности, либо статусов сырья, материалов и готовой продукции, которое будет внедряться «вечно».
Было бы очень ценно узнать мнения авторов Руководств или мнения экспертного сообщества, что подразумеваются под такими терминами, как «картирование процессов». На мой взгляд всё достаточно логично сводится к стандартной бизнес-аналитике. Ведь попытка выполнить заявленные действия как-то иначе будет сродни изобретению колеса. Вот абстрактный пример – отталкиваемся от прямой формулировки – процессы, производящие данные, картируются. Сколько процессов на среднестатистическом фармпредприятии? Понято, что зависит от уровня декомпозиции, но тем не менее? Очевидно, что эти бизнес-процессы нужно «посчитать», «инвентаризировать». Далее, речь идёт о данных. Сколько и каких данных генерирует среднестатистическое фармпредприятие? Ответ аналогичный. Если кто-либо попытается это сделать «пешком», «карандашиком в блокнотик», то неизбежно зароется в рутине. И для блокнотика или для «номинального» документа с титульным листом DIRA этого может оказаться и достаточно. Но построить работающую компьютеризированную систему таким образом, не то, чтобы не удастся – просто в процессе разработки и тестирования будут неприемлемо большие затраты на разрешение непродуманных коллизий или противоречий. Ведь если, к примеру, вы не продумали в модели системы, как будет работать 1С, то ошибка в модели приведёт к тому, что программа просто прервёт свою функцию или выполнить её неправильно. Причем логические ошибки можно искать годами. А система тем временем не сформирует бланк, не передаст выполнение функции на следующий шаг, не предоставит полномочия ответственному специалисту и т.п.
Взгляните, как выглядит пример стандартного бизнес-процесса (относительно простого) в демонстрационной версии системы BPMS CE ELMA:
Это пример улучшения бизнес-процесса. Как прочитать данную диаграмму, выполненную в нотации BPMN 2.0? Укрупнённо – есть дорожки (пулы) ответственности- Инициатор, Владелец процесса, Исполнитель. Есть ключевые этапы и виды деятельности – старт процесса (зеленый кружок), операции различных видов (пользовательская задача, оповещение и т.п.) и закономерное завершение процесса (красный кружок). Данная нотация позволяет выяснить «кто на ком стоял» (с). Ведь чем грешит бумажный документооборот? Неопределенностью. Кто заполняет журнал или бланк, в какой момент заполняет его, какие данные при этом генерируются и т.д. Нотация BPMN 2.0 в значительной степени снимет такие вопросы, поскольку модели проверяются на непротиворечивость перед их публикацией. Это и составляет ключевое отличие от «наскальной живописи», выполненной в Visio или иными графическими редакторами. Это в простом примере выше вы довольно легко «по наитию» накидаете сценарий. А если у вас таких бизнес-процессов тысячи? А если большинство сценариев – межмодульные? Впрочем, к этому образцу у читателя вполне должен сформироваться ясный ответ. Преимуществом любой нотации бизнес-моделирования являются встроенные проверки состоятельности нашей модели, прежде чем отдать её в реализацию.
Ценность данной нотации состоит в том, что она формализует комплекс всех бизнес-процессов предприятия, накладывая её на сформированную и поддерживаемую организационную структуру, а её преимущество по отношении к другим нотациям – это то, что бизнес-логика может быть автоматом транслирована в код (т.н.lowcode программирование) и на выходе можно получить сразу готовое решение, чья модель всех устраивает. Например, это может быть внутрифирменный портал.
Что при этом является дополнительным преимуществом, так это то, что многие вопросы в отношении целостности данных решены будут ещё на проектном этапе. Нецелостная модель просто «не взлетит». А самый распространенный вопрос – кто, в какой момент и какие данные внёс или имеет право внести – будут решены ещё на уровне проверки модели.
Я постараюсь развить данную тематику на ближайшей Российской неделе валидации. Ведь очевидно, что подобные вопросы будут приобретать только всё большую актуальность. Мне же представляется, что адресация к стандартным практикам моделирования бизнес-процессов — вполне обоснованное решение указанных вопросов.
Data Integrity
Смотреть что такое «Data Integrity» в других словарях:
Data integrity — in its broadest meaning refers to the trustworthiness of system resources over their entire life cycle. In more analytic terms, it is the representational faithfulness of information to the true state of the object that the information represents … Wikipedia
Data Integrity — [engl.], Datenintegrität … Universal-Lexikon
data integrity — duomenų vientisumas statusas Aprobuotas sritis informacija, informacinės technologijos ir informacinė visuomenė apibrėžtis Elektroninės informacijos savybė – elektroninė informacija nebuvo atsitiktinai ar neteisėtai pakeista ar sunaikinta.… … Lithuanian dictionary (lietuvių žodynas)
data integrity — duomenų nepažeistumas statusas T sritis informatika apibrėžtis Duomenų tapatumo išsaugojimas juos laikant, perkeliant į kitą vietą, persiunčiant tinklu. Duomenys turi išlikti absoliučiai tokie pat, kokie buvo pradžioje. Tai gali užtikrinti… … Enciklopedinis kompiuterijos žodynas
data integrity — duomenų vientisumas statusas T sritis informatika apibrėžtis Perduodamų ir apdorojamų duomenų suderinamumas, tikslumas ir neprieštaringumas. atitikmenys: angl. data integrity ryšiai: dar žiūrėk – apsauga … Enciklopedinis kompiuterijos žodynas
Data integrity — An ISO term. The property that data has not been altered or destroyed in an unauthorised manner … International financial encyclopaedia
data integrity — A measure of accuracy based on error detection … IT glossary of terms, acronyms and abbreviations
Data Integrity Field — DIF stands for Data Integrity Field. The purpose of this field is to provide End to End data protection in Computer/Enterprise data storage methodology. Data integrity concerns are not new, and protection mechanisms abound. Packet based storage… … Wikipedia
Data warehouse — Overview In computing, a data warehouse (DW) is a database used for reporting and analysis. The data stored in the warehouse is uploaded from the operational systems. The data may pass through an operational data store for additional operations… … Wikipedia
Integrity constraints — are used to ensure accuracy and consistency of data in a relational database. Data integrity is handled in a relational database through the concept of referential integrity. There are many types of integrity constraints that play a role in… … Wikipedia
Data quality — Data are of high quality if they are fit for their intended uses in operations, decision making and planning (J. M. Juran). Alternatively, the data are deemed of high quality if they correctly represent the real world construct to which they… … Wikipedia
5 Data Integrity
This chapter explains how integrity constraints enforce the business rules associated with a database and prevent the entry of invalid information into tables.
This chapter contains the following sections:
Introduction to Data Integrity
Business rules specify conditions and relationships that must always be true or must always be false. For example, each company defines its own policies about salaries, employee numbers, inventory tracking, and so on.
Techniques for Guaranteeing Data Integrity
When designing a database application, developers have various options for guaranteeing the integrity of data stored in the database.
These options include:
Enforcing business rules with triggered stored database procedures, as described in «Overview of Triggers»
Using stored procedures to completely control access to data, as described in «Introduction to Server-Side Programming»
Enforcing business rules in the code of a database application
Using Oracle Database integrity constraints, which are rules defined at the column or object level that restrict values in the database
Advantages of Integrity Constraints
An integrity constraint is a schema object that is created and dropped using SQL. To enforce data integrity, use integrity constraints whenever possible.
Advantages of integrity constraints over alternatives for enforcing data integrity include:
Because you define integrity constraints using SQL statements, no additional programming is required when you define or alter a table. The SQL statements are easy to write and eliminate programming errors.
Flexibility when loading data
You can disable integrity constraints temporarily to avoid performance overhead when loading large amounts of data. When the data load is complete, you can re-enable the integrity constraints.
Oracle Database Administrator’s Guide to learn how to manage integrity constraints
Types of Integrity Constraints
Oracle Database enables you to apply constraints both at the table and column level.
A constraint specified as part of the definition of a column or attribute is an inline specification. A constraint specified as part of the table definition is an out-of-line specification.
Table 5-1 Types of Integrity Constraints
Constraint Type
Description
See Also
Allows or disallows inserts or updates of rows containing a null in a specified column.
Prohibits multiple rows from having the same value in the same column or combination of columns but allows some values to be null.
Combines a NOT NULL constraint and a unique constraint. It prohibits multiple rows from having the same value in the same column or combination of columns and prohibits values from being null.
Requires a database value to obey a specified condition.
Oracle Database SQL Language Reference to learn more about the types of constraints
NOT NULL Integrity Constraints
A NOT NULL constraint requires that a column of a table contain no null values. A null is the absence of a value. By default, all columns in a table allow nulls.
NOT NULL constraints are intended for columns that must not lack values. For example, the hr.employees table requires a value in the email column. An attempt to insert an employee row without an email address generates an error:
You can only add a column with a NOT NULL constraint if the table does not contain any rows or if you specify a default value.
Oracle Database 2 Day Developer’s Guide for examples of adding NOT NULL constraints to a table
Oracle Database SQL Language Reference for restrictions on using NOT NULL constraints
Oracle Database Development Guide to learn when to use the NOT NULL constraint
Unique Constraints
A unique key constraint requires that every value in a column or set of columns be unique. No rows of a table may have duplicate values in a single column (the unique key ) or set of columns (the composite unique key ) with a unique key constraint.
Unique key constraints are appropriate for any column where duplicate values are not allowed. Unique constraints differ from primary key constraints, whose purpose is to identify each table row uniquely, and typically contain values that have no significance other than being unique. Examples of unique keys include:
A customer phone number, where the primary key is the customer number
A department name, where the primary key is the department number
As shown in Example 2-1, a unique key constraint exists on the email column of the hr.employees table. The relevant part of the statement is as follows:
The emp_email_uk constraint ensures that no two employees have the same email address, as shown in the following example:
Unless a NOT NULL constraint is also defined, a null always satisfies a unique key constraint. Thus, columns with both unique key constraints and NOT NULL constraints are typical. This combination forces the user to enter values in the unique key and eliminates the possibility that new row data conflicts with existing row data.
Because of the search mechanism for unique key constraints on multiple columns, you cannot have identical values in the non-null columns of a partially null composite unique key constraint.
Example 5-1 Unique Constraint
Oracle Database 2 Day Developer’s Guide for examples of adding UNIQUE constraints to a table
Primary Key Constraints
A primary key can be natural or a surrogate. A natural key is a meaningful identifier made of existing attributes in a table. For example, a natural key could be a postal code in a lookup table. In contrast, a surrogate key is a system-generated incrementing identifier that ensures uniqueness within a table. Typically, a sequence generates surrogate keys.
The Oracle Database implementation of the primary key constraint guarantees that the following statements are true:
No two rows have duplicate values in the specified column or set of columns.
The primary key columns do not allow nulls.
A typical situation calling for a primary key is the numeric identifier for an employee. Each employee must have a unique ID. A employee must be described by one and only one row in the employees table.
The example in Unique Constraints indicates that an existing employee has the employee ID of 202, where the employee ID is the primary key. The following example shows an attempt to add an employee with the same employee ID and an employee with no ID:
You can explicitly create a unique index with the CREATE UNIQUE INDEX statement.
If a usable index exists when a primary key constraint is created, then the constraint reuses this index and does not implicitly create one.
By default the name of the implicitly created index is the name of the primary key constraint. You can also specify a user-defined name for an index. You can specify storage options for the index by including the ENABLE clause in the CREATE TABLE or ALTER TABLE statement used to create the constraint.
Oracle Database 2 Day Developer’s Guide and Oracle Database Development Guide to learn how to add primary key constraints to a table
Foreign Key Constraints
A foreign key constraint requires that for each value in the column on which the constraint is defined, the value in the other specified other table and column must match. An example of a referential integrity rule is an employee can work for only an existing department.
The following table lists terms associated with referential integrity constraints.
Table 5-2 Referential Integrity Constraint Terms
Foreign keys may be defined as multiple columns. However, a composite foreign key must reference a composite primary or unique key with the same number of columns and the same data types.
The value of foreign keys can match either the referenced primary or unique key value, or be null. If any column of a composite foreign key is null, then the non-null portions of the key do not have to match any corresponding portion of a parent key.
Dependent or child table
Referenced or parent table
Figure 5-1 shows a foreign key on the employees.department_id column. It guarantees that every value in this column must match a value in the departments.department_id column. Thus, no erroneous department numbers can exist in the employees.department_id column.
Figure 5-1 Referential Integrity Constraints
Description of «Figure 5-1 Referential Integrity Constraints»
Oracle Database 2 Day Developer’s Guide and Oracle Database Development Guide to learn how to add foreign key constraints to a table
Self-Referential Integrity Constraints
A self-referential integrity constraint is a foreign key that references a parent key in the same table.
In the following figure, a self-referential constraint ensures that every value in the employees.manager_id column corresponds to an existing value in the employees.employee_id column. For example, the manager for employee 102 must exist in the employees table. This constraint eliminates the possibility of erroneous employee numbers in the manager_id column.
Figure 5-2 Single Table Referential Constraints
Description of «Figure 5-2 Single Table Referential Constraints»
Nulls and Foreign Keys
The relational model permits the value of foreign keys to match either the referenced primary or unique key value, or be null. For example, a user could insert a row into hr.employees without specifying a department ID.
If any column of a composite foreign key is null, then the non-null portions of the key do not have to match any corresponding portion of a parent key.
Parent Key Modifications and Foreign Keys
The relationship between foreign key and parent key has implications for deletion of parent keys. For example, if a user attempts to delete the record for this department, then what happens to the records for employees in this department?
When a parent key is modified, referential integrity constraints can specify the following actions to be performed on dependent rows in a child table:
No action on deletion or update
A deletion cascades ( DELETE CASCADE ) when rows containing referenced key values are deleted, causing all rows in child tables with dependent foreign key values to also be deleted. For example, the deletion of a row in departments causes rows for all employees in this department to be deleted.
Deletions that set null
A deletion sets null ( DELETE SET NULL ) when rows containing referenced key values are deleted, causing all rows in child tables with dependent foreign key values to set those values to null. For example, the deletion of a department row sets the department_id column value to null for employees in this department.
Table 5-3 outlines the DML statements allowed by the different referential actions on the key values in the parent table, and the foreign key values in the child table.
Table 5-3 DML Statements Allowed by Update and Delete No Action
DML Statement
Issued Against Parent Table
Issued Against Child Table
Always OK if the parent key value is unique
OK only if the foreign key value exists in the parent key or is partially or all null
Allowed if the statement does not leave any rows in the child table without a referenced parent key value
Allowed if the new foreign key value still references a referenced key value
Allowed if no rows in the child table reference the parent key value
Oracle Database SQL Language Reference to learn about the ON DELETE clause
Indexes and Foreign Keys
As a rule, foreign keys should be indexed. The only exception is when the matching unique or primary key is never updated or deleted.
Indexing the foreign keys in child tables provides the following benefits:
Prevents a full table lock on the child table. Instead, the database acquires a row lock on the index.
Removes the need for a full table scan of the child table. As an illustration, assume that a user removes the record for department 10 from the departments table. If employees.department_id is not indexed, then the database must scan employees to see if any employees exist in department 10.
Check Constraints
A check constraint on a column or set of columns requires that a specified condition be true or unknown for every row. If DML results in the condition of the constraint evaluating to false, then the SQL statement is rolled back.
The chief benefit of check constraints is the ability to enforce very specific integrity rules. For example, you could use check constraints to enforce the following rules in the hr.employees table:
The salary column must not have a value greater than 10000.
The commission column must have a value that is not greater than the salary.
The following example creates a maximum salary constraint on employees and demonstrates what happens when a statement attempts to insert a row containing a salary that exceeds the maximum:
A single column can have multiple check constraints that reference the column in its definition. For example, the salary column could have one constraint that prevents values over 10000 and a separate constraint that prevents values less than 500.
If multiple check constraints exist for a column, then they must be designed so their purposes do not conflict. No order of evaluation of the conditions can be assumed. The database does not verify that check conditions are not mutually exclusive.
Oracle Database SQL Language Reference to learn about restrictions for check constraints
States of Integrity Constraints
As part of constraint definition, you can specify how and when Oracle Database should enforce the constraint, thereby determining the constraint state.
Checks for Modified and Existing Data
The database enables you to specify whether a constraint applies to existing data or future data. If a constraint is enabled, then the database checks new data as it is entered or updated. Data that does not conform to the constraint cannot enter the database.
For example, enabling a NOT NULL constraint on employees.department_id guarantees that every future row has a department ID. If a constraint is disabled, then the table can contain rows that violate the constraint.
You can set constraints to validate ( VALIDATE ) or not validate ( NOVALIDATE ) existing data. If VALIDATE is specified, then existing data must conform to the constraint. For example, enabling a NOT NULL constraint on employees.department_id and setting it to VALIDATE checks that every existing row has a department ID. If NOVALIDATE is specified, then existing data need not conform to the constraint.
The behavior of VALIDATE and NOVALIDATE always depends on whether the constraint is enabled or disabled. The following table summarizes the relationships.
Table 5-4 Checks on Modified and Existing Data
Modified Data
Existing Data
Summary
Existing and future data must obey the constraint. An attempt to apply a new constraint to a populated table results in an error if existing rows violate the constraint.
The database checks the constraint, but it need not be true for all rows. Thus, existing rows can violate the constraint, but new or modified rows must conform to the rules.
The database disables the constraint, drops its index, and prevents modification of the constrained columns.
The constraint is not checked and is not necessarily true.
When the Database Checks Constraints for Validity
Every constraint is either in a not deferrable (default) or deferrable state. This state determines when Oracle Database checks the constraint for validity.
The following graphic shows the options for deferrable constraints.
Figure 5-3 Options for Deferrable Constraints
Description of «Figure 5-3 Options for Deferrable Constraints»
Nondeferrable Constraints
For example, a nondeferrable NOT NULL constraint exists for the employees.last_name column. If a session attempts to insert a row with no last name, then the database immediately rolls back the statement because the NOT NULL constraint is violated. No row is inserted.
Deferrable Constraints
A deferrable constraint permits a transaction to use the SET CONSTRAINT clause to defer checking of this constraint until a COMMIT statement is issued. If you make changes to the database that might violate the constraint, then this setting effectively enables you to disable the constraint until all changes are complete.
You can set the default behavior for when the database checks the deferrable constraint. You can specify either of the following attributes:
The database checks the constraint immediately after each statement executes. If the constraint is violated, then the database rolls back the statement.
The database checks the constraint when a COMMIT is issued. If the constraint is violated, then the database rolls back the transaction.
Oracle Database SQL Language Reference for information about constraint attributes and their default values
Examples of Constraint Checking
The following examples help illustrate when Oracle Database performs the checking of constraints.
Assume the following:
The self-referential constraint makes entries in the manager_id column dependent on the values of the employee_id column.
Example: Insertion of a Value in a Foreign Key Column When No Parent Key Value Exists
This example concerns the insertion of the first row into the employees table. No rows currently exist, so how can a row be entered if the value in the manager_id column cannot reference an existing value in the employee_id column?
Some possibilities are:
If the manager_id column does not have a NOT NULL constraint defined on it, then you can enter a null for the manager_id column of the first row.
Because nulls are allowed in foreign keys, Oracle Database inserts this row into the table.
You can enter the same value in the employee_id and manager_id columns, specifying that the employee is his or her own manager.
This case reveals that Oracle Database performs its constraint checking after the statement executes. To allow a row to be entered with the same values in the parent key and the foreign key, the database must first insert the new row, and then determine whether any row in the table has an employee_id that corresponds to the manager_id of the new row.
A multiple row INSERT statement, such as an INSERT statement with nested SELECT statements, can insert rows that reference one another.
For example, the first row might have 200 for employee ID and 300 for manager ID, while the second row has 300 for employee ID and 200 for manager. Constraint checking is deferred until the complete execution of the INSERT statement. The database inserts all rows, and then checks all rows for constraint violations.
Default values are included as part of an INSERT statement before the statement is parsed. Thus, default column values are subject to all integrity constraint checking.
Example: Update of All Foreign Key and Parent Key Values
In this example, a self-referential constraint makes entries in the manager_id column of employees dependent on the values of the employee_id column.
The company has been sold. Because of this sale, all employee numbers must be updated to be the current value plus 5000 to coordinate with the employee numbers of the new company. As shown in the following graphic, some employees are also managers:
Figure 5-4 The employees Table Before Updates
Description of «Figure 5-4 The employees Table Before Updates»
Because manager numbers are also employee numbers, the manager numbers must also increase by 5000. You could execute the following SQL statement to update the values:
Although a constraint is defined to verify that each manager_id value matches an employee_id value, the preceding statement is valid because the database effectively checks constraints after the statement completes. Figure 5-5 shows that the database performs the actions of the entire SQL statement before checking constraints.
Figure 5-5 Constraint Checking
Description of «Figure 5-5 Constraint Checking»
The examples in this section illustrate the constraint checking mechanism during INSERT and UPDATE statements, but the database uses the same mechanism for all types of DML statements. The database uses the same mechanism for all types of constraints, not just self-referential constraints.
Operations on a view or synonym are subject to the integrity constraints defined on the base tables.