...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
...
For the heading consider "Working with transactions..."
Current approach for to working with transactions in RMB
Maybe, try to paraphrase the underlined sentences
Work with the database on the FOLIO project is presented through a custom solution on top of the VERTX.X Postgres Client. The main feature of working with To enable the work with a database in FOLIO project there is a custom solution implemented on top of the VERT.X Postgres Client. The main feature of working with RMB and VERT.X is the usage of the asynchronous approach. Sequential Sequential execution of operations requires handling that each operation was finished and all errors were operated. If the first operation was succeeded then the subsequent operation can be executed. The development of business logic arises the need for transactionality and rollback of all operations in case of an error in one of the operations. This is necessary to maintain consistency of data. At the moment, this possibility is implemented as follows:
...
Sequential execution of operations requires handling the completion of each operation and occurring errors. Each subsequent operation can be executed only if the previous one is succeeded. In order to maintain data consistency there is a need to execute the operations in transaction and be able to rollback the changes in case an error occurred. At the moment, this possibility is implemented as follows:
- *
TheA database connection object is created and the SQL command “BEGIN” is executed - The The connection object is passed as a parameter to the Postgres client's methods and, accordingly, all commands are executed within a single connection
- Handle all errors and Futures succeed All errors are handled and Futures are succeeded
- If an error occurs, you must explicitly call rollback
At rollback rollback must be explicitly called - At the end of a
athe transaction, you must explicitly call the endTransaction() method the endTransaction() method must be explicitly called - *After the end of the transaction - execute the SQL command “COMMIT” After the transaction is ended, the SQL command "COMMIT" is executed
The First and and the last operations RMB PostgresClient do does automatically
Example method with two operation in scope of one transaction
Code Block | ||||
---|---|---|---|---|
| ||||
public Future<Void> example() { Future future = Future.future(); PostgresClient client = PostgresClient.getInstance(vertx, tenantId); // start tx client.startTx(tx -> { // first operation client.get(tx, "upload_definition", UploadDefinition.class, new Criterion(), true, false, getHandler -> { if (getHandler.succeeded()) { // second operation client.save(tx, "upload_definition", UUID.randomUUID().toString(), getHandler.result(), saveHandler -> { if (saveHandler.succeeded()) { client.endTx(tx, endHandler -> { if (endHandler.succeeded()) { future.succeeded(); } else { client.rollbackTx(tx, rollbackHandler -> { future.fail(getHandler.cause()); }); } }); } else { client.rollbackTx(tx, rollbackHandler -> { future.fail(getHandler.cause()); }); } }); } else { client.rollbackTx(tx, rollbackHandler -> { future.fail(getHandler.cause()); }); } }); }); return future; } |
...
When developing a slightly more complex business logic, the difficulty arises in the fact that certain operations may take some time and, accordingly, at this moment there is a possibility that it will be necessary to process another such request. Without locking a record in the database, there is a high probability of “lost changes” when the second request will overwrite overwrites the changes made by the first one. But since VERTX.X is asynchronous, any locks and synchronous code executions are unacceptable, and the Persistence Context is absent. The most obvious solution is to use locks on the record in the database using the “SELECT FOR UPDATE” statement. Accordingly, to perform a safe update of the record in the database, you must must should:
- Create Transaction Object
- Select data from database for update (using “SELECT FOR UPDATE”)
- Do some kind of business logic operation
- Update entity in database
- Complete transaction
Such kind of the scenario was needed at mod-data-import for file upload functionality.
Steps for file upload example:
- Load Upload Definition UploadDefinition from database
- Check for FileDefinition
- Save file to the local storage
- Update Upload Definition UploadDefinition status
- Save changed Upload Definition UploadDefinition entity into the database
Upload Definition mutator interface for callback usage
...
Code Block | ||||
---|---|---|---|---|
| ||||
@Override
public Future<UploadDefinition> uploadFile(String fileId, String uploadDefinitionId, InputStream data, OkapiConnectionParams params) {
return uploadDefinitionService.updateBlocking(uploadDefinitionId, uploadDefinition -> {
Future<UploadDefinition> future = Future.future();
Optional<FileDefinition> optionalFileDefinition = uploadDefinition.getFileDefinitions().stream().filter(fileFilter -> fileFilter.getId().equals(fileId))
.findFirst();
if (optionalFileDefinition.isPresent()) {
FileDefinition fileDefinition = optionalFileDefinition.get();
FileStorageServiceBuilder
.build(vertx, tenantId, params)
.map(service -> service.saveFile(data, fileDefinition, params)
.setHandler(onFileSave -> {
if (onFileSave.succeeded()) {
uploadDefinition.setFileDefinitions(replaceFile(uploadDefinition.getFileDefinitions(), onFileSave.result()));
uploadDefinition.setStatus(uploadDefinition.getFileDefinitions().stream().allMatch(FileDefinition::getLoaded)
? UploadDefinition.Status.LOADED
: UploadDefinition.Status.IN_PROGRESS);
future.complete(uploadDefinition);
} else {
future.fail("Error during file save");
}
}));
} else {
future.fail("FileDefinition not found. FileDefinition ID: " + fileId);
}
return future;
});
} |
Problems of the current approach
When uUsing the asynchronous approach when working with a database, there are has a number of limitations and difficulties in when it comes to writing sequential or transactional business logic. Such as following:
The inability to simultaneously run multiple operations within a single connection
Code Block language java linenumbers true public void test1() { PostgresClient client = PostgresClient.getInstance(vertx, "diku");
...
client.startTx(tx -> { for (int i = 0; i <
...
5; i++) { // ConnectionStillRunningQueryException: [2] - There is a query still being run here - race -> false
...
client.save(tx, UPLOAD_DEFINITION_TABLE, UUID.randomUUID().toString(), new UploadDefinition().withId(UUID.randomUUID().toString()), reply -> { if
...
(reply.
...
succeeded()) {
...
System.out.println(reply.result()); } else {
...
...
...
...
System.out.println(reply.cause().getLocalizedMessage());
...
...
...
...
...
...
}
...
...
});
...
}
...
}); }
...
When using the asynchronous approach when working with a database, there are a number of limitations and difficulties in writing sequential or transactional business logic.
- The inability to simultaneously run multiple operations within a single connection
- A transaction is used within one connection and, accordingly, all subsequent actions must be performed in handlers and manually processed all errors and all errors must be manually processed. "Callback hell" as a result
- There is no support for some kind of persistence context and all locks must be done manually in the database by separate requests
- There is no possibility to easily manage the transaction isolation level at the application level
- Since all objects are stored in JSON format in the database, there is no way to be sure that the data is stored correctly. At the moment there is an opportunity to save any JSON in any table
- Because of the storage of objects in JSON format, it is not possible to build durable relationships between entities
- It is necessary either to store all the links in one big JSON object in one table or put them into the other tables and create primary keys that do not guarantee contact with another entity. Need to make several requests to load data by primary keys and insert them into the parent object
- RMB don't have all needed methods for working with transactions and queries.
- RMB don't have method for get() method using custom SQL script with transaction support
...