Similar to the execution of single statements committing or
rolling back a transaction can also trigger warnings. To be able
to process these warnings the replied result object of
Session.commit();
or
Session.rollback();
needs to be checked.
This is shown in the following example. The example assumes that
the test schema exists and that the collection
my_collection
does not exist.
var mysqlx = require('mysqlx');
// Connect to server
var mySession = mysqlx.getSession( {
host: 'localhost', port: 33060,
user: 'user', password: 'password' } );
// Get the Schema test
var myDb = mySession.getSchema('test');
// Create a new collection
var myColl = myDb.createCollection('my_collection');
// Start a transaction
mySession.startTransaction();
try
{
myColl.add({'name': 'Rohit', 'age': 18, 'height': 1.76}).execute();
myColl.add({'name': 'Misaki', 'age': 24, 'height': 1.65}).execute();
myColl.add({'name': 'Leon', 'age': 39, 'height': 1.9}).execute();
// Commit the transaction if everything went well
var reply = mySession.commit();
// handle warnings
if (reply.warningCount){
var warnings = reply.getWarnings();
for (index in warnings){
var warning = warnings[index];
print ('Type ['+ warning.level + '] (Code ' + warning.code + '): ' + warning.message + '\n');
}
}
print ('Data inserted successfully.');
}
catch(err)
{
// Rollback the transaction in case of an error
reply = mySession.rollback();
// handle warnings
if (reply.warningCount){
var warnings = reply.getWarnings();
for (index in warnings){
var warning = warnings[index];
print ('Type ['+ warning.level + '] (Code ' + warning.code + '): ' + warning.message + '\n');
}
}
// Printing the error message
print ('Data could not be inserted: ' + err.message);
}
By default all warnings are sent from the server to the client.
If an operation is known to generate many warnings and the
warnings are of no value to the application then sending the
warnings can be suppressed. This helps to save bandwith.
session.setFetchWarnings()
controls whether
warnings are discarded at the server or are sent to the client.
session.getFetchWarnings()
is used to learn
the currently active setting.
var mysqlx = require('mysqlx');
function process_warnings(result){
if (result.getWarningCount()){
var warnings = result.getWarnings();
for (index in warnings){
var warning = warnings[index];
print ('Type ['+ warning.level + '] (Code ' + warning.code + '): ' + warning.message + '\n');
}
}
else{
print ("No warnings were returned.\n");
}
}
// Connect to server
var mySession = mysqlx.getSession( {
host: 'localhost', port: 33060,
user: 'user', password: 'password' } );
// Disables warning generation
mySession.setFetchWarnings(false);
var result = mySession.sql('drop schema if exists unexisting').execute();
process_warnings(result);
// Enables warning generation
mySession.setFetchWarnings(true);
var result = mySession.sql('drop schema if exists unexisting').execute();
process_warnings(result);