RU2526753C1 - Method for data recovery in database management system - Google Patents
Method for data recovery in database management system Download PDFInfo
- Publication number
- RU2526753C1 RU2526753C1 RU2013128323/08A RU2013128323A RU2526753C1 RU 2526753 C1 RU2526753 C1 RU 2526753C1 RU 2013128323/08 A RU2013128323/08 A RU 2013128323/08A RU 2013128323 A RU2013128323 A RU 2013128323A RU 2526753 C1 RU2526753 C1 RU 2526753C1
- Authority
- RU
- Russia
- Prior art keywords
- log
- redo
- database
- record
- undo
- Prior art date
Links
- 238000000034 method Methods 0.000 title claims abstract description 35
- 238000011084 recovery Methods 0.000 title claims description 34
- 230000008569 process Effects 0.000 claims description 15
- 230000008859 change Effects 0.000 claims description 12
- 230000000903 blocking effect Effects 0.000 claims description 4
- 238000005516 engineering process Methods 0.000 abstract description 4
- 239000000126 substance Substances 0.000 abstract 1
- 238000007726 management method Methods 0.000 description 11
- 230000009471 action Effects 0.000 description 9
- 238000005096 rolling process Methods 0.000 description 4
- 230000002730 additional effect Effects 0.000 description 3
- 238000010586 diagram Methods 0.000 description 2
- 230000003993 interaction Effects 0.000 description 2
- 239000000463 material Substances 0.000 description 2
- 230000004048 modification Effects 0.000 description 2
- 238000012986 modification Methods 0.000 description 2
- 238000004364 calculation method Methods 0.000 description 1
- 239000008187 granular material Substances 0.000 description 1
- 230000000750 progressive effect Effects 0.000 description 1
Images
Landscapes
- Information Retrieval, Db Structures And Fs Structures Therefor (AREA)
Abstract
Description
Изобретение относится к вычислительной технике (вычислительным сетям), в частности к способу восстановления данных в системе управления базами данных - СУБД, и может быть использовано в СУБД для управления транзакциями и восстановления одного и более файлов базы данных - БД в системе в случае аппаратного или программного сбоя.The invention relates to computing (computer networks), in particular to a method for recovering data in a database management system — a DBMS, and can be used in a DBMS to manage transactions and restore one or more database files — a database in a system in the case of hardware or software a failure.
За последние десятилетия в связи с развитием вычислительной техники и использованием компьютерных технологий и СУБД, все более актуальной является задача для управления транзакциями и восстановления одного и более файлов данных в СУБД после возможного аппаратного или программного сбоя - организация рестарта системы после сбоя и структура журнала транзакций.Over the past decades, in connection with the development of computer technology and the use of computer technologies and DBMSs, the task of managing transactions and recovering one or more data files in a DBMS after a possible hardware or software failure is more and more relevant - organizing a system restart after a failure and the structure of the transaction log.
Транзакция - это групповая операция, т.е. набор действий с БД, самым существенным для этих действий является правило: либо все, либо ничего. Если во время выполнения данного набора действий, на каком-то этапе невозможно произвести очередное действие, то нужно выполнить возврат БД к начальному состоянию (произвести откат транзакции). Таким образом, при правильном планировании транзакций обеспечивается логическая и физическая целостность БД ([1] Управление транзакциями - сайт - форум (http://citforum.ru/programming/32less/les310.shtml).A transaction is a group operation, i.e. a set of actions with the database, the most important rule for these actions is the rule: either all or nothing. If during the execution of this set of actions, at some stage it is impossible to perform the next action, then you need to return the database to its initial state (roll back the transaction). Thus, with the proper planning of transactions, the logical and physical integrity of the database is ensured ([1] Transaction management - site - forum (http://citforum.ru/programming/32less/les310.shtml).
Рестарт - это перезагрузка СУБД после программного или аппаратного сбоя, процесс, при котором СУБД восстанавливает последнее перед сбоем согласованное состояние БД и возобновляет свою работу заново.Restart is a reboot of a DBMS after a software or hardware failure, a process in which a DBMS restores the last agreed DB state before a failure and resumes its work again.
На восстановление данных в СУБД направлено известное техническое решение - изобретение по патенту [2] US 5,966,706 «Local logging in a distributed database management computer system», Int. Cl. G06F 11/14, в котором распределенная база данных компьютерной системы управления включает в себя множество узлов и множество страниц базы данных. Когда первый узел в компьютерной системе обновляет первую страницу базы данных, первый узел генерирует запись в журнале. Первый узел определяет, будет ли он управлять первой страницей базы данных. Если первый узел определяет, что он управляет первой страницей базы данных, первый узел пишет запись в журнале хранения на первый узел. Однако, если первый узел определяет, что он не успевает управлять первой страницей базы данных, первый узел определяет, включает ли в себя локальное хранение журнала. Если первый узел включает в себя локальное хранение журнала, первый узел пишет запись в локальное хранение журналов, даже если ему не удается управлять первой страницей базы данных. Если первый узел не включают запись в локальное хранение журнала, первый узел отправляет запись в журнал на второй узел управления первой страницей базы данных.A well-known technical solution is directed to data recovery in a DBMS - an invention according to the patent [2] US 5,966,706 “Local logging in a distributed database management computer system”, Int. Cl. G06F 11/14, in which a distributed database of a computer control system includes a plurality of nodes and a plurality of database pages. When the first node in the computer system updates the first page of the database, the first node generates a log entry. The first node determines whether it will manage the first page of the database. If the first node determines that it controls the first page of the database, the first node writes an entry in the storage log to the first node. However, if the first node determines that it does not manage to manage the first page of the database, the first node determines whether it includes local log storage. If the first node includes local log storage, the first node writes an entry to local log storage, even if it cannot manage the first page of the database. If the first node does not include an entry in local log storage, the first node sends a journal entry to the second management node of the first page of the database.
Недостаткам данного технического решения является громоздкая структура баз данных, где каждая база данных представляет собой отдельный файл, сложный алгоритм ведения журнала транзакций, используется большой объем внешней памяти под журнализацию, наличие таблицы грязных страниц, содержащих записи о каждом объекте, назначенном к модификации, списки неоконченных транзакций для отката.The disadvantages of this technical solution is the cumbersome database structure, where each database is a separate file, a complex transaction logging algorithm, a large amount of external memory is used for logging, the presence of a dirty page table containing records about each object assigned for modification, incomplete lists transactions to roll back.
Наиболее близким техническим решением (прототипом) к заявляемому изобретению является изобретение по патенту [3] US 6,173,292 «Data recovery in a transactional database using write-ahead logging and file caching», Int. Cl.: G06F 11/14 (2006.01.); G06F 012/00, которое описывает способ и систему восстановления данных в транзакционной БД с помощью упреждающей регистрации и кэширования файлов. СУБД управляет одной или несколькими БД, в каждой из которых содержится один или несколько объектов. СУБД поддерживает кэш-файл для этих БД. Система управления транзакциями записывает транзакции в одну или несколько записей, хранящихся в файле журнала, каждой из записи присваивается уникальный номер транзакции в журнале (LSN), LSN выбирается из состава группы (groupcomprised) из (1) страницы (PageLSN), которая идентифицирует версию объекта, (2) запись (RecLSN), которая идентифицирует восстановление версии объекта, (3) минимальная запись (MinRecLSN), которая является минимальным значением всех записей RecLSNs из буферного пула общих объектов памяти и грязном столе объектов, (4) кэш (FCacheLSN) является минимальным значением для записей RecLSNs всех объектов, которые, как предполагается, находятся в файле кэша, и (5) переделать (ReDoLSN), который идентифицирует запись RecLSN в лог-файл, где перезагрузка восстановления БД должна начаться.The closest technical solution (prototype) to the claimed invention is the invention according to patent [3] US 6,173,292 "Data recovery in a transactional database using write-ahead logging and file caching", Int. Cl .: G06F 11/14 (2006.01.); G06F 012/00, which describes a method and system for recovering data in a transactional database using proactive registration and file caching. The DBMS manages one or more databases, each of which contains one or more objects. The DBMS maintains a cache file for these databases. A transaction management system writes transactions to one or more records stored in a log file, each record is assigned a unique transaction number in the log (LSN), LSN is selected from the group (groupcomprised) from (1) page (PageLSN), which identifies the version of the object , (2) a record (RecLSN) that identifies the restoration of the version of an object, (3) a minimum record (MinRecLSN), which is the minimum value of all RecLSNs from the buffer pool of shared memory objects and a dirty table of objects, (4) the cache (FCacheLSN) is minimal the value for RecLSNs of all objects that are supposed to be in the cache file, and (5) redo (ReDoLSN), which identifies the RecLSN record in the log file, where the reboot of the database recovery should begin.
Несмотря на то, что способ-прототип по патенту [3] US 6,173,292 является на данный момент наиболее прогрессивным по сравнению с другими техническими решениями в известном уровне техники для восстановления данных в СУБД, ему присущ ряд существенных недостатков, а именно:Despite the fact that the prototype method according to the patent [3] US 6,173,292 is currently the most progressive in comparison with other technical solutions in the prior art for data recovery in a DBMS, it has a number of significant drawbacks, namely:
во-первых, прототип использует громоздкую структуру БД, где каждая БД представляет собой отдельный файл, использует сложный алгоритм ведения журнала транзакций с большим количеством вычисляемых LSNS: PageLSNs, RecLSNs, TempFCacheLSNs, ReDoLSNs;firstly, the prototype uses a cumbersome database structure, where each database is a separate file, uses a complex transaction logging algorithm with a large number of calculated LSNS: PageLSNs, RecLSNs, TempFCacheLSNs, ReDoLSNs;
во-вторых, использует много внешней памяти под журнализацию (файловая система является общей для всех баз данных), наличие таблицы грязных страниц, содержащих записи о каждом объекте, назначенном к модификации (его LSN + адрес), списки неоконченных транзакций для отката и список объектов (гранул) аннулирования.secondly, it uses a lot of external memory for logging (the file system is common for all databases), the presence of a dirty page table containing records about each object assigned for modification (its LSN + address), lists of incomplete transactions for rollback and a list of objects (granules) cancellation.
Все эти недостатки существенно снижают эффективность восстановления данных в БД СУБД после сбоя.All these disadvantages significantly reduce the efficiency of data recovery in a DBMS database after a failure.
Поэтому задача восстановления данных в БД при аппаратном или программном сбое в СУБД является по-прежнему актуальной.Therefore, the task of restoring data in the database with a hardware or software failure in the DBMS is still relevant.
Техническая задача, на решение которой направлено заявляемое изобретение, - это повышение точности восстановления данных в БД СУБД до последнего по времени согласованного состояния БД, не требуя при восстановлении дополнительного объема оперативной и внешней памяти под журнализациюThe technical problem to which the claimed invention is directed is to increase the accuracy of data recovery in a DBMS database to the last agreed-upon state of the database, without requiring additional recovery of operational and external memory for logging
Поставленная техническая задача решается заявляемым способом восстановления данных в системе управления базами данных - СУБД, при котором:The technical task is solved by the claimed method of data recovery in a database management system - DBMS, in which:
базы данных - БД сформированы в виде реляционных таблиц, каждая из которых описывается метаданными и содержит данные, сформированные в строки одинаковой структуры, где каждая строка идентифицирована уникальным номером и представлена набором полей с заданными типами данных, а совокупность значений одного и того же поля в разных строках образует столбец значений данных, каждый из которых имеет свой тип данных;Databases - databases are formed in the form of relational tables, each of which is described by metadata and contains data formed into rows of the same structure, where each row is identified by a unique number and represented by a set of fields with specified data types, and a set of values of the same field in different rows forms a column of data values, each of which has its own data type;
СУБД, в которой наименьшей единицей блокирования является кортеж, формируя данные файловой структуры БД, образует файлы данных в оперативной памяти, одновременно выполняет протоколирование изменений БД, формируя файлы для хранения записей протоколированных изменений во внешней памяти, в которых поддерживается журнал транзакций, при этом на период рестарта обеспечивается постоянство используемой памяти - оперативной и внешней,A DBMS in which the smallest blocking unit is a tuple, generating data of the database file structure, forms data files in RAM, simultaneously logs database changes, generating files for storing logged changes in external memory in which the transaction log is maintained, while for a period restart ensures the constancy of the used memory - operational and external,
заключающимся в том, что при аппаратном или программном сбое в БД выполняют управление транзакциями, используя временные файлы для хранения данных во внешней памяти, и восстанавливают один или более файлов данных до последнего по времени согласованного состояния базы данных,consisting in the fact that during a hardware or software failure in the database, transaction management is performed using temporary files for storing data in external memory, and one or more data files are restored to the most recently agreed database state,
отличающимся согласно изобретению тем, чтоcharacterized according to the invention in that
формируют журнал, единый для транзакций и рестарта, состоящий из определяемого пользователем числа файлов журнала заданного размера, содержащий множество журнальных записей различного типа, среди которых формируют в том числе записи, каждая из которых описывает redo-обновление только на одной странице одной из таблиц БД и предназначена для доката обновления в БД, которое не было записано во внешнюю память;form a log that is common for transactions and restart, consisting of a user-defined number of log files of a given size, containing a lot of log records of various types, among which they include records, each of which describes a redo update on only one page of one of the database tables and It is intended for the update update in the database, which was not written to external memory;
в структуру записи redo-обновления включают:The redo update record structure includes:
поле TSN - time sequence number - синтетическое время СУБД, представляющее уникальную последовательно возрастающую числовую комбинацию,TSN field - time sequence number - synthetic DBMS time representing a unique sequentially increasing numerical combination,
обновление и его длину,update and its length,
адрес обновления - номер страницы файла таблицы и смещение в ней,update address - page number of the table file and offset in it,
поле обратной ссылки - журнальный адрес предыдущей записи транзакции для выполнения откатов транзакций, причем значение поля ссылки содержит номер файла журнала и смещение в нем;backlink field - the journal address of the previous transaction record for performing rollbacks of transactions, and the value of the link field contains the number of the log file and the offset in it;
при рестарте накатывают на физическом уровне все зарегистрированные в журнале обновления, которые не попали в БД, после чего выполняют откаты всех незавершенных транзакций на логическом уровне, при этом рестарт выполняют в три прохода:upon restart, roll on the physical level all updates registered in the log that did not fall into the database, then roll back all incomplete transactions at the logical level, and restart in three passes:
первый - аналитический проход, в котором определяют адрес последней, предназначенной к накату, журнальной записи и адрес размещения служебной записи слежения, оценивают состояние тех страниц БД, которые предназначены к накату пропущенных обновлений, и информацию о которых извлекают при проходе по журналу из записей, описывающих redo-обновления, и определяют состояние всех транзакций;the first is an analytical passage, in which the address of the last logbook intended to be rolled up and the location of the tracking service record are determined, the state of those database pages that are designed to run through the missed updates, and information about which is extracted from the records describing the passage through the log redo updates, and determine the status of all transactions;
второй - redo-проход, при котором выполняют накат пропущенных обновлений и для каждой неоконченной транзакции в записи о ее начале выставляют соответствующий признак;the second is a redo-pass, in which skipped updates are rolled forward and for each unfinished transaction, a corresponding sign is set in the entry about its start;
третий - undo-проход, при котором выполняют откат всех незавершенных транзакций, которые не были закоммичены или не до конца осуществили откат;the third is an undo-pass, in which they roll back all incomplete transactions that were not committed or did not complete the rollback;
причем в аналитическом проходе:and in the analytical passage:
заполняют массив состояний транзакций, хранимый в оперативной памяти и логически состоящий из поля идентификатора ID транзакции и поля битовых флагов, который используют в undo-проходе, при этом поле битовых флагов включает значения:fill in the array of transaction states stored in RAM and logically consisting of the identifier field of the transaction ID and the field of bit flags, which is used in an undo-pass, while the field of bit flags includes the values:
транзакция не была закоммичена,The transaction has not been committed
транзакция не до конца осуществила откат,The transaction did not complete the rollback,
транзакция представляет собой операцию над метаданными,a transaction is an operation on metadata,
транзакция содержит последнюю незаконченную журнальную операцию и требует отката на физическом уровне;transaction contains the last unfinished journal operation and requires rollback at the physical level;
в redo-проходе:in the redo pass:
перед записью измененной страницы во внешнюю память БД изменяют во внешней памяти журнала поля TSN всех redo-обновлений, касающихся измененной страницы,before writing the changed page to the external memory, the databases change the TSN fields of all redo updates relating to the changed page in the external memory of the journal,
используют служебную запись слежения, сохраненную в соответствующем файле журнала до начала redo-прохода, для отслеживания адреса и поля TSN текущего накатываемого redo-обновления,use the tracking service record stored in the corresponding log file before the start of the redo pass to track the address and TSN field of the current rolling redo update,
служебную запись и redo-обновления журнала сбрасывают во внешнюю память журнала каждый раз, когда измененные данные БД готовят к записи в БД,service record and redo-log updates are dumped into the external memory of the log every time the changed database data is prepared for writing to the database,
при этом структура служебной записи содержит поля:the structure of the service record contains the fields:
cpFlag - флаги состояния рестарта в redo-проходе или undo-проходе,cpFlag - flags of restart status in redo-pass or undo-pass,
startTSN - значение синтетического времени СУБД перед первым восстановлением по журналу,startTSN - DBMS synthetic time value before the first log recovery,
specAddr - адрес в журнале текущей записи redo-обновления, которое будет накатываться в БД,specAddr - the address in the log of the current redo-update record that will be rolled into the database,
specTSN - TSN текущей журнальной записи redo-обновления, которое будет накатываться в базу данных;specTSN - TSN of the current redo update log entry that will be rolled into the database;
предназначенные к накату в БД обновления в redo-проходе определяют путем сравнения полей TSN каждой журнальной записи redo-обновления и полей TSN заголовка соответствующей страницы БД, на которой выполняют обновление, при этомupdates to be performed in the database in the redo-pass are determined by comparing the TSN fields of each redo-update journal entry and the TSN fields of the header of the corresponding database page on which the update is performed, while
если поле TSN журнальной записи больше поля TSN заголовка страницы, обновление считают необходимым для наката,if the TSN field of the journal entry is greater than the TSN field of the page header, the update is considered necessary for roll-over,
в противном случае сравнение полей TSN продолжают с использованием значений полей из служебной записи слежения,otherwise, the TSN field comparison is continued using the field values from the tracking service record,
если по результатам сравнения полей TSN выявлено, что обновление необходимо для наката, поле TSN в записи этого обновления в пуле журнала изменяют в соответствии с текущим синтетическим временем СУБД, а само обновление вносят в поле соответствующей страницы БД;if, according to the results of comparing the TSN fields, it is revealed that the update is necessary for the roll-over, the TSN field in the record of this update in the journal pool is changed in accordance with the current synthetic DBMS time, and the update is made in the field of the corresponding database page;
по окончании redo-прохода сохраняют все обновления в БД, накатившиеся к моменту ее старта посредством сброса всех обновленных страниц оперативной памяти во внешнюю память, при этом в служебную запись слежения ставят признак окончания redo-прохода;at the end of the redo-pass, all updates are saved in the database, rolled up to the moment of its start by resetting all updated pages of the RAM into external memory, and the redo-pass is signaled in the tracking service record;
обновленное поле TSN записывают и впоследствии используют как основу для сравнения полей TSN в случае повторного восстановления данных в БД из-за возможных отказов СУБД в процессе рестарта, повторное восстановление данных начинают с начала журнала;the updated TSN field is recorded and subsequently used as the basis for comparing TSN fields in the case of repeated data recovery in the database due to possible DBMS failures during the restart process; data recovery is started from the beginning of the log;
если в аналитическом проходе выявлены незакоммиченные транзакции, то они откатываются на логическом уровне в undo-проходе рестарта, при этом redo-журнал сканируют по записям от конца к началу;if non-committed transactions are detected in the analytic pass, then they are rolled back at a logical level in the undo restart pass, while the redo log is scanned from records from end to beginning;
все изменения данных в БД, вызываемые откатами, протоколируют в журнале, формируя файлы записей отката в undo-журнале;all data changes in the database caused by rollbacks are logged in the log, forming rollback record files in the undo log;
поле ссылки в записях отката в undo-журнале, содержащее адрес журнальной записи из redo-журнала, откат которой она описывает, используют для корреляции адресов в читаемом redo-журнале и растущем undo-журнале;the link field in rollback entries in the undo log containing the address of the log entry from the redo log, the rollback of which it describes, is used to correlate addresses in the read redo log and the growing undo log;
протоколирование откатов в undo-проходе обеспечивают посредством существующего кольца файлов redo-журнала и двух резервных файлов, имеющих размер файла redo-журнала, которые предварительно резервируют;logging rollbacks in the undo-pass is provided by means of the existing ring of redo-log files and two backup files having the size of the redo-log file, which are previously reserved;
в начале undo-прохода первый резервный файл переименовывают и включают в кольцо файлов redo-журнала последним файлом, в который переносят служебную запись слежения, выполняют протоколирование откатов незакоммиченных транзакций до тех пор, пока пространство этого резервного файла будет заполнено, включают в кольцо файлов undo-журнала второй резервный файл;at the beginning of the undo pass, the first backup file is renamed and included in the redo-log file ring with the last file into which the tracking service record is transferred, logs of rollbacks of non-committed transactions are performed until the space of this backup file is full, include in the ring of undo files log a second backup file;
в процессе undo-прохода из массива состояний транзакций последовательно исключают полностью откатившиеся незаконченные транзакции, при этом в undo-журнал каждый раз поступает соответствующая запись об изменении состояния массива транзакций;in the process of undo-passage from the array of transaction states, completely rolled back incomplete transactions are sequentially excluded, while in the undo-log each time a corresponding record about the change in the state of the array of transactions is received;
в случае повторного рестарта, если отказ системы произошел на стадии undo-прохода, рестарт в три прохода используют только для undo-журнала, при этом массив состояний транзакций предварительно заполняют в ходе просмотра redo-журнала в соответствии с записями, описывающими начало транзакций, и при сканировании в аналитическом проходе корректируют в соответствии с журнальными записями об изменении состояния этого массива, по содержимому поля ссылки в последней записи undo-журнала определяют адрес последней откатившейся записи redo-обновления в redo-журнале; в redo-проходе по undo-журналу все пропущенные откатные обновления накатывают в БД;in the case of repeated restart, if the system failure occurred at the undo-pass stage, three-pass restart is used only for the undo-log, while the array of transaction states is pre-populated while viewing the redo-log in accordance with the entries describing the beginning of the transactions, and when scanning in the analytical pass is adjusted in accordance with the journal entries about the state change of this array, the contents of the link field in the last record of the undo-log determine the address of the last rolled redo-update record in redo Magazine in the redo-pass through the undo-log, all missed rollback updates are rolled into the database;
используя сканирование файлов записей в redo-журнале от конца к началу, смену номера читаемого файла на предыдущий номер отражают в undo-журнале в содержимом поля ссылки очередной записи, как только очередной файл записей redo-журнала полностью прочитан, содержимое файлов записей undo-журнала, включая последнюю запись, принудительно сбрасывают во внешнюю память, а полностью прочитанный файл записей redo-журнала переименовывают в следующий файл записей кольца файлов undo-журнала, если этого требует наличие транзакций, предназначенных к откату;using a scan of record files in the redo log from the end to the beginning, changing the number of the read file to the previous number is reflected in the undo log in the contents of the link field of the next record, as soon as the next redo log record file is completely read, the contents of the undo log record files, including the last record, it is forcibly flushed to external memory, and the fully read redo-log file is renamed to the next file of undo-log file ring records, if this is required by transactions intended for rollback;
когда транзакций, предназначенных к откату, не обнаруживают, все откатные обновления сбрасывают в БД и ставят в запись слежения признак окончания undo-прохода;when transactions destined for rollback are not detected, all rollback updates are discarded in the database and put in the tracking record a sign of the end of the undo-pass;
по окончании рестарта с откатом незавершенных транзакций, начальный адрес файла записей redo-журнала для нового цикла будет равен адресу последней откатившейся записи в одном из файлов записей undo-журнала, а количество файлов записей undo-журнала равно размеру кольца журнала и двух резервных файлов.at the end of the restart with the rollback of incomplete transactions, the starting address of the redo log file for the new cycle will be equal to the address of the last rolled record in one of the undo log files, and the number of undo log files is equal to the size of the log ring and two backup files.
При этом столбец значений данных и метаданных имеет свой тип данных, например, текстовый или числовой, или тип даты, или BLOB - Binary Large Object, представляющий собой специальный тип данных, предназначенный для хранения изображений, аудио и видео, а также компилированного программного кода.At the same time, the column of data and metadata values has its own data type, for example, text or numeric, or the date type, or BLOB - Binary Large Object, which is a special data type designed to store images, audio and video, as well as compiled program code.
Журнал формируют, используя протокол ahead logging, при котором журнальные записи, отображающие изменения данных, сохраняют во внешней памяти прежде, чем эти измененные данные будут сохранены в реальной БД.The log is generated using the ahead logging protocol, in which the log records displaying data changes are stored in external memory before these changed data are stored in a real database.
При сравнении полей TSN с использованием значений полей из служебной записи слежения учитывают расположение текущей записи журнала относительно адреса последней накатившейся в БД записи redo-обновления из служебной записи слежения specAddr, до или после, или точно по этому адресу, при этом для сравнения поля TSN используют поля:When comparing TSN fields using the field values from the tracking service record, the location of the current log entry relative to the address of the last redo update record rolled up in the database from the specAddr tracking record, before or after, or exactly at this address, is taken into account, while TSN fields are used for comparison fields:
logTSN - TSN текущей журнальной записи redo-обновления,logTSN - TSN of the current redo update log entry,
logPtr - адрес текущей журнальной записи redo-обновления,logPtr - address of the current redo update log entry,
dbTSN - TSN из заголовка страницы БД, соответствующей накатываемому redo-обновлению,dbTSN - TSN from the header of the database page corresponding to the rolling redo update,
startTSN - значение синтетического времени СУБД TSN, отсеченное перед началом самого первого восстановления рестарта,startTSN - TSN DBMS synthetic time value, cut off before the very first restart recovery,
resTSN - значение синтетического времени СУБД TSN, отсеченное перед началом текущего восстановления рестарта,resTSN - TSN DBMS synthetic time value, cut off before the start of the restart restart,
specPtr - адрес последней накатившейся в БД записи redo-обновления из служебной записи слежения,specPtr - address of the last redo-update record that rolled in the database from the tracking service record,
specTSN - TSN последней накатившейся в БД записи redo-обновления из служебной записи слежения.specTSN - TSN of the last redo update record that has rolled into the database from the tracking service record.
Таким образом, заявляемый способ восстановления данных в СУБД позволяет после программного или аппаратного сбоя максимально точно восстановить данные в БД до последнего по времени согласованного состояния БД, что достигается за счет того, что:Thus, the claimed method of data recovery in a DBMS allows, after a software or hardware failure, to restore the data in the database as accurately as possible to the last coordinated state of the database, which is achieved due to the fact that:
- формируют единый журнал, состоящий из заданного числа файлов определенного размера, при этом число и размер файлов задаются пользователем, при этом модель журнала может быть использована в процессе рестарта системы без увеличения размера;- form a single log, consisting of a given number of files of a certain size, while the number and size of files are set by the user, while the log model can be used in the process of restarting the system without increasing the size;
- по достижении количества файлов, заданного пользователем, выполняют переиспользование более ранних файлов с новым номером - журнал замыкают в кольцо, при этом файлам в кольце назначают последовательно возрастающую нумерацию, причем, если наличие незавершенной транзакции в файле не позволяет переиспользовать его, создают новый файл и временно расширяют кольцо журнала до тех пор, пока транзакция не завершится, после чего кольцо возвращают к исходному числу файлов;- upon reaching the number of files specified by the user, reuse of earlier files with a new number is performed - the journal is closed in a ring, while the files in the ring are assigned sequentially increasing numbering, and if the presence of an incomplete transaction in the file does not allow reusing it, create a new file and temporarily expand the log ring until the transaction is completed, after which the ring is returned to the original number of files;
- параметры журнального пространства кольца, задаваемые пользователем, определяются интенсивностью и длительностью транзакций в конкретной базе данных, причем при обоснованно заданном размере кольца дополнительно создают два резервных файла, которые резервируют дисковое пространство указанного размера, которые в процессе работы используются под файлы журнала посредством переименования, в частности, для откатов незавершенных транзакций при рестарте СУБД после системного сбоя.- parameters of the journal space of the ring, set by the user, are determined by the intensity and duration of transactions in a particular database, and with a reasonably specified ring size, two additional backup files are created that reserve disk space of a specified size, which are used for log files by renaming in the process, in particular, for rollbacks of incomplete transactions when restarting a DBMS after a system failure.
Проведенный заявителем патентный и научно-технический поиск не выявил признаки данного изобретения в известном уровне техники. Таким образом, заявляемый способ восстановления данных в системе управления базами данных является новым и наиболее эффективным по сравнению с известными техническими решениями в данной области техники потому, что для восстановления данных в БД после сбоя кроме имеющихся файлов журнала не использует дополнительной внешней памяти, при этом позволяет привести данные БД в непротиворечивое состояние и обеспечивает гарантию свойств атомарности и сохранности в БД результатов транзакций.A patent and scientific and technical search carried out by the applicant did not reveal the features of this invention in the prior art. Thus, the claimed method of data recovery in a database management system is new and most effective in comparison with the known technical solutions in this technical field because, in addition to the existing log files, it does not use additional external memory to recover data in the database after a failure, while allowing to bring the database data into a consistent state and provides a guarantee of the atomicity and safety properties of the transaction results in the database.
Далее описание изобретения поясняется примерами выполнения со ссылкой на чертежи (иллюстрирующие материалы).Further, the description of the invention is illustrated by examples with reference to the drawings (illustrative materials).
На фиг.1 показан пример расположения двумерного массива данных в виде реляционной таблицы.Figure 1 shows an example of the location of a two-dimensional data array in the form of a relational table.
На фиг.2 в виде структурной схемы показан пример взаимодействия устройств оперативной памяти и внешней памяти для осуществления заявляемого изобретения.Figure 2 in the form of a structural diagram shows an example of the interaction of the RAM devices and external memory for the implementation of the claimed invention.
Фиг.3 в общем виде иллюстрирует алгоритм восстановления данных в СУБД согласно заявляемому изобретению, где показано:Figure 3 in General terms illustrates the data recovery algorithm in a DBMS according to the claimed invention, which shows:
1 - текущая redo-запись, предназначенная для переноса в БД;1 - current redo-record intended for transfer to the database;
2 - чтение текущей redo-записи;2 - read the current redo-record;
3 - перенос текущей redo-записи в соответствующую страницу БД;3 - transfer of the current redo-record to the corresponding database page;
4 - перезапись текущей redo-записи с обновленным полем TSN в журнал; инициируется п.6;4 - overwriting the current redo-record with the updated TSN field in the log; p. 6 is initiated;
5 - запись адреса и обновленного поля TSN текущей redo-записи в запись слежения; инициируется п.6;5 - record of the address and the updated TSN field of the current redo record in the tracking record; p. 6 is initiated;
6 - запись страницы БД во внешнюю память.6 - writing a database page to external memory.
На фиг.4 показана схема сравнения поля TSN в redo-проходе теплого рестарта, гдеFigure 4 shows a comparison diagram of the TSN field in the warm restart redo-pass, where
7 - обновление накатывают в БД;7 - update roll into the database;
8 - обновление не накатывают в БД.8 - update is not rolled into the database.
Фиг.5 иллюстрирует включение переименованных резервных файлов в кольцо журнала в undo-проходе теплого рестарта.Figure 5 illustrates the inclusion of renamed backup files in the log ring in an undo warm restart pass.
Фиг.6 иллюстрирует восстановление размеров кольца журнала и количества резервных файлов по окончании undo-прохода теплого рестарта.Fig.6 illustrates the restoration of the size of the log ring and the number of backup files at the end of the undo-pass warm restart.
Осуществляют изобретение следующим образом.Carry out the invention as follows.
Заявляемый способ реализуется в системе управления базами данных - СУБД для малых компьютерных систем, наименьшей единицей блокирования в которых является кортеж, что обусловлено структурой записей журнала и техникой восстановления БД в процессе рестарта после сбоя. В заявляемом способе структура журнала может быть использована в процессе рестарта системы без увеличения размера журнала. Это важно для малых компьютерных систем, в которых поддерживается система журнализации с заранее заданными количеством и размером файлов. При этом на период рестарта обеспечивается постоянство используемой памяти - оперативной и внешней.The inventive method is implemented in a database management system - DBMS for small computer systems, the smallest blocking unit of which is a tuple, which is due to the structure of the journal entries and the technique of restoring the database during the restart after a failure. In the claimed method, the structure of the log can be used in the process of restarting the system without increasing the size of the log. This is important for small computer systems that support a journaling system with a predetermined number and size of files. Moreover, for the restart period, the constancy of the used memory is ensured - operational and external.
БД сформированы в виде реляционных таблиц, каждая из которых описывается метаданными и содержит данные, сформированные в строки одинаковой структуры, где каждая строка идентифицирована уникальным номером и представлена набором полей с заданными типами данных, а совокупность значений одного и того же поля в разных строках образует столбец значений данных (как показано на фиг.1), каждый из которых имеет свой тип данных: текстовый или числовой, или тип даты, или BLOB - Binary Large Object, представляющий собой специальный тип данных, предназначенный, например, для хранения изображений, аудио и видео, а также компилированного программного кода, и пронумерованы по строкам таким образом, что каждая строка получает уникальный номер.Databases are formed in the form of relational tables, each of which is described by metadata and contains data generated in rows of the same structure, where each row is identified by a unique number and represented by a set of fields with specified data types, and the totality of the values of the same field in different rows forms a column data values (as shown in figure 1), each of which has its own data type: text or numeric, or date type, or BLOB - Binary Large Object, which is a special data type designed, for example An example for storing images, audio and video, as well as compiled program code, and are numbered line by line so that each line gets a unique number.
СУБД в процессе рестарта системы восстанавливают БД, целью восстановления являются:DBMS in the process of restarting the system restore the database, the purpose of recovery are:
1) приведение данных в состояние физической и логической непротиворечивости;1) bringing data into a state of physical and logical consistency;
2) гарантия сохранности в БД результатов законченных транзакций.2) a guarantee of safety in the database of the results of completed transactions.
Поэтому при управлении транзакциями все изменения в БД, производимые в оперативной памяти, дублируются в журнале, едином для транзакций и рестарта (далее журнал) для сохранения изменений во внешней памяти (фиг.2, где в виде структурной схемы показан пример взаимодействия устройств оперативной памяти и внешней памяти 2 для осуществления заявляемого изобретения).Therefore, when managing transactions, all changes to the database made in the main memory are duplicated in a log that is common for transactions and restart (hereinafter the log) to save the changes in external memory (Fig. 2, where an example of the interaction of the main memory devices and external memory 2 for the implementation of the claimed invention).
На фиг.3 иллюстративно выполнен алгоритм восстановления данных в СУБД согласно заявляемому изобретению, где показано:Figure 3 illustratively performed the data recovery algorithm in the DBMS according to the claimed invention, which shows:
1 - текущая redo-запись, предназначенная для переноса в БД;1 - current redo-record intended for transfer to the database;
2 - чтение текущей redo-записи;2 - read the current redo-record;
3 - перенос текущей redo-записи в соответствующую страницу БД;3 - transfer of the current redo-record to the corresponding database page;
4 - перезапись текущей redo-записи с обновленным TSN в журнал; инициируется п.6;4 - overwriting the current redo-record with the updated TSN in the log; p. 6 is initiated;
5 - запись адреса и обновленного TSN текущей redo-записи в запись слежения; инициируется п.6;5 - record of the address and updated TSN of the current redo record in the tracking record; p. 6 is initiated;
6 - запись страницы БД во внешнюю память.6 - writing a database page to external memory.
Формируют журнал, состоящий из определяемого пользователем числа файлов журнала заданного размера, содержащий множество журнальных записей различного типа, среди которых формируют в том числе записи, каждая из которых описывает redo-обновление только на одной странице одной из таблиц БД и предназначена для доката обновления в БД, которое не было записано во внешнюю память (могло быть потеряно в случае аппаратного или программного сбоя).A log is formed, which consists of a user-defined number of log files of a given size, containing many journal entries of various types, among which are formed records, each of which describes a redo update on only one page of one of the database tables and is intended for updating the database that was not written to external memory (could be lost in the event of a hardware or software failure).
В структуру записи redo-обновления включают:The redo update record structure includes:
- поле TSN - time sequence number - синтетическое время СУБД, представленное уникальной последовательно возрастающей числовой комбинацией;- TSN field - time sequence number - synthetic DBMS time represented by a unique sequentially increasing numerical combination;
- обновление и его длину,- update and its length,
- адрес обновления - номер страницы файла таблицы и смещение в ней,- update address - page number of the table file and offset in it,
- поле обратной ссылки - журнальный адрес предыдущей записи транзакции для выполнения откатов транзакций, причем значение поля ссылки содержит номер файла журнала и смещение в нем.- backlink field - the journal address of the previous transaction record for performing rollbacks of transactions, and the value of the link field contains the number of the log file and the offset in it.
Поддерживаемый протокол журнализации транзакций write-ahead logging [4] (http://en.wikipedia.org/wiki/Write-ahead_logging) или используемый в описании патента [3] US 6,173,292 подразумевает, что записи журнала, отображающие изменения каких-либо данных, должны успешно сохраниться во внешней памяти прежде, чем эти измененные данные начнут сохраняться во внешней памяти БД.The supported transaction logging protocol write-ahead logging [4] (http://en.wikipedia.org/wiki/Write-ahead_logging) or used in patent specification [3] US 6,173,292 implies that journal entries displaying changes in any data must be successfully stored in external memory before these changed data begin to be saved in the external memory of the database.
Для этого достаточно отслеживать присутствие несохраненных обновлений в журнале всякий раз, как измененные страницы БД готовятся к записи во внешнюю память, и предварительно сбрасывать эти обновления в текущий файл журнала.To do this, it is enough to monitor the presence of unsaved updates in the journal each time the changed database pages are prepared for writing to external memory, and first dump these updates into the current log file.
Необходим также принудительный сброс журнальных обновлений в файл(ы) по окончании фиксации транзакции.You also need to force log updates to file (s) at the end of transaction commit.
В период рестарта также поддерживают протокол write-ahead logging: прежде чем пропущенное обновление, накатываемое в страницу БД, сохранится на запоминающем устройстве, соответствующая этому обновлению запись журнала с обновленным полем, TSN должна уже быть сохранена в файле журнала.During the restart period, the write-ahead logging protocol is also supported: before a missed update rolled into the database page is stored on the storage device, the corresponding log entry with the updated field corresponding to this update, the TSN must already be saved in the log file.
При рестарте накатывают сначала на физическом уровне (переносят в БД) все зарегистрированные в журнале обновления, которые не попали в БД. Затем выполняют откаты всех незавершенных транзакций на логическом уровне.When restarting, they roll first at the physical level (transfer to the database) all updates registered in the log that did not fall into the database. Then rollbacks of all pending transactions at the logical level are performed.
Такой порядок работы имеет принципиальное значение.This order of work is of fundamental importance.
Рестарт при этом выполняют в три прохода:Restart is performed in three passes:
первый - аналитический проход, в котором определяют адрес последней, предназначенной к накату (переносу в БД), журнальной записи и адрес размещения служебной записи слежения, оценивают состояние тех страниц в БД, которые потенциально предназначены к накату пропущенных обновлений (переносу в БД невыполненных обновлений), и информацию о которых извлекают при проходе по журналу из записей, описывающих redo-обновления, и определяют состояние всех транзакций;the first is an analytical passage in which the address of the last logbook intended for roll-over (transfer to the database) and the location of the tracking service record are determined, the state of those pages in the database that are potentially designed for roll-through of missed updates (transfer of failed updates to the database) is estimated , and information about which is extracted during the passage through the log from entries describing redo-updates, and determine the status of all transactions;
второй - redo-проход, при котором выполняют накат пропущенных обновлений (перенос в БД невыполненных обновлений) и для каждой неоконченной транзакции в записи о ее начале выставляют соответствующий признак;the second is a redo-pass, in which skipped updates are rolled forward (transfer of failed updates to the database) and for each unfinished transaction, an appropriate sign is set in the record about its beginning;
третий - undo-проход, при котором выполняют откат всех незавершенных транзакций, а именно тех, которые не были закоммичены (зафиксированы) или не до конца осуществили откат.the third is an undo-pass, in which all pending transactions are rolled back, namely those that have not been committed (committed) or have not fully rolled back.
Причем в аналитическом проходе:Moreover, in the analytical passage:
заполняют массив состояний транзакций, хранимый в оперативной памяти и логически состоящий из двух полей: поля идентификатора (ID) транзакции и поля битовых флагов;fill in an array of transaction states stored in RAM and logically consisting of two fields: transaction identifier (ID) field and bit flag field;
массив заполняют в аналитическом проходе, а затем используют в undo-проходе;the array is filled in the analytical pass, and then used in the undo pass;
поле битовых флагов включает следующие значения:the bit flag field includes the following values:
транзакция не была закоммичена,The transaction has not been committed
транзакция не до конца осуществила откат,The transaction did not complete the rollback,
транзакция представляет собой операцию над метаданными,a transaction is an operation on metadata,
транзакция содержит последнюю незаконченную журнальную операцию и требует отката на физическом уровне.The transaction contains the last unfinished journal operation and requires rollback at the physical level.
В redo-проходе:In the redo pass:
перед записью измененной страницы во внешнюю память БД изменяют во внешней памяти журнала поля TSN всех redo-обновлений, касающихся этой измененной страницы;Before writing the changed page to the external memory, the databases change the TSN fields of all redo-updates related to this changed page in the external memory of the journal;
используют служебную запись слежения, сохраненную в соответствующем файле в конце журнала до начала redo-прохода, для отслеживания адреса и поля TSN текущего накатываемого redo-обновления; запись слежения имеет небольшую длину и предназначена для отслеживания журнального адреса текущего redo-обновления, предназначенного к переносу в БД;use the tracking service record stored in the corresponding file at the end of the log before the start of the redo pass to track the address and TSN field of the current rolling redo update; Tracking record is short and designed to track the journal address of the current redo-update, intended for transfer to the database;
служебную запись слежения и redo-обновления журнала сбрасывают во внешнюю память журнала (вместе с несохраненными обновлениями в журнале) каждый раз, когда измененные данные БД готовят к записи в БД;Tracking service record and redo-log updates are dumped into the external memory of the log (together with unsaved updates in the log) each time the changed database data is prepared for writing to the database;
при этом структура служебной записи содержит поля:the structure of the service record contains the fields:
cpFlag - флаги состояния рестарта в redo-проходе или undo-проходе (проход аналитический, redo-/undo-проход) и существования/отсутствия контрольной точки, выставленной по окончании redo-прохода (см. ниже);cpFlag - flags of the restart status in the redo-pass or undo-pass (analytical pass, redo- / undo-pass) and the existence / absence of a control point set at the end of the redo-pass (see below);
startTSN - значение синтетического времени СУБД перед первым восстановлением по журналу;startTSN - DBMS synthetic time value before the first log recovery;
specAddr - адрес в журнале текущей записи redo-обновления, которое будет накатываться в базу данных (предназначено к переносу в БД);specAddr - the address in the log of the current redo-update record that will be rolled into the database (intended for transfer to the database);
specTSN - TSN текущей журнальной записи redo-обновления, которое будет накатываться в БД (предназначено к переносу в БД).specTSN - TSN of the current redo-update journal entry that will be rolled into the database (intended for transfer to the database).
Предназначенные к накату в БД (переносу в БД) обновления в redo-проходе определяют путем сравнением полей TSN каждой журнальной записи redo-обновления и поля TSN заголовка соответствующей страницы БД, на которой выполняют обновление. При этом, если поле TSN журнальной записи больше поля TSN заголовка страницы, обновление считают необходимым для наката (переноса в страницу). В противном случае сравнение полей TSN продолжают с использованием значений полей из служебной записи слежения.The updates to the database (transfer to the database) to be updated in the redo-pass are determined by comparing the TSN fields of each redo-update journal entry and the TSN field of the header of the corresponding database page on which the update is performed. Moreover, if the TSN field of the journal entry is greater than the TSN field of the page header, the update is considered necessary for rolling (transfer to the page). Otherwise, the TSN field comparison is continued using the field values from the tracking service record.
Алгоритм сравнения в этом случае различается в зависимости от того, расположена ли запись до или после адреса текущей записи specAddr из служебной записи слежения, или точно по этому адресу.The comparison algorithm in this case differs depending on whether the record is located before or after the address of the current record specAddr from the tracking service record, or exactly at this address.
Формула сравнения полей TSN содержит следующие поля:The TSN field comparison formula contains the following fields:
logTSN - TSN текущей журнальной записи redo-обновления;logTSN - TSN of the current redo update log entry;
logPtr - адрес текущей журнальной записи redo-обновления;logPtr - address of the current redo update log entry;
dbTSN - TSN из заголовка страницы БД, соответствующей накатываемому redo-обновлению (переносимому в базу redo-обновлению);dbTSN - TSN from the header of the database page corresponding to the rolled redo-update (transferred to the redo-update database);
startTSN - значение синтетического времени СУБД TSN, отсеченное перед началом самого первого восстановления рестарта (на начало самого первого восстановления рестарта, - этот TSN необходим, чтобы определить страницы БД, ушедшие во внешнюю память уже в процессе восстановления по журналу);startTSN - TSN DBMS synthetic time value, cut off before the very first restart restore (at the beginning of the very first restart restore - this TSN is necessary to determine the database pages that went into external memory during the log recovery process);
resTSN - значение синтетического времени СУБД TSN, отсеченное перед началом текущего восстановления рестарта (на начало текущего восстановления рестарта; используется для определения страниц БД, ушедших во внешнюю память в процессе текущего восстановления по журналу, в случае первого восстановления, например, это значение совпадает со startTSN);resTSN - TSN DBMS synthetic time value cut off before the start of the restart recovery (at the beginning of the current restart recovery; used to determine the database pages that went into external memory during the current log recovery, in the case of the first recovery, for example, this value coincides with startTSN );
specPtr - адрес последней накатившейся в БД записи redo-обновления из служебной записи слежения (перенесенной в страницу БД записи redo-обновления из служебной записи слежения);specPtr - address of the last redo-update record rolled into the database from the tracking service record (transferred to the database page of the redo-update record from the tracking service record);
specTSN - TSN последней накатившейся в БД записи redo-обновления из служебной записи слежения (перенесенной в страницу БД записи redo-обновления из служебной записи слежения).specTSN - TSN of the last redo update record that has rolled into the database from the tracking service record (transferred to the database page of the redo update record from the tracking record).
Если по результатам сравнения полей TSN выявлено, что обновление необходимо для наката (переноса), поле TSN в записи этого обновления в пуле журнала (оперативной памяти) изменяют в соответствии с текущим синтетическим временем СУБД, а само обновление вносят в поле соответствующей страницы БД.If, according to the results of comparing the TSN fields, it is revealed that the update is necessary for roll-over (transfer), the TSN field in the record of this update in the journal pool (RAM) is changed in accordance with the current synthetic time of the DBMS, and the update is made in the field of the corresponding database page.
Обновленное поле TSN впоследствии служит основой для сравнения полей TSN по той же формуле для случая повторного (и т.д.) восстановления из-за возможных прерываний процесса рестарта, например, по причине сбоя оборудования или операционной системы.The updated TSN field subsequently serves as the basis for comparing TSN fields using the same formula for the case of repeated (etc.) restoration due to possible interruptions in the restart process, for example, due to a hardware or operating system failure.
Повторное восстановление при этом может начинаться с контрольной точки, выставленной в redo-проходе прерванного рестарта в некоторый момент времени. Под контрольной точкой мы понимаем принудительное сохранение во внешней памяти всех обновлений, уже перенесенных в БД к моменту ее старта.In this case, repeated recovery may begin from a checkpoint set in the redo-pass of the interrupted restart at some point in time. By checkpoint, we mean the forced saving in the external memory of all updates already transferred to the database at the time of its launch.
По окончании redo-прохода сохраняют все обновления в БД, накатившиеся к моменту ее старта посредством сброса всех обновленных страниц оперативной памяти во внешнюю память, при этом в служебную запись слежения ставят признак окончания redo-прохода.At the end of the redo-pass, all updates are saved in the database, rolled up to the moment of its start by resetting all updated pages of the RAM into external memory, while the redo-pass is signaled in the tracking service record.
Пример сравнения полей TSN в redo-проходе теплого рестарта показан на фиг.4.An example of comparing TSN fields in a warm restart redo-pass is shown in FIG. 4.
Обновленное поле TSN записывают и впоследствии используют как основу для сравнения полей TSN в случае повторного восстановления данных в БД из-за возможных отказов СУБД в процессе рестарта, повторное восстановление данных начинают с начала журнала.The updated TSN field is recorded and subsequently used as a basis for comparing TSN fields in the case of repeated data recovery in the database due to possible DBMS failures during the restart process; data recovery is started from the beginning of the log.
Если в аналитическом проходе выявлены незакоммиченные (незавершенные) транзакции, то они откатываются на логическом уровне в undo-проходе рестарта. При этом redo-журнал сканируют по записям от конца к началу. Откат данных на физическом уровне применяют только для незаконченных в журнале операций, записанных последними, для поддержания физической непротиворечивости БД.If non-committed (incomplete) transactions are detected in the analytical pass, then they are rolled back at a logical level in the undo restart pass. At the same time, the redo log is scanned from records from end to beginning. The rollback of data at the physical level is used only for the operations that were last recorded in the log that are incomplete in order to maintain the physical consistency of the database.
Все изменения данных в БД, вызываемые откатами, протоколируют в журнале, как любые действия по модификации БД, формируя файлы записей отката в undo-журнале. Эти изменения начинаются в первом резервном файле и формируют часть журнала, назовем ее undo-журналом. Поле ссылки в записях отката в undo-журнале, содержащее адрес журнальной записи из redo-журнала, откат которой она описывает, используют для корреляции адресов в читаемом redo-журнале и растущем undo-журнале.All data changes in the database caused by rollbacks are logged in the log, like any actions to modify the database, forming rollback record files in the undo log. These changes begin in the first backup file and form part of the log, let's call it an undo log. The link field in rollback entries in the undo log containing the address of the log entry from the redo log, the rollback of which it describes, is used to correlate addresses in the read redo log and the growing undo log.
Протоколирование откатов в undo-проходе обеспечивают посредством существующего кольца файлов redo-журнала и двух резервных файлов, имеющих размер файла redo-журнала, которые предварительно резервируют.Logging rollbacks in the undo-pass is provided through the existing ring of redo-log files and two backup files that have the size of the redo-log file that are pre-reserved.
В начале undo-прохода первый резервный файл переименовывают и включают в кольцо файлов redo-журнала последним файлом, в который переносят служебную запись слежения, а затем выполняют протоколирование откатов незакоммиченных транзакций (незавершенных транзакций) до тех пор, пока пространство этого резервного файла будет заполнено, после чего включают в кольцо файлов undo-журнала второй резервный файл.At the beginning of the undo pass, the first backup file is renamed and included in the redo-log file ring with the last file into which the tracking service record is transferred, and then logs rollbacks of non-closed transactions (pending transactions) until the space of this backup file is full, after which a second backup file is included in the undo-log file ring.
Включение переименованных резервных файлов в кольцо журнала в undo-проходе теплого рестарта показано на фиг.5.The inclusion of renamed backup files in the log ring in the undo-pass warm restart is shown in Fig.5.
Поясним, исходя из чего выбрано количество резервных файлов. Поскольку наименьшей единицей блокирования в заявляемом способе является кортеж, а не более крупный объект БД (например, страница), undo-действия могут не быть точной инверсией первичных действий транзакции из-за параллельных действий других транзакций. Поэтому первый резервный файл отводится под протоколирование отката транзакций из последнего файла redo-журнала, а второй - на протоколирование возможных дополнительных действий, совершаемых при этом в базе данных - расширение файла на N страниц, изменение битовой карты и т.д. Причем объем протоколирования этих возможных дополнительных действий незначителен по сравнению с объемом протокола операции, вызвавшей эти действия. Целый дополнительный файл выделяется, исходя из избыточного предположения, что все операции откатываемых транзакций могли привести к таким дополнительным действиям.Let us explain on the basis of which the number of backup files is selected. Since the smallest blocking unit in the claimed method is a tuple, and not a larger database object (for example, a page), undo actions may not be an exact inversion of the primary transaction actions due to parallel actions of other transactions. Therefore, the first backup file is allocated for logging rollback transactions from the last redo-log file, and the second for logging possible additional actions that are performed in the database — file extension by N pages, bitmap change, etc. Moreover, the amount of logging of these possible additional actions is negligible compared to the volume of the protocol of the operation that caused these actions. A whole additional file is allocated, based on the excessive assumption that all operations of rolled back transactions could lead to such additional actions.
Например, откат операции удаления строки таблицы может привести в результате к расширению файла данных или, если таблица индексирована, к изменению структуры страниц ее индекса(ов) на отличную от той, которая была в начале операции удаления. Поэтому откат такой операции будет содержать не только собственно добавление удаленной строки, но и дополнительные операции, в данном случае, протоколирование операции расширения файла (и/или изменения в индексах).For example, a rollback of a delete operation of a table row may result in an extension of the data file or, if the table is indexed, in a change in the page structure of its index (s) to that which was at the beginning of the delete operation. Therefore, the rollback of such an operation will contain not only the actual addition of the deleted row, but also additional operations, in this case, logging the file extension operation (and / or changes in the indexes).
Откаты в undo-проходе происходят в соответствии с массивом состояний транзакций, который заполняется в аналитическом проходе рестарта и постоянно присутствует в оперативной памяти. В процессе undo-прохода из массива состояний транзакций последовательно исключают полностью откатившиеся незаконченные транзакции. При этом в undo-журнал каждый раз поступает соответствующая запись об изменении состояния массива транзакций.Rollbacks in the undo pass occur in accordance with an array of transaction states, which is populated in the analytical restart pass and is constantly present in the RAM. In the process of undo-pass from the array of transaction states, completely rolled back unfinished transactions are sequentially excluded. In this case, the corresponding entry about the change in the state of the transaction array is received in the undo log every time.
В случае повторного рестарта (из-за возможных прерываний процесса рестарта, например, по причине сбоя оборудования или операционной системы), если отказ системы произошел на стадии undo-прохода, рестарт в три прохода используют только для undo-журнала. При этом массив состояний транзакций предварительно заполняют в ходе просмотра redo-журнала в соответствии с записями, описывающими начало транзакций, и при сканировании в аналитическом проходе undo-журнала корректируют в соответствии с журнальными записями об изменении состояния этого массива. Также в аналитическом проходе по содержимому поля ссылки в последней записи undo-журнала определяют адрес последней откатившейся записи redo-обновления в redo-журнале. В redo-проходе по undo-журналу все пропущенные откатные обновления накатывают в БД (переносят в БД).In the event of a repeated restart (due to possible interruptions in the restart process, for example, due to a hardware or operating system failure), if the system crashed at the undo-pass stage, a three-pass restart is used only for the undo-log. At the same time, the array of transaction states is pre-populated during the viewing of the redo-log in accordance with the records describing the beginning of the transactions, and when scanning in the analytical pass, the undo-log is corrected in accordance with the journal entries about the state change of this array. Also, in the analytical pass, the contents of the link field in the last undo log record determine the address of the last rolled redo update record in the redo log. In the redo-pass through the undo-log, all missed rollback updates are rolled into the database (transferred to the database).
Используя сканирование файлов записей в redo-журнале от конца к началу, смену номера читаемого файла на предыдущий номер отражают в undo-журнале в содержимом поля ссылки очередной записи. Как только очередной файл записей redo-журнала полностью прочитан, содержимое файлов записей undo-журнала, включая последнюю запись, принудительно сбрасывают во внешнюю память, а полностью прочитанный файл записей redo-журнала переименовывают в следующий файл записей кольца файлов undo-журнала, если этого требует наличие транзакций, предназначенных к откату.Using a scan of record files in the redo log from end to top, changing the number of the read file to the previous number is reflected in the undo log in the contents of the link field of the next record. As soon as the next redo log file is fully read, the contents of the undo log file, including the last one, are forcibly flushed to external memory, and the fully read redo log file is renamed to the next undo log file ring entry file, if required presence of transactions intended for rollback.
Когда транзакций, предназначенных к откату, больше не обнаруживают, все откатные обновления сбрасывают в БД и ставят в запись слежения признак окончания undo-прохода.When transactions destined for rollback are no longer detected, all rollback updates are discarded in the database and put in the tracking record a sign of the end of the undo-pass.
Номер файла в redo-журнале LastRedoFile, в котором содержится последняя откатившаяся запись, известен из содержимого ссылки последней записи в undo-журнале. Считая этот файл последним в redo-журнале, проверяют наличие предыдущих файлов в redo-журнале, начиная с LastRedoFile - 1. Если их количество, включая последний файл, меньше размера кольца файлов, добавляют недостающие файлы, переименовав последовательно файлы undo-журнала, начиная с номера LastRedoFile + 1. Файл с таким номером может отсутствовать, т.к. переименование файлов redo-журнале в undo-проходе могло породить пропуски в нумерации. Тогда переименовывают в следующий файл, и т.д. Когда размер кольца файлов восстановлен до требуемого размера, оставшиеся файлы переименовывают в два резервных файла. На фиг.6 показано восстановление размеров кольца журнала и количества резервных файлов по окончании undo-прохода теплого рестарта.The file number in the redo log LastRedoFile, which contains the last rolled record, is known from the contents of the link of the last record in the undo log. Considering this file to be the last in the redo log, check for the presence of previous files in the redo log, starting with LastRedoFile - 1. If their number, including the last file, is less than the size of the file ring, add the missing files, renaming the undo log files sequentially, starting with LastRedoFile + 1 numbers. A file with this number may not be present, because renaming redo-log files in an undo-pass could cause numbering gaps. Then rename to the next file, etc. When the file ring size is restored to the required size, the remaining files are renamed into two backup files. Figure 6 shows the restoration of the size of the log ring and the number of backup files at the end of the undo-pass warm restart.
По окончании рестарта с откатом незавершенных транзакций, начальный адрес файла записей redo-журнала для нового цикла будет равен адресу последней откатившейся записи в одном из файлов записей undo-журнала, а количество файлов записей undo-журнала будет всегда равно размеру кольца журнала и двух резервных файлов.At the end of the restart with the rollback of incomplete transactions, the starting address of the redo log file for the new cycle will be equal to the address of the last rolled record in one of the undo log file, and the number of undo log files will always be the size of the log ring and two backup files .
Заявляемый способ восстановления данных в СУБД по описанному выше алгоритму осуществляют на известных устройствах, используемых в вычислительных сетях (вычислительной технике), и не требуется дополнительных существенных аппаратных затрат.The inventive method of data recovery in a DBMS according to the algorithm described above is carried out on known devices used in computer networks (computer technology), and additional significant hardware costs are not required.
Для осуществления изобретения необходимы 32-х и более разрядные процессоры (intel старше i386, AMD, IBM, MIPS, ARM, NVidia, Qualcomm и т.д.), поскольку объемы данных, которыми оперирует СУБД, требуют, как минимум, 32-х разрядных вычислений, минимальный размер оперативной памяти устройства - 1 МБ (тип оперативной памяти может быть любым), требования к внешней памяти для размещения журнала транзакций и рестарта ограничиваются только требованиями к его ведению, поскольку сам процесс теплого рестарта не использует дополнительной внешней памяти.To implement the invention, 32 or more bit processors are required (intel older than i386, AMD, IBM, MIPS, ARM, NVidia, Qualcomm, etc.), because the data volumes that the DBMS operates require at least 32 bit calculations, the minimum size of the device’s RAM is 1 MB (the type of RAM can be any), the requirements for external memory for placing the transaction log and restart are limited only by the requirements for maintaining it, since the warm restart process itself does not use additional external memory.
Технологические потребности заявляемого изобретения позволяют использовать устройства различных классов (смартфоны, контроллеры, планшетные компьютеры, настольные компьютеры, серверы и т.п.) и различного назначения (центры обработки данных, медицинское, технологическое, навигационное, аэрокосмическое оборудование и т.д.).The technological needs of the claimed invention allow the use of devices of various classes (smartphones, controllers, tablet computers, desktop computers, servers, etc.) and for various purposes (data centers, medical, technological, navigation, aerospace equipment, etc.).
Предполагается, что заявляемый способ ведения журнала транзакций и рестарта используется в СУБД, ориентированной на минимальность используемых ресурсов, например, СУБД ЛИНТЕР [5] (В.Е. Максимов, Л.А. Козленко, С.П. Маркин, И.А. Бойченко, Защищенная реляционная СУБД ЛИНТЕР, Открытые системы №11 12/1999), [6] (В. Борисов, В. Максимов, СУБД для специализированных систем; Мир ПК №5, 2007), [7] (http://ru.wikipedia.org/wiki/ЛИНТЕР).It is assumed that the claimed method of logging transactions and restart is used in a DBMS focused on the minimality of resources used, for example, DBMS Linter [5] (V.E. Maksimov, L.A. Kozlenko, S.P. Markin, I.A. Boychenko, Protected Relational DBMS Linter, Open Systems No. 11 12/1999), [6] (V. Borisov, V. Maksimov, DBMS for specialized systems; PC World No. 5, 2007), [7] (http: // ru .wikipedia.org / wiki / LINTER).
Таким образом, заявляемый способ восстановления данных в СУБД позволяет после программного или аппаратного сбоя восстановить данные в БД до последнего по времени согласованного состояния данных БД, что достигается за счет того, что:Thus, the claimed method of data recovery in a DBMS allows, after a software or hardware failure, to restore data in the database to the last agreed-upon state of the database data, which is achieved due to the fact that:
- формируют единый журнал транзакций и рестарта, состоящий из заданного числа файлов определенного размера, при этом число и размер файлов задаются пользователем, при этом предлагаемая модель журнала позволяет использовать в процессе рестарта системы сформированное файловое пространство журнала без увеличения размера;- form a single transaction and restart log, consisting of a given number of files of a certain size, while the number and size of files are set by the user, while the proposed log model allows you to use the generated log file space in the system restart process without increasing the size;
- по достижении количества файлов, заданного пользователем, выполняют переиспользование более ранних файлов с новым номером - журнал замыкают в кольцо, при этом файлам в кольце назначают последовательно возрастающую нумерацию, причем, если наличие незавершенной транзакции(ий) в файле не позволяет переиспользовать его, создают новый файл и временно расширяют кольцо журнала до тех пор, пока транзакция(ии) не завершится(шатся), после чего кольцо возвращают к исходному числу файлов;- upon reaching the number of files specified by the user, reuse of earlier files with a new number is performed - the journal is closed in a ring, while the files in the ring are assigned sequentially increasing numbering, and if the presence of an incomplete transaction (s) in the file does not allow reusing it, create a new file and temporarily expand the log ring until the transaction (s) is completed (staggered), after which the ring is returned to the original number of files;
- параметры журнального пространства (кольца), задаваемые пользователем, определяются интенсивностью и длительностью транзакций в конкретной базе данных, причем при обоснованно заданном размере кольца дополнительно создают два резервных файла, которые резервируют дисковое пространство указанного размера, которые в процессе работы используются под файлы журнала посредством переименования, в частности, для откатов незавершенных транзакций при рестарте СУБД после системного сбоя.- parameters of the journal space (rings), set by the user, are determined by the intensity and duration of transactions in a specific database, and with a reasonably specified ring size, two additional backup files are created that reserve disk space of a specified size, which are used for log files by renaming , in particular, for rollbacks of incomplete transactions when restarting a DBMS after a system failure.
СПИСОК ЛИТЕРАТУРЫBIBLIOGRAPHY
1. Управление транзакциями (сайт-форум) (http://citforum.ru/programming/32less/les310.shtml).1. Transaction management (site-forum) (http://citforum.ru/programming/32less/les310.shtml).
2. Патент US 5,966,706 «Local logging in a distributed database management computer system». Int. Cl. G06F 11/14.2. Patent US 5,966,706 "Local logging in a distributed database management computer system". Int. Cl. G06F 11/14.
3. Патент US 6,173,292 «Data recovery in a transactional database using write-ahead logging and file caching». Int. Cl.: G06F 11/14 (2006.01.); G06F 012/00.3. US patent 6,173,292 "Data recovery in a transactional database using write-ahead logging and file caching". Int. Cl .: G06F 11/14 (2006.01.); G06F 012/00.
4. Протокол журнализации транзакций write-ahead logging (http://en.wikipedia.org/wiki/Write-ahead_logging).4. The write-ahead logging transaction logging protocol (http://en.wikipedia.org/wiki/Write-ahead_logging).
5. В.Е. Максимов, Л.А. Козленко, С.П. Маркин, И.А. Бойченко. Защищенная реляционная СУБД ЛИНТЕР, Открытые системы №11 12/1999.5. V.E. Maximov, L.A. Kozlenko, S.P. Markin, I.A. Boychenko. Secure Relational DBMS Linter, Open Systems No. 11 12/1999.
6. В. Борисов, В. Максимов. СУБД для специализированных систем, Мир ПК №5, 2007).6. V. Borisov, V. Maximov. DBMS for specialized systems, PC World No. 5, 2007).
7. ЛИНТЕР - материал из Википедии - свободной энциклопедии (http://ru.wikipedia.org/wiki/ЛИНТЕР).7. Linter - material from Wikipedia - the free encyclopedia (http://ru.wikipedia.org/wiki/Linter).
Claims (4)
Priority Applications (1)
| Application Number | Priority Date | Filing Date | Title |
|---|---|---|---|
| RU2013128323/08A RU2526753C1 (en) | 2013-06-20 | 2013-06-20 | Method for data recovery in database management system |
Applications Claiming Priority (1)
| Application Number | Priority Date | Filing Date | Title |
|---|---|---|---|
| RU2013128323/08A RU2526753C1 (en) | 2013-06-20 | 2013-06-20 | Method for data recovery in database management system |
Publications (1)
| Publication Number | Publication Date |
|---|---|
| RU2526753C1 true RU2526753C1 (en) | 2014-08-27 |
Family
ID=51456244
Family Applications (1)
| Application Number | Title | Priority Date | Filing Date |
|---|---|---|---|
| RU2013128323/08A RU2526753C1 (en) | 2013-06-20 | 2013-06-20 | Method for data recovery in database management system |
Country Status (1)
| Country | Link |
|---|---|
| RU (1) | RU2526753C1 (en) |
Cited By (4)
| Publication number | Priority date | Publication date | Assignee | Title |
|---|---|---|---|---|
| RU2666287C1 (en) * | 2017-03-31 | 2018-09-06 | Александр Олегович Попов | Method of development, storage and use of compiled to the binary representation of programs in database tables |
| CN110457284A (en) * | 2019-06-05 | 2019-11-15 | 黄疆 | More time point data restoration methods and system based on SQLServer database |
| CN114297003A (en) * | 2021-12-31 | 2022-04-08 | 北京人大金仓信息技术股份有限公司 | Database node fault recovery method, device, equipment and storage medium |
| RU2825077C1 (en) * | 2024-03-24 | 2024-08-19 | Общество с ограниченной ответственностью "Киберпротект" (ООО "Киберпротект") | Method and system for granular recovery of backup copy of database |
Citations (6)
| Publication number | Priority date | Publication date | Assignee | Title |
|---|---|---|---|---|
| RU2130643C1 (en) * | 1998-10-21 | 1999-05-20 | Открытое акционерное общество "Всероссийский научно-исследовательский институт автоматизации управления в непромышленной сфере" | Method for accessing data in database management system |
| US5966706A (en) * | 1997-02-19 | 1999-10-12 | At&T Corp | Local logging in a distributed database management computer system |
| US6173292B1 (en) * | 1998-03-04 | 2001-01-09 | International Business Machines Corporation | Data recovery in a transactional database using write-ahead logging and file caching |
| RU2208834C2 (en) * | 1997-05-29 | 2003-07-20 | Интернэшнл Бизнес Машинз Корпорейшн | Method and system for recovery of database integrity in system of bitslice databases without resource sharing using shared virtual discs and automated data medium for them |
| US6898609B2 (en) * | 2002-05-10 | 2005-05-24 | Douglas W. Kerwin | Database scattering system |
| US8364648B1 (en) * | 2007-04-09 | 2013-01-29 | Quest Software, Inc. | Recovering a database to any point-in-time in the past with guaranteed data consistency |
-
2013
- 2013-06-20 RU RU2013128323/08A patent/RU2526753C1/en active
Patent Citations (6)
| Publication number | Priority date | Publication date | Assignee | Title |
|---|---|---|---|---|
| US5966706A (en) * | 1997-02-19 | 1999-10-12 | At&T Corp | Local logging in a distributed database management computer system |
| RU2208834C2 (en) * | 1997-05-29 | 2003-07-20 | Интернэшнл Бизнес Машинз Корпорейшн | Method and system for recovery of database integrity in system of bitslice databases without resource sharing using shared virtual discs and automated data medium for them |
| US6173292B1 (en) * | 1998-03-04 | 2001-01-09 | International Business Machines Corporation | Data recovery in a transactional database using write-ahead logging and file caching |
| RU2130643C1 (en) * | 1998-10-21 | 1999-05-20 | Открытое акционерное общество "Всероссийский научно-исследовательский институт автоматизации управления в непромышленной сфере" | Method for accessing data in database management system |
| US6898609B2 (en) * | 2002-05-10 | 2005-05-24 | Douglas W. Kerwin | Database scattering system |
| US8364648B1 (en) * | 2007-04-09 | 2013-01-29 | Quest Software, Inc. | Recovering a database to any point-in-time in the past with guaranteed data consistency |
Cited By (5)
| Publication number | Priority date | Publication date | Assignee | Title |
|---|---|---|---|---|
| RU2666287C1 (en) * | 2017-03-31 | 2018-09-06 | Александр Олегович Попов | Method of development, storage and use of compiled to the binary representation of programs in database tables |
| CN110457284A (en) * | 2019-06-05 | 2019-11-15 | 黄疆 | More time point data restoration methods and system based on SQLServer database |
| CN110457284B (en) * | 2019-06-05 | 2022-11-29 | 黄疆 | Multi-time point data recovery method and system based on SQLServer database |
| CN114297003A (en) * | 2021-12-31 | 2022-04-08 | 北京人大金仓信息技术股份有限公司 | Database node fault recovery method, device, equipment and storage medium |
| RU2825077C1 (en) * | 2024-03-24 | 2024-08-19 | Общество с ограниченной ответственностью "Киберпротект" (ООО "Киберпротект") | Method and system for granular recovery of backup copy of database |
Similar Documents
| Publication | Publication Date | Title |
|---|---|---|
| US8874515B2 (en) | Low level object version tracking using non-volatile memory write generations | |
| US12530319B2 (en) | Database management system | |
| US9223805B2 (en) | Durability implementation plan in an in-memory database system | |
| EP2590086B1 (en) | Columnar database using virtual file data objects | |
| US10318648B2 (en) | Main-memory database checkpointing | |
| US10430298B2 (en) | Versatile in-memory database recovery using logical log records | |
| US9740582B2 (en) | System and method of failover recovery | |
| US7133884B1 (en) | Unobtrusive point-in-time consistent copies | |
| US9069704B2 (en) | Database log replay parallelization | |
| US8949190B2 (en) | Point-in-time database recovery using log holes | |
| US10810092B2 (en) | Checkpoints for document store | |
| US9471622B2 (en) | SCM-conscious transactional key-value store | |
| US11720451B2 (en) | Backup and recovery for distributed database with scalable transaction manager | |
| CN103678608B (en) | Blog management method and device | |
| Padhye et al. | Scalable transaction management with snapshot isolation for NoSQL data storage systems | |
| US20180046548A1 (en) | Method and Apparatus for Tracking Objects in a First Memory | |
| RU2526753C1 (en) | Method for data recovery in database management system | |
| CN114816224A (en) | Data management method and data management device | |
| CN105659214B (en) | Checkpoint settings for data unit collections | |
| Kumar et al. | Database recovery | |
| US11074141B2 (en) | Database recovery using shared memory | |
| Lee et al. | Validity tracking based log management for in-memory databases | |
| CN116257531B (en) | Database space recovery method | |
| JP6891533B2 (en) | Database device | |
| Lee et al. | A fast commit protocol for distributed main memory database systems |