RU2787143C2 - Method for replication of information in databases with encoding with simple syntactic replacement based on direct replacement table - Google Patents

Method for replication of information in databases with encoding with simple syntactic replacement based on direct replacement table Download PDF

Info

Publication number
RU2787143C2
RU2787143C2 RU2021111536A RU2021111536A RU2787143C2 RU 2787143 C2 RU2787143 C2 RU 2787143C2 RU 2021111536 A RU2021111536 A RU 2021111536A RU 2021111536 A RU2021111536 A RU 2021111536A RU 2787143 C2 RU2787143 C2 RU 2787143C2
Authority
RU
Russia
Prior art keywords
data
value
dictionary
databases
src
Prior art date
Application number
RU2021111536A
Other languages
Russian (ru)
Other versions
RU2021111536A (en
Inventor
Игорь Дмитриевич Королев
Евгений Сергеевич Литвинов
Сергей Владимирович Мулюкин
Максим Олегович Ахтямов
Роман Иванович Захарченко
Федор Романович Ефимец
Денис Игоревич Маркин
Сергей Олегович Костров
Original Assignee
федеральное государственное казенное военное образовательное учреждение высшего образования "Краснодарское высшее военное орденов Жукова и Октябрьской Революции Краснознаменное училище имени генерала армии С.М. Штеменко" Министерства обороны Российской Федерации
Filing date
Publication date
Application filed by федеральное государственное казенное военное образовательное учреждение высшего образования "Краснодарское высшее военное орденов Жукова и Октябрьской Революции Краснознаменное училище имени генерала армии С.М. Штеменко" Министерства обороны Российской Федерации filed Critical федеральное государственное казенное военное образовательное учреждение высшего образования "Краснодарское высшее военное орденов Жукова и Октябрьской Революции Краснознаменное училище имени генерала армии С.М. Штеменко" Министерства обороны Российской Федерации
Publication of RU2021111536A publication Critical patent/RU2021111536A/en
Application granted granted Critical
Publication of RU2787143C2 publication Critical patent/RU2787143C2/en

Links

Images

Abstract

FIELD: information technologies.
SUBSTANCE: method consists in that, in a system made in the form of a block for provision of a local network between the first and the second computers containing synchronized databases, a block for synchronization of operational modes of computers, a block for comparison of data in changeable databases, a block for isolation of mismatched fragments in changeable databases, as well as a block for introduction of changes in changeable databases, two blocks for data encoding-decoding are integrated, allowing for encoding of incoming and outcoming requests used during information replication in databases.
EFFECT: reduction in a volume of transmitted data without loss of information content used in information replication in distributed databases, in particular, in relation to two computers, in each of which a database similar by structure is downloaded, with a constant base of knowledge and independently changeable and complemented information in a base of clients and researches, and used for periodic synchronization of the database in both computers.
1 cl, 7 dwg

Description

Область техники, к которой относится изобретениеThe field of technology to which the invention belongs

Заявленное изобретение относится к информационным технологиям, в частности, к методам и средствам обеспечения информационного обмена между компьютерными системами с использованием механизма компрессии передаваемых данных кодированием запросов простой синтаксической заменой на основе таблицы кодировки и может быть использовано для поддержания в идентичном состоянии баз данных (БД), размещенных в независимых компьютерах.The claimed invention relates to information technologies, in particular, to methods and means of providing information exchange between computer systems using the mechanism of data transmission compression by encoding requests by simple syntactic replacement based on the encoding table and can be used to maintain databases (DB) in an identical state, hosted on independent computers.

Уровень техникиState of the art

а) Описание аналоговa) Description of analogues

Известен способ поточного кодирования дискретной информации по патенту РФ №2005120259 (класс Н04Н 9/00 заявл. 29.06.2005). В известном способе осуществляют поточное побитовое кодирование передаваемых данных с целью защиты информации от несанкционированного доступа.A known method of streaming encoding of discrete information according to the patent of the Russian Federation No. 2005120259 (class H04H 9/00 bid. 29.06.2005). In a known method, streaming bit-by-bit encoding of transmitted data is carried out in order to protect information from unauthorized access.

Недостатком данного способа является:The disadvantage of this method is:

данный способ подходит для решения задач защиты передаваемой информации от несанкционированного доступа, но не осуществляет компрессию передаваемых данных в режиме реального времени и не осуществляет репликацию данных между базами данных.this method is suitable for solving the problems of protecting transmitted information from unauthorized access, but does not compress transmitted data in real time and does not replicate data between databases.

Известен способ поточного кодирования дискретной информации по патенту РФ №2205516 (класс H04L 9/00 заявл. 20.02.2002). В известном способе осуществляют поточное побитовое кодирование передаваемых данных с целью защиты информации от несанкционированного доступа.A known method of streaming encoding of discrete information according to the patent of the Russian Federation No. 2205516 (class H04L 9/00 appl. 20.02.2002). In a known method, streaming bit-by-bit encoding of transmitted data is carried out in order to protect information from unauthorized access.

Недостатком данного способа является:The disadvantage of this method is:

данный способ подходит для решения задач защиты передаваемой информации от несанкционированного доступа, но не осуществляет компрессию передаваемых данных в режиме реального времени и не осуществляет репликацию данных между базами данных.this method is suitable for solving the problems of protecting transmitted information from unauthorized access, but does not compress transmitted data in real time and does not replicate data between databases.

Известен способ компрессии-декомпрессии данных и устройство для его осуществления по патенту РФ №2011124978, (класс Н03М 7/30 заявл. 17.06.2011). В известном способе осуществляют блочное преобразование данных с целью уменьшения объема таких данных.A known method of compression-decompression of data and a device for its implementation according to the patent of the Russian Federation No. In a known method, block data transformation is carried out in order to reduce the volume of such data.

Недостатком данного способа является:The disadvantage of this method is:

данный способ подходит для решения задач компрессии данных, но не осуществляет преобразование в поточном режиме и не осуществляет репликацию данных между базами данных.this method is suitable for solving data compression problems, but does not perform streaming conversion and does not replicate data between databases.

б) Описание ближайшего аналога (прототипа)b) Description of the closest analogue (prototype)

Наиболее близкой по своей технической сущности к заявленному способу является система репликации информации в базах данных по патенту РФ №2703961 «Система репликации информации в базах данных», (класс G06F 16/27, заявл. 25.07.2018, опубл. 22.10.2019 бюл. №30). Технический результат системы-прототипа заключается в том, что, при репликации два компьютера соединяют по локальной сети и производят обмен данными между базами данных компьютеров, причем, в каждый из двух компьютеров с установленными в них ORACLE-серверами предварительно загружают базу данных с неизменяемой базой знаний и изменяемой базой данных о клиентах и исследованиях, выполненной с возможностью независимых изменений и дополнений на каждом из двух компьютеров, причем, сначала один из компьютеров переводят в компьютер-источник путем формирования на его ORACLE-сервере обращения к ORACLE-серверу другого компьютера, который переводят в компьютер-приемник, сравнивают данные в их изменяемых базах данных по набору полей, определяющему записи в изменяемых базах данных, выделяют данные, имеющиеся в изменяемой базе данных компьютера-источника и отсутствующие в изменяемой базе данных компьютера-приемника, и вставляют в изменяемую базу данных компьютера-приемника, а затем другой компьютер переводят в компьютер-источник путем формирования на его ORACLE-сервере обращения к ORACLE-серверу первого компьютера, который переводят в компьютер-приемник, и производят указанные выше операции между этими компьютером-источником и компьютером-приемником.The closest in its technical essence to the claimed method is the system for replicating information in databases according to the patent of the Russian Federation No. No. 30). The technical result of the prototype system is that, during replication, two computers are connected via a local network and data is exchanged between computer databases, moreover, a database with an immutable knowledge base is preloaded into each of the two computers with ORACLE servers installed in them. and a changeable database about clients and studies, made with the possibility of independent changes and additions on each of the two computers, moreover, first one of the computers is transferred to the source computer by forming on its ORACLE server a call to the ORACLE server of another computer, which is transferred to the receiving computer, compare the data in their variable databases by a set of fields that define records in the variable databases, extract the data that is in the variable database of the source computer and are absent in the variable database of the receiver computer, and insert it into the variable database destination computer, and then another computer transfer to the source computer by forming on its ORACLE server a call to the ORACLE server of the first computer, which is transferred to the destination computer, and perform the above operations between these source computers and the destination computer.

По сравнению с аналогами, способ-прототип может быть использован в более широкой области примененияCompared with analogues, the prototype method can be used in a wider scope

Недостатками прототипа являются:The disadvantages of the prototype are:

1. Низкая скорость репликации информации при работе с базами данных, содержащими большие объемы данных различных типов при использовании высоко нагруженных каналов связи;1. Low speed of information replication when working with databases containing large amounts of data of various types when using highly loaded communication channels;

2. Невозможность использования нестабильных каналов связи с низкой пропускной способностью;2. Inability to use unstable communication channels with low bandwidth;

3. Отсутствие механизма, обеспечивающего компрессию передаваемых данных в режиме реального времени.3. The absence of a mechanism that provides compression of transmitted data in real time.

В настоящем изобретении предложен способ, позволяющий устранить выявленные недостатки.The present invention proposes a method to eliminate the identified disadvantages.

Раскрытие изобретения (его сущность)Disclosure of the invention (its essence)

а) технический результат, на достижение которого направлено изобретениеa) the technical result to which the invention is directed

Целью заявленного технического решения является разработка системы, позволяющей значительно сократить объем передаваемых данных без утраты информативности, используемой при репликации информации в распределенных базах данных, в частности, применительно к двум компьютерам, в каждый из которых загружена одинаковая по структуре база данных с неизменной базой знаний и независимо изменяемой и дополняемой информацией в базе клиентов и исследований и используемой для периодической синхронизации базы данных в обоих компьютерах.The purpose of the claimed technical solution is to develop a system that can significantly reduce the amount of transmitted data without losing the information content used when replicating information in distributed databases, in particular, in relation to two computers, each of which is loaded with a database of the same structure with an unchanged knowledge base and independently modified and supplemented information in the database of clients and studies and used for periodic synchronization of the database in both computers.

б) совокупность существенных признаковb) a set of essential features

Способ репликации информации в базах данных с использованием механизма кодирования запросов простой синтаксической заменой на основе таблицы кодировки, заключается в том, что в систему, выполненную в виде блока обеспечения локальной сети между первым и вторым компьютерами, содержащими синхронизируемые базы данных, блока синхронизации режимов работы компьютеров, при этом первый и второй входы-выходы блока обеспечения локальной сети между первым и вторым компьютерами соединены с первыми входами-выходами первого и второго компьютеров соответственно, а первый и второй входы-выходы блока синхронизации режимов работы компьютеров соединены со вторыми входами-выходами первого и второго компьютеров соответственно, блока сравнения данных в изменяемых базах данных первый вход-выход которого соединен с третьим входом-выходом блока синхронизации режимов работы компьютеров, блока выделения несовпадающих фрагментов в изменяемых базах данных, первый вход-выход которого соединен со вторым входом-выходом блока сравнения данных в изменяемых базах данных, а также блока внесения изменений в изменяемые базы данных, первый вход-выход которого соединен со вторым входом-выходом блока выделения несовпадающих фрагментов в изменяемых базах данных, вводится блок кодирования-декодирования данных, первый и второй входы-выходы которого соединены с третьими входами-выходами первого и второго компьютера соответственно, а третий и четвертый входы-выходы соединены с четвертыми входами-выходами первого и второго компьютера соответственно.The method of replicating information in databases using the query encoding mechanism by a simple syntactic replacement based on the encoding table consists in the fact that in a system made in the form of a block for providing a local network between the first and second computers containing synchronized databases, a block for synchronizing the operating modes of computers , wherein the first and second inputs-outputs of the block for providing a local network between the first and second computers are connected to the first inputs-outputs of the first and second computers, respectively, and the first and second inputs-outputs of the block for synchronizing the operating modes of computers are connected to the second inputs-outputs of the first and of the second computer, respectively, the block for comparing data in variable databases, the first input-output of which is connected to the third input-output of the block for synchronizing the operating modes of computers, the block for selecting mismatched fragments in variable databases, the first input-output of which is connected to the second input-output m of the block for comparing data in changeable databases, as well as the block for making changes to changeable databases, the first input-output of which is connected to the second input-output of the block for selecting mismatched fragments in changeable databases, a data encoding-decoding block is introduced, the first and second inputs - the outputs of which are connected to the third inputs-outputs of the first and second computers, respectively, and the third and fourth inputs-outputs are connected to the fourth inputs-outputs of the first and second computers, respectively.

Дополнительно, способ репликации информации в базах данных с кодированием простой синтаксической заменой на основе таблицы прямой замены, который основан на выполнении следующих действий: предварительно на основе базы данных создается файл, содержащий словарь замены (таблицу кодировки): принимают информацию, включающую в себя словарь table_names <x1, …, x2, …, xn>, содержащий названия таблиц базы данных, где n - количество таблиц, формируют формируют запрос на подключение к базе данных, в случае если подключение не выполнено, выводится сообщение об ошибке подключения и подтверждают отправку повторного запроса на подключение к базе данных, в случае если отправка подтверждена, выполняют повторное обращение к базе данных, если отправке не подтверждена, происходит завершение работы, если подключение выполнено успешно, формируют маркер номера обрабатываемой таблицы i, изначально равный 1, формирует список data для хранения записей таблицы, формируют запрос на извлечение всех данных из таблицы table_namesi, ответ на запрос записывают в словарь data, и в случае если ответ на запрос представляет собой некорректные данные, выводится сообщение о соответствующей ошибке и подтверждают отправку повторного запроса на подключение к базе данных, а в случае если отправка подтверждена, выполняют повторное обращение к базе данных, если отправка не подтверждена, формируется отчет о проделанной работе и происходит завершение работы, если данные корректны, формируется флаг достижения последней записи data_quantity, записывают в него значение длины словаря data, формируют флаг достижения последнего поля таблицы field_quantity, записывают в него значение длины словаря data0, формируют маркеры j, k, номера обрабатываемого элемента словаря data, формируют маркер t, представляющий собой значение, которое будет поставлено способом синтаксической замены в соответствие данным базы данных, формируют словарь уникальных данных field_unique формата «ключ» : «значение», устанавливают значение маркера k равное 0, устанавливают значение маркера j равное 0, устанавливают значение маркера t равное 0, производится проверка: если в словаре field_unique отсутствует запись с ключом datajk, в словарь field_unique добавляют запись с ключом datajk и значением t, значение t увеличивают на 1, значение j увеличивают на 1, если в словаре field_unique запись с ключом datajk имеется, происходит переход к шагу инкрементирования j, происходит проверка: если последняя запись таблицы не обработана, а именно значение маркера j не равно значению флага data_quantity, происходит возвращение к шагу проверки вхождения datajk в словарь field_unique, если последняя запись таблицы обработана, словарь field_unique записывают в файл таблицы кодировки, очищают словарь field_unique и увеличивают значение маркера k на 1, происходит проверка: если последнее поле таблицы не обработано, а именно значение маркера k не равно значению флага fields_quantity, происходит возвращение к шагу установления значения маркера j, если последнее поле обработано, значение маркера номера обрабатываемой таблицы i увеличивается на 1, происходит проверка: если база данных не обработана полностью, а именно значение флага i больше значения количества таблиц n, происходит переход к шагу создания словаря data, если конец таблицы достигнут, формируется отчет о проделанной работе и происходит завершение работы, процесс передачи запроса к базе данных производится следующим образом: устанавливают соединение с базой данных для приема/передачи данных, если соединение не установлено, выводится сообщение об ошибке соединения и подтверждают установку повторного соединения, в случае если установка повторного соединения подтверждена, выполняют повторное соединение с базой данных, если установка повторного соединения не подтверждена, формируется отчет о проделанной работе и происходит завершение работы, если подключение выполнено успешно, открывают для чтения и записи файл таблицы кодировки, принимают информацию, содержащую пользовательский запрос к базе данных, записывают принятые данные в словарь open_data_list_src, формируют строку кодированных данных encoded_data_src, формируют маркер обхода словаря i и флаг внесения изменений в таблицу кодировки f с начальными значениями, равными 0, формируют флаг достижения конца словаря len_src, записывают в него значение длины словаря open_data_list_src, происходит проверка: если в таблице кодировки имеется значение open_data_list_srci, в encoded_data_src записывают кодированное значение, соответствующее open_data_list_srci, если в таблице кодировки значение open_data_list_srcj отсутствует, в таблицу кодировки заносится значение open_data_list_srci, значение флага f устанавливают равным 1 и переходят к шагу записи кодированного значения в encoded_data_src, значение маркера i увеличивается на 1, происходит проверка: если конец словаря open_data_list_src не достигнут, а именно значение маркера i не равно значению флага len_src, переходят к шагу проверки наличия open_data_list_srcj в таблице кодировки, если конец словаря open_data_list_src достигнут, производят проверку: если флаг внесения изменений в таблицу f равен 0, значение encoded_data_src передается по каналу связи, если флаг f не равен 0, производят синхронизацию таблиц кодировки и переходят к передаче значения encoded_data_src, осуществляют прием переданных данных, записывают принятые данные в словарь encoded_data_list_dst, открывают для чтения таблицу кодировки, формируют строку декодированных данных decoded_data_dst, формируют маркер обхода словаря j с начальным значением 0, формируют флаг достижения конца словаря len_dst, записывают в него значение длины словаря encoded_data_list_dst, записывают в decoded_data_dst декодированное значение, соответствующее encoded_data_list_srcj, увеличивают значение маркера j на 1, производят проверку: если конец словаря encoded_data_list_src не достигнут, а именно значение маркера j не равно значение флага len_dst, переходят к шагу занесения в decoded_data_dst декодированных данных, если конец словаря encoded_data_list_src достигнут, значение decoded_data_dst передается обработчику событий, формируется отчет о проделанной работе и происходит завершение работы.Additionally, a method for replicating information in databases with simple syntactic substitution encoding based on a direct substitution table, which is based on performing the following steps: a file containing a substitution dictionary (encoding table) is first created based on the database: information including a table_names dictionary is received <x 1 , …, x 2 , …, x n >, containing the names of database tables, where n is the number of tables, form a request to connect to the database, if the connection is not successful, a connection error message is displayed and confirm sending a repeated request to connect to the database, if the sending is confirmed, re-accessing the database, if the sending is not confirmed, the work is completed, if the connection is successful, form the marker of the number of the processed table i, initially equal to 1, form the data list to store table records, form a request to retrieve all data from tables table_names i , the response to the request is written to the data dictionary, and if the response to the request is incorrect data, a message is displayed about the corresponding error and confirms the sending of a repeated request to connect to the database, and if the sending is confirmed, a second request is made to the database, if the sending is not confirmed, a report on the work done is generated and the work is completed, if the data is correct, the flag for reaching the last data_quantity record is generated, the value of the length of the data dictionary is written to it, the flag of reaching the last field of the field_quantity table is generated, the value is written to it the length of the dictionary data 0 , form the markers j, k, the numbers of the processed element of the data dictionary, form the marker t, which is a value that will be matched by the syntactic replacement method to the database data, form a dictionary of unique data field_unique of the format "key" : "value" , set marker value k is equal to 0, marker value j is set to 0, marker value t is set to 0, a check is made: if there is no entry with the key data jk in the field_unique dictionary, an entry with the key data jk and value t is added to the field_unique dictionary, the value of t is increased by 1, the value of j is increased by 1, if there is an entry with the key data jk in the field_unique dictionary, the transition to the step of incrementing j takes place, a check is made: if the last table entry is not processed, namely the value of the marker j is not equal to the value of the data_quantity flag, the return to the step of checking the entry of data jk into the field_unique dictionary, if the last table entry is processed, the field_unique dictionary is written to the encoding table file, the field_unique dictionary is cleared and the value of marker k is increased by 1, a check is made: if the last field of the table is not processed, namely the value of marker k is not equal to the value of the fields_quantity flag, it returns to the value setting step the value of the marker j, if the last field is processed, the value of the marker of the number of the processed table i is increased by 1, a check is made: if the database is not fully processed, namely the value of the flag i is greater than the value of the number of tables n, the transition to the step of creating the data dictionary takes place, if the end table is reached, a report on the work done is generated and the work is completed, the process of sending a request to the database is performed as follows: establish a connection to the database for receiving / transmitting data, if the connection is not established, a connection error message is displayed and reconnection is confirmed, if the reconnection is confirmed, the database is reconnected; if the reconnection is not confirmed, a progress report is generated and the work is completed; if the connection is successful, the encoding table file is opened for reading and writing, the information containing containing a user request to the database, write the received data to the open_data_list_src dictionary, form a string of encoded data encoded_data_src, form a dictionary bypass marker i and a flag for making changes to the encoding table f with initial values equal to 0, form the end of dictionary len_src flag, write to it the value of the length of the open_data_list_src dictionary, a check is made: if the value open_data_list_src i is present in the encoding table, the encoded value corresponding to open_data_list_src i is written to encoded_data_src , if the open_data_list_src j value is absent in the encoding table, the value open_data_list_src i is entered into the encoding table, the flag value f is set to 1 and go to the step of writing the encoded value to encoded_data_src, the value of marker i is increased by 1, a check is made: if the end of the open_data_list_src dictionary is not reached, namely the value of marker i is not equal to the value of the flag len_src, go to the check step the presence of open_data_list_src j in the encoding table, if the end of the open_data_list_src dictionary is reached, a check is made: if the flag for making changes to the table f is 0, the encoded_data_src value is transmitted over the communication channel, if the f flag is not equal to 0, the encoding tables are synchronized and proceed to transferring the encoded_data_src value , receive the transmitted data, write the received data to the encoded_data_list_dst dictionary, open the encoding table for reading, form the decoded data string decoded_data_dst, form the dictionary bypass marker j with the initial value 0, form the end of the dictionary end flag len_dst, write the length value of the encoded_data_list_dst dictionary into it, write the decoded value corresponding to encoded_data_list_src j into decoded_data_dst , increase the value of marker j by 1, check: if the end of the encoded_data_list_src dictionary is not reached, namely the value of marker j is not equal to the value of the len_dst flag, go to step beyond If the end of the encoded_data_list_src dictionary is reached, the decoded_data_dst value is passed to the event handler, a progress report is generated, and the work is terminated.

Сопоставительный анализ заявляемого решения с прототипом показывает, что предлагаемый способ отличается от известного:Comparative analysis of the proposed solution with the prototype shows that the proposed method differs from the known:

наличием дополнительного блока, позволяющего производить поточное кодирование-декодирование реплицируемых данных;the presence of an additional block that allows streaming encoding-decoding of replicated data;

заданием конфигурационного файла, содержащего в себе значения, необходимые для формирования запроса на внесение изменений и получения данных из удаленной базы данных;setting a configuration file containing the values necessary to generate a request for changes and receive data from a remote database;

создание на основе баз данных словаря замены кодируемых данных;creation on the basis of databases of the dictionary of replacement of the encoded data;

формированием отчетов о проделанной работе и достигнутых результатах.formation of reports on the work done and the results achieved.

в) причинно-следственная связь между признаками и техническим результатомc) causal relationship between features and technical result

Благодаря новой совокупности существенных признаков в заявленном способе расширяется функционал работы системы, обеспечивающей репликацию информации в распределенных базах данных и поддержание в идентичном состоянии баз данных, размещенных в независимых компьютерах посредством снижения объема передаваемых данных без утраты информативности с использованием технологии кодирования реплицируемых данных при выполнении синхронизации баз данных двух независимых компьютеров, в каждый из которых загружена одинаковая по структуре база данных с неизменной базой знаний и независимо изменяемой в этих компьютерах и дополняемой информацией в базе клиентов и исследований.Thanks to a new set of essential features, the claimed method expands the functionality of the system that provides information replication in distributed databases and maintenance of databases hosted on independent computers in an identical state by reducing the amount of transmitted data without loss of information content using replicated data coding technology when performing database synchronization data of two independent computers, each of which is loaded with a database of the same structure with an unchanged knowledge base and independently modified in these computers and supplemented by information in the database of clients and studies.

Проведенный анализ уровня техники позволил установить, что аналоги, характеризующиеся совокупностью признаков, тождественных всем признакам заявленного технического решения, отсутствуют, что указывает на соответствие заявленного способа условию патентоспособности «новизна».The analysis of the prior art made it possible to establish that there are no analogues characterized by a set of features identical to all the features of the claimed technical solution, which indicates the compliance of the claimed method with the condition of patentability "novelty".

Результаты поиска известных решений в данной и смежных областях техники с целью выявления признаков, совпадающих с отличительными от прототипа признаками заявленного объекта, показали, что они не следуют явным образом из уровня техники. Из уровня техники также не выявлена известность отличительных существенных признаков, обусловливающих тот же технический результат, который достигнут в заявляемом способе. Следовательно, заявленное изобретение соответствует условию патентоспособности «изобретательский уровень».The results of the search for known solutions in this and related fields of technology in order to identify features that match the distinguishing features of the prototype of the claimed object showed that they do not follow explicitly from the prior art. The prior art also did not reveal the fame of distinctive essential features that determine the same technical result that is achieved in the claimed method. Therefore, the claimed invention meets the condition of patentability "inventive step".

Краткое описание чертежейBrief description of the drawings

Заявленный способ поясняется чертежами, на которых показаны:The claimed method is illustrated by drawings, which show:

Фиг. 1 - структурная схема репликации данных;Fig. 1 - block diagram of data replication;

Фиг. 2 - таблица «Исследование»;Fig. 2 - table "Research";

Фиг. 3 - таблица «Пациенты»;Fig. 3 - table "Patients";

Фиг. 4 - таблица для выполнения синхронизации;Fig. 4 - table for synchronization;

Фиг. 5 - таблица с настройками автоматического запуска синхронизации;Fig. 5 - table with settings for automatic start of synchronization;

Фиг. 6 - Блок-схема процесса формирования таблицы кодировки;Fig. 6 - Flowchart of the process of generating the encoding table;

Фиг. 7 - Блок-схема процесса кодирования/декодирования реплицируемых данных.Fig. 7 - Flowchart of the process of encoding/decoding replicated data.

Осуществление изобретенияImplementation of the invention

Реализация заявленного способа объясняется следующим образом.The implementation of the claimed method is explained as follows.

В систему, выполненную в виде блока обеспечения локальной сети между первым и вторым компьютерами, содержащими синхронизируемые базы данных, блока синхронизации режимов работы компьютеров, при этом первый и второй входы-выходы блока обеспечения локальной сети между первым и вторым компьютерами соединены с первыми входами-выходами первого и второго компьютеров соответственно, а первый и второй входы-выходы блока синхронизации режимов работы компьютеров соединены со вторыми входами-выходами первого и второго компьютеров соответственно, блока сравнения данных в изменяемых базах данных первый вход-выход которого соединен с третьим входом-выходом блока синхронизации режимов работы компьютеров, блока выделения несовпадающих фрагментов в изменяемых базах данных, первый вход-выход которого соединен со вторым входом-выходом блока сравнения данных в изменяемых базах данных, а также блока внесения изменений в изменяемые базы данных, первый вход-выход которого соединен со вторым входом-выходом блока выделения несовпадающих фрагментов в изменяемых базах данных согласно изобретению, введены блоки кодирования-декодирования данных, первый и второй входы-выходы которых соединены с третьими и четвертыми входами-выходами первого и второго компьютера соответственно, а третьи и четвертые входы-выходы соединены со вторыми и третьими входами-выходами блоков сравнения данных в изменяемых базах данных и внесения изменений в изменяемые базы данных соответственно.Into a system made in the form of a block for providing a local network between the first and second computers containing synchronized databases, a block for synchronizing the operating modes of computers, while the first and second inputs and outputs of the block for providing a local network between the first and second computers are connected to the first inputs and outputs of the first and second computers, respectively, and the first and second inputs-outputs of the block for synchronizing the operating modes of computers are connected to the second inputs-outputs of the first and second computers, respectively, of the block for comparing data in variable databases, the first input-output of which is connected to the third input-output of the synchronization block operating modes of computers, a block for selecting mismatched fragments in changeable databases, the first input-output of which is connected to the second input-output of the block for comparing data in changeable databases, as well as a block for making changes to changeable databases, the first input-output of which is connected to the second block input-output for selecting mismatched fragments in variable databases according to the invention, data encoding-decoding blocks are introduced, the first and second inputs-outputs of which are connected to the third and fourth inputs-outputs of the first and second computers, respectively, and the third and fourth inputs-outputs are connected to the second and third inputs-outputs of blocks for comparing data in changeable databases and making changes to changeable databases, respectively.

На фигуре 1 представлена функциональная схема системы репликации информации в базах данных совместно с первым и со вторым компьютерами.The figure 1 shows a functional diagram of the information replication system in databases together with the first and second computers.

Система репликации информации в базах данных содержит блок 1 обеспечения локальной сети между первым 2 и вторым 3 компьютерами, содержащими синхронизируемые базы данных, первый и второй входы-выходы которого соединены с первыми входами-выходами первого 2 и второго 3 компьютеров, соответственно. Кроме того, система репликации информации в базах данных содержит блок 4 синхронизации режимов работы компьютеров, первый и второй входы-выходы которого соединены со вторыми входами-выходами первого 2 и второго 3 компьютеров, соответственно, блок 5 сравнения данных в изменяемых базах данных, первый вход-выход которого соединен с третьим входом-выходом блока 4 синхронизации режимов работы компьютеров, блок 6 выделения несовпадающих фрагментов в изменяемых базах данных, первый вход-выход которого соединен с четвертым входом-выходом блока 5 сравнения данных в изменяемых базах данных, блок 7 внесения изменений в изменяемые базы данных, первый вход-выход которого соединен со вторым входом-выходом блока 6 выделения несовпадающих фрагментов в изменяемых базах, а также блоки 8 и 9 кодирования-декодирования данных, первый и второй входы-выходы которых соединены с третьими и четвертыми входами-выходами первого 2 и второго 3 компьютера соответственно, а третьи и четвертые входы-выходы блоков 8 и 9 кодирования-декодирования данных соединены со вторыми и третьими входами-выходами блоков 5 сравнения данных в изменяемых базах данных и 7 внесения изменений в изменяемые базы данных соответственно.The information replication system in databases contains a block 1 for providing a local network between the first 2 and second 3 computers containing synchronized databases, the first and second inputs and outputs of which are connected to the first inputs and outputs of the first 2 and second 3 computers, respectively. In addition, the information replication system in databases contains a block 4 for synchronizing the operating modes of computers, the first and second inputs-outputs of which are connected to the second inputs-outputs of the first 2 and second 3 computers, respectively, a block 5 for comparing data in variable databases, the first input - the output of which is connected to the third input-output of block 4 for synchronizing computer operating modes, block 6 for selecting mismatched fragments in variable databases, the first input-output of which is connected to the fourth input-output of block 5 for comparing data in variable databases, block 7 for making changes into variable databases, the first input-output of which is connected to the second input-output of block 6 for selecting mismatched fragments in variable databases, as well as blocks 8 and 9 for encoding and decoding data, the first and second inputs-outputs of which are connected to the third and fourth inputs - outputs of the first 2 and second 3 computers, respectively, and the third and fourth inputs-outputs of blocks 8 and 9 data encoding/decoding are connected to the second and third inputs/outputs of blocks 5 for comparing data in variable databases and 7 for making changes to variable databases, respectively.

Система содержит элементы и блоки, охарактеризованные на функциональном уровне, и описываемая форма реализации предполагает использование программируемого (настраиваемого) многофункционального средства, поэтому при описании его работы представляются сведения, подтверждающие возможность выполнения таким средством конкретной предписываемой ему в составе данной системы функции.The system contains elements and blocks characterized at the functional level, and the described form of implementation involves the use of a programmable (configurable) multifunctional tool, therefore, when describing its operation, information is provided confirming the possibility of such a tool to perform a specific function assigned to it as part of this system.

Типичной практической задачей, которая возникает для компьютерных систем, содержащих, например, основную (главную) стационарную часть (например, настольный компьютер) и мобильную (периферийную) часть (например, ноутбук), информация в которых может изменяться без привязки к интернету, и работа на ноутбуке производится в выездном режиме. В этом случае возникает необходимость регулярно производить полную репликацию/синхронизацию баз данных, загруженных в компьютерах.A typical practical problem that arises for computer systems containing, for example, the main (main) stationary part (for example, a desktop computer) and a mobile (peripheral) part (for example, a laptop), the information in which can change without being connected to the Internet, and work on a laptop is done in offsite mode. In this case, it becomes necessary to regularly perform full replication / synchronization of databases loaded on computers.

Рассмотрим работу способа репликации информации в базах данных с использованием кодирования запросов технологией простой синтаксической замены с использованием таблицы кодировки на примере медицинской базы данных. В научно-медицинском центре в качестве средства хранения данных используется два независимых компьютера, один из которых применяется, например, как мобильный вариант, в котором используется модификация локальной установки СУБД ORACLE. Задача состоит в объединении данных с двух компьютеров и разработке механизма, позволяющего проводить регулярную синхронизацию данных между двумя ORACLE-серверами. База данных состоит из двух частей - практически неизменяемой базы знаний и регулярно изменяемой базой данных о клиентах и исследованиях, выполненной с возможностью независимых изменений и дополнений на каждом из двух компьютеров. Задача предполагает синхронизацию только изменяемой части базы данных, так как изменения в базу знаний вносятся централизовано, и база знаний считается одинаковой в разных репликах СУБД. Центральной таблицей базы данных является таблица «Исследование» (ANALYSIS), представленная на фигуре 2, все остальные таблицы связаны с ней по идентификационному номеру исследования (ID исследования) отношением один-ко-многим. Исключение составляет таблица «Пациенты» (CLIENTS), изображенная на фигуре 3, которая связана с таблицей «Исследование» по идентификационному номеру пациента связью один-к-одному.Consider the operation of the method of replicating information in databases using query coding using simple syntactic replacement technology using an encoding table using the example of a medical database. In the scientific and medical center, two independent computers are used as a means of storing data, one of which is used, for example, as a mobile version that uses a modification of the local installation of the ORACLE DBMS. The task is to combine data from two computers and develop a mechanism that allows regular data synchronization between two ORACLE servers. The database consists of two parts - a virtually unchangeable knowledge base and a regularly updated database of clients and studies, made with the possibility of independent changes and additions on each of the two computers. The task assumes synchronization of only the changeable part of the database, since changes to the knowledge base are made centrally, and the knowledge base is considered the same in different DBMS replicas. The Central table of the database is the table "Investigation" (ANALYSIS), presented in figure 2, all other tables are associated with it by the identification number of the study (Study ID) in a one-to-many relationship. The exception is the CLIENTS table shown in Figure 3, which is linked to the Study table by patient ID in a one-to-one relationship.

В базе данных не обеспечивается как уникальность пациента и для каждого нового исследования делается новая запись в таблице «Пациенты», так и уникальность данных об исследовании. Такая особенность базы данных затрудняет сравнение двух ее модификаций на двух независимых компьютерах. В качестве уникальных данных об исследовании в рамках локальной СУБД предлагается использовать совокупность полей ID пациента + ID типа биосубстрата + ID минералограммы + ID профиля исследования + Дата забора биосубстрата + Признак наличия диабета + Признак наличия ожирения + Признак наличия ССЗ + Признак ограничения по алкоголю. Для таблицы «Пациенты» поле ID пациента является автоматически наращиваемым счетчиком и не может быть использовано в уникальной комбинации полей для сравнения данных между двумя серверами. Вместо него необходимо использовать уникальную совокупность полей таблицы «Пациенты» для однозначной идентификации данных о пациентах Номер карты + Фамилия + Имя + День рождения + Пол. Таким образом, совокупность полей ID пациента + ID типа биосубстрата + ID минералограммы + ID профиля исследования + Дата забора биосубстрата + Признак наличия диабета + Признак наличия ожирения + Признак наличия ССЗ + Признак ограничения по алкоголю + Номер карты + Фамилия + Имя + День рождения + Пол однозначно определяют каждое исследование и могут быть взяты в качестве идентификационной комбинации полей. Поле «Системный статус исследования» содержит значения, характеризующие завершенность обработки результатов исследования и может быть использовано в качестве критерия для обновления записей, совпадающих по идентификационной совокупности полей. Множество исследований в каждой из сравниваемых баз данных задается комбинацией полей, однозначно определяющих каждое исследование. Задача сводится к объединению этих множеств, при этом в области пересечения множеств необходимо оставить исследования, обработка которых максимально завершена (степень «завершенности» исследования определяется значением в поле Системный статус исследования). Предполагается что исследования, совпадающие по комбинации полей для идентификации и с одинаковым значением в поле Системный статус исследования, идентичны и их сравнение не производится. Обозначим множество исследовании в сравниваемых базах данных А и В. Для объединения множеств необходимо выполнить следующие действия:The database does not provide both the uniqueness of the patient and for each new study a new entry is made in the "Patients" table, and the uniqueness of the data about the study. This feature of the database makes it difficult to compare two of its modifications on two independent computers. As unique data about the study within the local DBMS, it is proposed to use a set of fields Patient ID + Biosubstrate type ID + Mineralogram ID + Study profile ID + Date of biosubstrate sampling + Sign of diabetes + Sign of obesity + Sign of CVD + Sign of alcohol restriction. For the Patients table, the Patient ID field is an auto-incrementing counter and cannot be used in a unique combination of fields to compare data between two servers. Instead, it is necessary to use a unique set of fields in the "Patients" table to uniquely identify patient data Card number + Surname + First name + Birthday + Gender. Thus, the totality of fields Patient ID + ID of biosubstrate type + ID of mineralogram + ID of study profile + Date of biosubstrate sampling + Sign of diabetes + Sign of obesity + Sign of CVD + Sign of alcohol restriction + Card number + Surname + First name + Birthday + Gender is uniquely identified by each study and can be taken as an identifying combination of fields. The "Research System Status" field contains values that characterize the completeness of processing the results of the study and can be used as a criterion for updating records that match the identification set of fields. The set of studies in each of the compared databases is given by a combination of fields that uniquely identify each study. The task is reduced to the union of these sets, while in the area of intersection of the sets it is necessary to leave the studies, the processing of which is maximally completed (the degree of “completion” of the study is determined by the value in the System status of the study field). Exams that match the combination of identification fields and the same value in the Systemic Exam Status field are assumed to be identical and are not compared. Let's denote the study set in the compared databases A and B. To merge the sets, you must perform the following steps:

- найти разность множеств А\В;- find the difference of sets A\B;

- добавить полученную разность к множеству В;- add the resulting difference to the set B;

- в области пересечения множеств найти записи, имеющие разное значение поля Системный статус исследования;- in the area of intersection of sets, find records that have different values of the field System status of the study;

- обновить в множестве В те записи, для которых в области пересечения имеются записи с «большим завершением» по значению в поле Системный статус исследования и совпадающие по остальным полям идентификации исследования;- update in the set B those records for which there are records in the intersection area with “great completion” in terms of the value in the System status of the study field and matching in the rest of the study identification fields;

- повторить описанные действия, поменяв местами базы данных А и В.- repeat the described actions, swapping databases A and B.

Поскольку таблица «Исследование» (ANALYSIS) связана с большим количеством других таблиц, детализирующих проведенные анализы, по идентификационному номеру исследования (ID исследования), и этот номер является внутренним для каждой Базы данных, то есть одинаковым значением поля ID исследования могут быть обозначены разные исследования на разных базах данных, при переносе информации с одной базы данных на другую необходимо обеспечить вычисление соответствующего значения ID исследования, и использовать его в связанных таблицах. Объект базы данных DATABASE LINK с именем MASTER - это подключение локального сервера к удаленной базе данных. Настройка триггеров таблицы «Пациенты» и «Исследования». Для этого требуется изменить автоматическое увеличение первичного ключа таблицы таким образом, чтобы вычисление нового ключа происходило, только в случае когда ключ не заполнен. Вычисление новых значений первичного ключа при выполнении задачи объединения данных будет происходить не посредством триггера, а внутри программы объединения, так чтобы значение первичного ключа можно было использовать при добавлении данных из связанных таблиц. Запросы на сравнение таблиц NEWDATA и UPDDATA.NEWDATA -запрос, вычисляющий разность множеств исследований на локальном сервере и сервере, присоединенном через DBLink MASTER. Результат представлен в виде пар (ID_ANALYSIS, IDCLIENTS), определяющих исследования, которых нет в таблице ANALYSIS@MASTER. UPDDATA - запрос, находящий те исследования на локальном сервере, у которых значение поля Системный статус исследования (STATUS) больше, чем значение поля Системный статус исследования (STATUS) на сервере, присоединенном через DBLink MASTER. Результат представлен в виде пар (ID_ANALYSIS, IDCLIENTS). Таблица SYNCHRONIZE, изображенная на фигуре 4, необходима для подготовки данных для синхронизации. Агрегирует в себе данные из запросов NEWDATA и UPDDATA. В нее помещаются новые идентификаторы записей, которые будут вставлены в соответствующие таблицы сервера MASTER. А также помечаются записи для вставки при ручном отборе записей. Таблица SYNCHRONIZEPARAMETERS, изображенная на фигуре 5, является таблицей с настройками автоматического запуска синхронизации.Since the “Study” (ANALYSIS) table is linked to a large number of other tables detailing the analyzes performed, by the study identification number (study ID), and this number is internal to each Database, that is, different studies can be designated by the same value of the study ID field on different databases, when transferring information from one database to another, it is necessary to ensure that the corresponding study ID value is calculated and used in related tables. The DATABASE LINK database object named MASTER is a local server connection to a remote database. Setting up triggers for the "Patient" and "Research" tables. To do this, you need to change the automatic increase of the primary key of the table in such a way that the calculation of the new key occurs only in the case when the key is not filled. The calculation of new primary key values during the data federation task will not occur through a trigger, but within the join program, so that the primary key value can be used when adding data from related tables. Queries to compare tables NEWDATA and UPDDATA.NEWDATA - a query that calculates the difference between the study sets on the local server and the server connected via DBLink MASTER. The result is presented as pairs (ID_ANALYSIS, IDCLIENTS) that define studies that are not in the ANALYSIS@MASTER table. UPDDATA is a query that finds those studies on the local server that have the value of the Study System Status (STATUS) field greater than the value of the Study System Status (STATUS) field on the server connected via DBLink MASTER. The result is presented as pairs (ID_ANALYSIS, IDCLIENTS). The SYNCHRONIZE table shown in Figure 4 is needed to prepare the data for synchronization. Aggregates data from NEWDATA and UPDDATA requests. It contains new record identifiers that will be inserted into the corresponding tables of the MASTER server. And also records are marked for insertion when manually selecting records. The SYNCHRONIZEPARAMETERS table shown in Figure 5 is a table with automatic synchronization start settings.

Все запросы на извлечение данных и внесение изменений в удаленную базу данных кодируются простой синтаксической заменой, механизм кодирования реализуется следующим образом: запрос или ответ на запрос разбивается на части, пригодные для кодирования и на основе этих частей производится поиск в таблице в таблице синтаксической замены (кодировки). Найденные кодированные аналоги составляют готовый к передаче по каналу связи запрос или ответ на запрос.All requests to retrieve data and make changes to the remote database are encoded by a simple syntactic replacement, the encoding mechanism is implemented as follows: the request or response to the request is divided into parts suitable for encoding and based on these parts, a table is searched in the table of syntactic replacement (encodings ). The found coded analogues constitute a request or a response to a request ready for transmission over a communication channel.

Таблица синтаксической замены создается на основе локальной базы. Данная таблица предназначена для хранения уникальных данных по каждому полю всех таблиц базы данных в совокупности с кодированным значением, которое будет поставлено в соответствие этим данным. Формирование подобной таблицы представлено в виде блок-схемы 200, изображенной на фигуре 6. Блок 202 формирования конфигурационных данных на основе считанных блоком 201 данных создает словарь конфигурационных данных, содержащий список имен таблиц базы данных, на основе которой производится формирование таблицы синтаксической замены, а также количество таблиц в данной базе данных. Эти конфигурационные данные нужны для реализации запросов на выгрузку информации из базы данных. Блок 203 формирует запрос на подключение к базе данных и на основе блока 204 проверки успешности подключения к базе данных, в случае, если подключение по какой-либо причине не выполнено, блоками 205 и 206 производится вывод сообщения об ошибке подключения к базе данных и выполняется запрос реакции пользователя: выполнить повторное подключение к базе данных, либо завершить работу. Обработка данного ответа пользователя выполняется блоком 207.The syntax substitution table is created from the local base. This table is designed to store unique data for each field of all database tables in conjunction with a coded value that will be associated with this data. The formation of such a table is presented in the form of a flowchart 200 shown in figure 6. The block 202 for generating configuration data, based on the data read by block 201, creates a dictionary of configuration data containing a list of names of database tables, on the basis of which the syntactic replacement table is formed, as well as the number of tables in the given database. These configuration data are needed to implement requests to unload information from the database. Block 203 generates a request to connect to the database and, based on block 204 of checking the success of the connection to the database, if the connection is not successful for any reason, blocks 205 and 206 produce an error message about the connection to the database and execute the request user response: reconnect to the database, or exit. Processing of this user response is performed by block 207.

Далее блоками 208 и 209 формируются маркер итерации i номера обрабатываемой таблицы равный 1 и словарь data для хранения записей таблицы базы данных. Формируется запрос 210 к базе данных на извлечение всех данных i-й таблицы базы данных и ответ на данный запрос записывается 211 в data и на основе блока проверки корректности ответа на запрос 212 в случае, если ответ на запрос представляет собой некорректные данные, блоками 213 и 206 производится вывод сообщения о некорректности данных и выполняется запрос реакции пользователя: выполнить повторное подключение к базе данных, либо завершить работу. Обработки данного ответа пользователя выполняется блоком 207.Further, blocks 208 and 209 form the iteration marker i of the number of the processed table equal to 1 and the data dictionary for storing records of the database table. A query 210 is formed to the database to retrieve all the data of the i-th table of the database and the response to this query is written 211 in data and based on the block for checking the correctness of the response to the query 212 in case the response to the query is incorrect data, blocks 213 and 206, a message about incorrect data is displayed and a request is made for the user's reaction: reconnect to the database, or exit. Processing of this user response is performed by block 207.

Далее формируются следующие технические значения:The following technical values are then formed:

data_quantity - для хранения количества записей таблицы 214;data_quantity - to store the number of records in table 214;

field_quantity - для хранения количества полей таблицы 215;field_quantity - to store the number of fields in the table 215;

j, k - маркеры номера обрабатываемого элемента списка data 218;j, k - markers of the number of the processed element of the list data 218;

t - маркер синтаксической замены кодируемых данных 219;t is a syntax substitution marker for encoded data 219;

field_unique - словарь уникальных данных формата «ключ» : «значение» 220.field_unique - a dictionary of unique data of the format "key" : "value" 220.

Значения k, j, t устанавливаются равными 0 блоками 221, 222, 223 соответственно.The values k, j, t are set to 0 by blocks 221, 222, 223, respectively.

Нахождение уникальных значений по полям таблицы происходит следующим образом: блок проверки уникальности значений 224 в случае, если в словаре уникальных данных field_unique значение datajk отсутствует, следовательно, это значение по k-му полю ранее не встречалось и является уникальным, в field_unique добавляется 225 запись с ключом datajk и значением - t, значение маркера t увеличивается 226 на 1, и обработчик таблицы переходит 227 к следующей записи, увеличивая маркер j на 1. В случае, если значение datajk в словаре отсутствует, и, следовательно, данное значение по k-му полю уникальным не является, обработка сразу переходит 227 к следующей записи. После достижения 228 последней записи k-го поля таблицы, то есть установления равенства j и data_quantity, словарь уникальных значений по данному полю записывается 229 в таблицу кодировки, а затем очищается 230. Далее обработчик таблицы переходит 231 к следующему полю таблицы, увеличивая маркер k на 1. После достижения 232 последней записи последнего поля, то есть установления равенства k и fields_quantity, обработка переходит 233 к следующей таблице базы данных, значение маркера i увеличивается на 1. После окончания обработки последней таблицы, формируется 235 отчет о результатах работы.Finding unique values by the fields of the table is as follows: the block for checking the uniqueness of values 224 in case the value data jk is absent in the field_unique dictionary of unique data, therefore, this value has not previously been encountered in the k-th field and is unique, an entry 225 is added to field_unique with key data jk and value - t, the value of marker t is incremented 226 by 1, and the table engine moves 227 to the next record, incrementing marker j by 1. k-th field is not unique, processing immediately proceeds 227 to the next record. After reaching 228 the last record of the k-th field of the table, i.e. establishing the equality of j and data_quantity, the dictionary of unique values for this field is written 229 to the encoding table, and then cleared 230. Next, the table handler proceeds 231 to the next field of the table, increasing the marker k by 1. After reaching 232 the last record of the last field, that is, establishing the equality of k and fields_quantity, processing proceeds 233 to the next database table, the value of marker i increases by 1. After processing the last table, a report on the results of work is generated 235 .

Кодирование и раскодирование запросов и ответов на запросы представлено на блок схеме 300, изображенной на фигуре 7. Блок 301 устанавливает соединение с удаленной базой данных для приема и передачи данных и на основе блока 302 проверки успешности установления соединения с базой данных, в случае, если подключение по какой-либо причине не выполнено, блоками 303 и 304 производится вывод сообщения об ошибке подключения к базе данных и выполняется запрос реакции пользователя: выполнить повторное соединения с базой данных, либо завершить работу. Обработка данного ответа пользователя выполняется блоком 305. Далее для чтения и записи открывается 306 вышеописанная предварительно сгенерированная таблица кодировки. Считывается 307 файл конфигурации и на его основе формируется 308 словарь конфигурационных данных, содержащий запрос или ответ на запрос, разбитые на блоки, пригодные для кодирования.Encoding and decoding of requests and responses to requests is presented in block diagram 300 shown in figure 7. Block 301 establishes a connection with a remote database for receiving and transmitting data and based on block 302 checks the success of establishing a connection with the database, in case the connection fails for some reason, blocks 303 and 304 produce a database connection error message and request a user response to either reconnect to the database or exit. Processing of this user response is performed at block 305. Next, the pre-generated encoding table described above is opened 306 for reading and writing. The configuration file is read 307 and based on it a configuration data dictionary is formed 308 containing the request or response to the request, divided into blocks suitable for encoding.

Далее формируются следующие технические значения:The following technical values are then formed:

encoded_data_src - для хранения кодированных данных 309;encoded_data_src - for storing encoded data 309;

i - маркер итерации обхода словаря конфигурационных данных 310;i is the iteration marker of the traversal of the configuration data dictionary 310;

f - флаг внесения изменений в таблицу кодировки;f - flag for making changes to the encoding table;

len_src - для хранения значения длины словаря конфигурационных данных 311.len_src - to store the length value of the configuration data dictionary 311.

Выполняется проверка необходимости внесения изменений 312 в таблицу кодировки: в случае если в таблице кодировки i-e значения словаря конфигурационных данных отсутствует, данное значение записывается 313 в таблицу и флаг внесения изменений f устанавливается 314 равным 1. В encoded_data_src записывается 315 кодированное значение из таблицы кодировки, соответствующее i-му значению словаря конфигурационных данных и обработка переходит 316 к следующему элементу словаря, значение i увеличивается на 1. После обработки 317 последнего элемента словаря в том случае, если в таблицу синтаксической замены вносились 318 новые данные, иными словами значение флага f равняется 1, происходит 319 синхронизация словарей кодировки локального и удаленного компьютеров.A check is made for the need to make changes 312 to the encoding table: if there is no configuration data dictionary value in the encoding table i-e, this value is written 313 to the table and the change flag f is set 314 to 1. The encoded_data_src is written 315 the encoded value from the encoding table corresponding to i-th value of the configuration data dictionary and processing proceeds 316 to the next element of the dictionary, the value of i increases by 1. After processing 317 of the last element of the dictionary, if new data was entered into the syntax replacement table 318, in other words, the value of the flag f is 1, the encoding dictionaries of the local and remote computers are 319 synchronized.

Далее происходит передача 320 закодированного запроса или ответа на запрос по каналу связи, данные принимаются 321 удаленным компьютером, разбиваются на блоки, пригодные для раскодирования и на их основе формируется 322 словарь конфигурационных данных, затем для чтения открывается 323 файл таблицы кодировки и формируются следующие технические значения:Next, the encoded request or response to the request is transmitted 320 over a communication channel, the data is received 321 by a remote computer, divided into blocks suitable for decoding and based on them a configuration data dictionary is formed 322, then the encoding table file 323 is opened for reading and the following technical values are formed :

decoded_data_dst - для хранения декодированных данных 324;decoded_data_dst - for storing decoded data 324;

j - маркер итерации обхода словаря конфигурационных данных 325;j is the iteration marker of the traversal of the configuration data dictionary 325;

len_dst - для хранения значения длины словаря конфигурационных данных 326.len_dst - to store the length value of the configuration data dictionary 326.

В decoded_data_dst записывается 327 раскодированное значение из таблицы кодировки, соответствующее j-му значению словаря конфигурационных данных и обработка переходит 328 к следующему элементу словаря, значение j увеличивается на 1. После обработки 329 последнего элемента словаря decoded_data_dst передается 330 обработчику данных, формируется отчет о результате работы.The decoded_data_dst value is written 327 to decoded_data_dst from the encoding table corresponding to the j-th value of the configuration data dictionary, and processing proceeds 328 to the next element of the dictionary, the value of j increases by 1. After processing 329 the last element of the decoded_data_dst dictionary, it is transferred 330 to the data handler, and a report is generated on the result of the work .

При реализации рассмотренного способа репликации данных предложенная система используется следующим образом. Блок 1, первый и второй входы-выходы которого соединены с первыми входами-выходами первого 2 и второго 3 компьютеров, соответственно, обеспечивает локальную сеть между первым 2 и вторым 3 компьютером, содержащими синхронизируемые базы данных. Блок 4 синхронизации режимов работы компьютеров, первый и второй входы-выходы которого соединены со вторыми входами-выходами первого 2 и второго 3 компьютеров, соответственно, обеспечивает перевод первого 2 и второго 3 компьютеров поочередно в режим компьютера-приемника и компьютера-источника. Блок 5 сравнения данных в изменяемых базах данных, первый вход-выход которого соединен с третьим входом-выходом блока 4 синхронизации режимов работы компьютеров, производит сравнения в изменяемых базах данных первого 2 и второго 3 компьютеров, а блок 6 выделения несовпадающих фрагментов в изменяемых базах данных, первый вход-выход которого соединен с четвертым входом-выходом блока 5 сравнения данных в изменяемых базах данных, выделяет фрагменты для замены (обновления) изменяемых баз данных, которые с помощью блока 7 внесения изменений в изменяемые базы данных вносятся в виде изменений в изменяемые базы данных. Блоки 8 и 9 кодирования-декодирования данных, первый и второй входы-выходы которых соединены с третьими и четвертыми входами-выходами первого 2 и второго 3 компьютера соответственно, а третьи и четвертые входы-выходы блоков 8 и 9 кодирования-декодирования данных соединены со вторыми и третьими входами-выходами блоков 5 сравнения данных в изменяемых базах данных и 7 внесения изменений в изменяемые базы данных соответственно осуществляют прямое преобразование данных к сжатому (закодированному) виду при их передаче и обратное преобразование данных к развернутому (раскодированному) виду при их приеме во время осуществления информационного обмена по каналам связи от первого компьютера ко второму и от второго компьютера к первому.When implementing the considered method of data replication, the proposed system is used as follows. Block 1, the first and second inputs-outputs of which are connected to the first inputs-outputs of the first 2 and second 3 computers, respectively, provides a local network between the first 2 and second 3 computers containing synchronized databases. Unit 4 for synchronization of computer operating modes, the first and second inputs-outputs of which are connected to the second inputs-outputs of the first 2 and second 3 computers, respectively, ensures the transfer of the first 2 and second 3 computers alternately into the mode of the computer-receiver and computer-source. Block 5 for comparing data in variable databases, the first input-output of which is connected to the third input-output of block 4 for synchronizing computer operating modes, makes comparisons in variable databases of the first 2 and second 3 computers, and block 6 for selecting mismatched fragments in variable databases , the first input-output of which is connected to the fourth input-output of block 5 for comparing data in changeable databases, allocates fragments for replacing (updating) changeable databases, which, using block 7 for making changes to changeable databases, are made in the form of changes to changeable databases data. Blocks 8 and 9 encoding-decoding data, the first and second inputs-outputs of which are connected to the third and fourth inputs-outputs of the first 2 and second 3 computer, respectively, and the third and fourth inputs-outputs of blocks 8 and 9 encoding-decoding data are connected to the second and third inputs-outputs of blocks 5 for comparing data in variable databases and 7 for making changes to variable databases, respectively, directly convert data to a compressed (encoded) form when they are transmitted and inversely convert data to an expanded (decoded) form when they are received during implementation of information exchange via communication channels from the first computer to the second and from the second computer to the first.

После проведения процедуры репликации для обоих компьютеров изменяемые части их базах данных становятся полностью одинаковыми.After the replication procedure for both computers, the changeable parts of their databases become exactly the same.

Claims (1)

Способ репликации информации в базах данных с использованием механизма кодирования запросов простой синтаксической заменой на основе таблицы кодировки, осуществляемый системой, выполненной в виде блока обеспечения локальной сети между первым и вторым компьютерами, содержащими синхронизируемые базы данных, блока синхронизации режимов работы компьютеров, при этом первый и второй входы-выходы блока обеспечения локальной сети между первым и вторым компьютерами соединены с первыми входами-выходами первого и второго компьютеров соответственно, а первый и второй входы-выходы блока синхронизации режимов работы компьютеров соединены со вторыми входами-выходами первого и второго компьютеров соответственно, блока сравнения данных в изменяемых базах данных, первый вход-выход которого соединен с третьим входом-выходом блока синхронизации режимов работы компьютеров, блока выделения несовпадающих фрагментов в изменяемых базах данных, первый вход-выход которого соединен с входом-выходом блока сравнения данных в изменяемых базах данных, а также блока внесения изменений в изменяемые базы данных, первый вход-выход которого соединен со вторым входом-выходом блока выделения несовпадающих фрагментов в изменяемых базах данных, отличающийся тем, что введены два блока кодирования-декодирования данных в систему, первый и второй входы-выходы которых соединены с третьими и четвертыми входами-выходами первого и второго компьютера соответственно, а третьи и четвертые входы-выходы соединены со вторыми и третьими входами-выходами блоков сравнения данных в изменяемых базах данных и внесения изменений в изменяемые базы данных соответственно, а первый вход-выход блока выделения несовпадающих фрагментов изменяемых базах данных соединен с четвертым входом-выходом блока сравнения данных в изменяемых базах данных, причем блоки кодирования-декодирования данных реализованы следующим образом: предварительно на основе базы данных создается файл, содержащий таблицу кодировки: принимают информацию, включающую в себя словарь table_names <х1, …, х2, …, xn>, содержащий названия таблиц базы данных, где n - количество таблиц, формируют запрос на подключение к базе данных, в случае если подключение не выполнено, выводится сообщение об ошибке подключения и подтверждают отправку повторного запроса на подключение к базе данных, в случае если отправка подтверждена, выполняют повторное обращение к базе данных, если отправке не подтверждена, происходит завершение работы, если подключение выполнено успешно, формируют маркер номера обрабатываемой таблицы i, изначально равный 1, формирует список data для хранения записей таблицы, формируют запрос на извлечение всех данных из таблицы table_namesi, ответ на запрос записывают в словарь data, и в случае если ответ на запрос представляет собой некорректные данные, выводится сообщение о соответствующей ошибке и подтверждают отправку повторного запроса на подключение к базе данных, а в случае если отправка подтверждена, выполняют повторное обращение к базе данных, если отправка не подтверждена, формируется отчет о проделанной работе и происходит завершение работы, если данные корректны, формируется флаг достижения последней записи data_quantity, записывают в него значение длины словаря data, формируют флаг достижения последнего поля таблицы field_quantity, записывают в него значение длины словаря data0, формируют маркеры j, k, номера обрабатываемого элемента словаря data, формируют маркер t, представляющий собой значение, которое будет поставлено способом синтаксической замены в соответствие данным базы данных, формируют словарь уникальных данных field_unique формата «ключ»: «значение», устанавливают значение маркера k, равное 0, устанавливают значение маркера j, равное 0, устанавливают значение маркера t, равное 0, производится проверка: если в словаре field_unique отсутствует запись с ключом datajk, в словарь field_unique добавляют запись с ключом datajk и значением t, значение t увеличивают на 1, значение j увеличивают на 1, если в словаре field_unique запись с ключом datajk имеется, происходит переход к шагу инкрементирования j, происходит проверка: если последняя запись таблицы не обработана, а именно значение маркера j не равно значению флага data_quantity, происходит возвращение к шагу проверки вхождения datajk в словарь field_unique, если последняя запись таблицы обработана, словарь field_unique записывают в файл таблицы кодировки, очищают словарь field_unique и увеличивают значение маркера k на 1, происходит проверка: если последнее поле таблицы не обработано, а именно значение маркера k не равно значению флага fields_quantity, происходит возвращение к шагу установления значения маркера j, если последнее поле обработано, значение маркера номера обрабатываемой таблицы i увеличивается на 1, происходит проверка: если база данных не обработана полностью, а именно значение флага i больше значения количества таблиц n, происходит переход к шагу создания словаря data, если конец таблицы достигнут, формируется отчет о проделанной работе и происходит завершение работы, процесс передачи запроса к базе данных производится следующим образом: устанавливают соединение с базой данных для приема/передачи данных, если соединение не установлено, выводится сообщение об ошибке соединения и подтверждают установку повторного соединения, в случае если установка повторного соединения подтверждена, выполняют повторное соединение с базой данных, если установка повторного соединения не подтверждена, формируется отчет о проделанной работе и происходит завершение работы, если подключение выполнено успешно, открывают для чтения и записи файл таблицы кодировки, принимают информацию, содержащую пользовательский запрос к базе данных, записывают принятые данные в словарь open_data_list_src, формируют строку кодированных данных encoded_data_src, формируют маркер обхода словаря i и флаг внесения изменений в таблицу кодировки f с начальными значениями, равными 0, формируют флаг достижения конца словаря len_src, записывают в него значение длины словаря open_data_list_src, происходит проверка: если в таблице кодировки имеется значение open_data_list_srci, в encoded_data_src записывают кодированное значение, соответствующее open_data_list_srcj, если в таблице кодировки значение open_data_list_srci отсутствует, в таблицу кодировки заносится значение open_data_list_srci, значение флага f устанавливают равным 1 и переходят к шагу записи кодированного значения в encoded_data_src, значение маркера i увеличивается на 1, происходит проверка: если конец словаря open_data_list_src не достигнут, а именно значение маркера i не равно значению флага len_src, переходят к шагу проверки наличия open_data_list_srci в таблице кодировки, если конец словаря open_data_list_src достигнут, производят проверку: если флаг внесения изменений в таблицу f равен 0, значение encoded_data_src передается по каналу связи, если флаг f не равен 0, производят синхронизацию таблиц кодировки и переходят к передаче значения encoded_data_src, осуществляют прием переданных данных, записывают принятые данные в словарь encoded_data_list_dst, открывают для чтения таблицу кодировки, формируют строку декодированных данных decoded_data_dst, формируют маркер обхода словаря j с начальным значением 0, формируют флаг достижения конца словаря len_dst, записывают в него значение длины словаря encoded_data_list_dst, записывают в decoded_data_dst декодированное значение, соответствующее encoded_data_list_srcj, увеличивают значение маркера j на 1, производят проверку: если конец словаря encoded_data_list_src не достигнут, а именно значение маркера j не равно значение флага len_dst, переходят к шагу занесения в decoded_data_dst декодированных данных, если конец словаря encoded_data_list_src достигнут, значение decoded_data_dst передается обработчику событий, формируется отчет о проделанной работе и происходит завершение работы.A method for replicating information in databases using a mechanism for encoding requests by simple syntactic replacement based on an encoding table, carried out by a system made in the form of a block for providing a local network between the first and second computers containing synchronized databases, a block for synchronizing the operating modes of computers, while the first and the second inputs-outputs of the block for providing a local network between the first and second computers are connected to the first inputs-outputs of the first and second computers, respectively, and the first and second inputs-outputs of the block for synchronizing the operating modes of computers are connected to the second inputs-outputs of the first and second computers, respectively, of the block comparing data in variable databases, the first input-output of which is connected to the third input-output of the block for synchronizing the operating modes of computers, the block for selecting mismatched fragments in variable databases, the first input-output of which is connected to the input-output of the comparison unit I of data in changeable databases, as well as a block for making changes to changeable databases, the first input-output of which is connected to the second input-output of the block for selecting mismatched fragments in changeable databases, characterized in that two data encoding-decoding blocks are introduced into the system , the first and second inputs-outputs of which are connected to the third and fourth inputs-outputs of the first and second computers, respectively, and the third and fourth inputs-outputs are connected to the second and third inputs-outputs of blocks for comparing data in changeable databases and making changes to changeable databases data, respectively, and the first input-output block for selecting mismatched fragments in changeable databases is connected to the fourth input-output block for comparing data in changeable databases, and the data encoding-decoding blocks are implemented as follows: a file containing an encoding table is first created on the basis of the database : receive information including table_names <х 1 , …, х 2 , …, x n > dictionary, containing the names of database tables, where n is the number of tables, form a request to connect to the database, if the connection is not successful, an error message is displayed connections and confirm the sending of a repeated request to connect to the database, if the sending is confirmed, re-access the database, if the sending is not confirmed, the work is completed, if the connection is successful, form a marker of the number of the processed table i, initially equal to 1, generates a data list for storing table records, generates a request to retrieve all data from the table_names i table, writes the response to the request to the data dictionary, and if the response to the request is incorrect data, a message is displayed about the corresponding error and confirms sending a second request to connection to the database, and if the sending is confirmed, they re-access the database For data, if the sending is not confirmed, a progress report is generated and the work is completed, if the data is correct, the flag for reaching the last data_quantity record is generated, the value of the length of the data dictionary is written to it, the flag of reaching the last field of the field_quantity table is generated, the length value is written to it of the dictionary data 0 , form markers j, k, numbers of the processed element of the data dictionary, form a marker t, which is a value that will be set by the syntactic replacement method in accordance with the database data, form a dictionary of unique field_unique data of the "key": "value" format, set the value of marker k to 0, set the value of marker j to 0, set the value of marker t to 0, a check is made: if there is no entry in the field_unique dictionary with the key data jk , an entry with the key data jk and value t is added to the field_unique dictionary , the value of t is increased by 1, the value of j is increased by 1, e If there is an entry with the key data jk in the field_unique dictionary, the transition to the increment step j takes place, a check occurs: if the last table entry is not processed, namely the value of the marker j is not equal to the value of the data_quantity flag, the return to the step of checking the occurrence of data jk in the field_unique dictionary , if the last table entry is processed, the field_unique dictionary is written to the encoding table file, the field_unique dictionary is cleared and the value of marker k is increased by 1, a check is made: if the last field of the table is not processed, namely the value of marker k is not equal to the value of the fields_quantity flag, the return to the step of setting the value of the marker j, if the last field is processed, the value of the marker of the number of the processed table i is increased by 1, a check is made: if the database is not processed completely, namely the value of the flag i is greater than the value of the number of tables n, the transition to the step of creating the data dictionary takes place, if the end of the table is reached, generates When the report on the work done is completed and the work is completed, the process of sending a request to the database is performed as follows: establish a connection to the database for receiving / transmitting data, if the connection is not established, a connection error message is displayed and reconnection is confirmed if the reconnection is confirmed, reconnect to the database, if the reconnection is not confirmed, a progress report is generated and the work is completed, if the connection is successful, open the encoding table file for reading and writing, receive information containing a user request to database, write the received data to the open_data_list_src dictionary, form a string of encoded data encoded_data_src, form a dictionary bypass marker i and a flag for making changes to the encoding table f with initial values equal to 0, form the end of dictionary reaching flag len_src, writing the value of the length of the open_data_list_src dictionary is added to it, a check is made: if the value open_data_list_src i is present in the encoding table, the encoded value corresponding to open_data_list_src j is written to encoded_data_src , if the value open_data_list_src i is absent in the encoding table, the value open_data_list_src i is entered into the encoding table, the value of flag f set equal to 1 and go to the step of writing the encoded value to encoded_data_src, the value of marker i is increased by 1, a check is made: if the end of the open_data_list_src dictionary is not reached, namely the value of marker i is not equal to the value of the flag len_src, go to the step of checking the presence of open_data_list_src i in the table encodings, if the end of the open_data_list_src dictionary is reached, a check is made: if the flag for making changes to the table f is 0, the encoded_data_src value is transmitted over the communication channel, if the f flag is not equal to 0, the encoding tables are synchronized and proceed to transferring the encode value d_data_src, receive the transmitted data, write the received data to the encoded_data_list_dst dictionary, open the encoding table for reading, form the decoded data string decoded_data_dst, form the dictionary bypass marker j with the initial value 0, form the end of the dictionary len_dst flag, write the value of the length of the encoded_data_list_dst dictionary to it , write the decoded value corresponding to encoded_data_list_src j into decoded_data_dst , increase the value of marker j by 1, check: if the end of the encoded_data_list_src dictionary is not reached, namely, the value of marker j is not equal to the value of the len_dst flag, go to the step of entering decoded data into decoded_data_dst, if the end encoded_data_list_src dictionary has been reached, the decoded_data_dst value is passed to the event handler, a progress report is generated, and work is completed.
RU2021111536A 2021-04-21 Method for replication of information in databases with encoding with simple syntactic replacement based on direct replacement table RU2787143C2 (en)

Publications (2)

Publication Number Publication Date
RU2021111536A RU2021111536A (en) 2022-10-21
RU2787143C2 true RU2787143C2 (en) 2022-12-29

Family

ID=

Citations (6)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US8204856B2 (en) * 2007-03-15 2012-06-19 Google Inc. Database replication
RU2531572C2 (en) * 2008-12-22 2014-10-20 РОКСТАР КОНСОРЦИУМ ЮЭс ЛП Database replication method and table updating apparatus
RU188004U1 (en) * 2018-07-25 2019-03-26 федеральное государственное бюджетное образовательное учреждение высшего образования "Российский государственный университет им. А.Н. Косыгина (Технологии. Дизайн. Искусство)" Information replication device in databases of independent computers
US20190278782A1 (en) * 2017-11-15 2019-09-12 International Business Machines Corporation Data replication in a database environment
RU2703961C1 (en) * 2018-07-25 2019-10-22 федеральное государственное бюджетное образовательное учреждение высшего образования "Российский государственный университет им. А.Н. Косыгина (Технологии. Дизайн. Искусство)" Information replication system in databases
RU2740865C1 (en) * 2017-11-01 2021-01-21 Свирлдз, Инк. Methods and device for efficient implementation of database supporting fast copying

Patent Citations (6)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
US8204856B2 (en) * 2007-03-15 2012-06-19 Google Inc. Database replication
RU2531572C2 (en) * 2008-12-22 2014-10-20 РОКСТАР КОНСОРЦИУМ ЮЭс ЛП Database replication method and table updating apparatus
RU2740865C1 (en) * 2017-11-01 2021-01-21 Свирлдз, Инк. Methods and device for efficient implementation of database supporting fast copying
US20190278782A1 (en) * 2017-11-15 2019-09-12 International Business Machines Corporation Data replication in a database environment
RU188004U1 (en) * 2018-07-25 2019-03-26 федеральное государственное бюджетное образовательное учреждение высшего образования "Российский государственный университет им. А.Н. Косыгина (Технологии. Дизайн. Искусство)" Information replication device in databases of independent computers
RU2703961C1 (en) * 2018-07-25 2019-10-22 федеральное государственное бюджетное образовательное учреждение высшего образования "Российский государственный университет им. А.Н. Косыгина (Технологии. Дизайн. Искусство)" Information replication system in databases

Similar Documents

Publication Publication Date Title
US9305070B2 (en) Continuous change data capture without disruption of DDL
US8660987B2 (en) Data cache techniques in support of synchronization of databases in a distributed environment
CN109906448B (en) Method, apparatus, and medium for facilitating operations on pluggable databases
JP2020184774A (en) Method and system for protecting and verifying identity and credential via blockchain
KR100462839B1 (en) Method for database synchronization and conflict resolution between clients and server of mobile system
US20200089666A1 (en) Secure data isolation in a multi-tenant historization system
US7895172B2 (en) System and method for writing data dependent upon multiple reads in a distributed database
US11347720B2 (en) Data transfer and resource management system
CN115455499A (en) Method and system for distributed data storage with persistent integrity assurance
CN110837535A (en) Data synchronization method, device, equipment and medium
US11475031B2 (en) Identification and compiling of information relating to an entity
US20100030817A1 (en) Statement categorization and normalization
RU2787143C2 (en) Method for replication of information in databases with encoding with simple syntactic replacement based on direct replacement table
US20200104309A1 (en) Transaction merging for offline applications
Malkhi et al. Concise version vectors in WinFS
US7599903B2 (en) Systems and methods for extracting data sets from an online relational database into a data warehouse
US11061909B2 (en) Generating a single transactional data stream from multiple database logs
RU2703961C1 (en) Information replication system in databases
RU2706482C1 (en) Method of replication of information in databases
JP2002244908A (en) Database synchronous control method and db system by the method
CN114328464A (en) Data maintenance method, device, equipment and readable medium for distributed storage equipment
CN113342890A (en) Method and system for realizing cross-security isolation gatekeeper database real-time synchronization
CN113254457A (en) Account checking method, account checking system and computer readable storage medium
US20170116219A1 (en) Efficient differential techniques for metafiles
RU2021111536A (en) METHOD OF INFORMATION REPLICATION IN DATABASES WITH ENCODING BY SIMPLE SYNTAX REPLACEMENT BASED ON DIRECT REPLACEMENT TABLE