X DevAPI 用户指南  / 第 8 章语句执行  / 8.1 交易处理  /  8.1.1 处理警告

8.1.1 处理警告

类似于执行单个语句提交或回滚事务也会触发警告。为了能够处理这些警告, 需要检查 Session.commit();or 的回复结果对象。Session.rollback();

这在以下示例中显示。该示例假定测试架构存在且集合 my_collection不存在。

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);
}

默认情况下,所有警告都从服务器发送到客户端。如果已知某个操作会生成许多警告并且这些警告对应用程序没有价值,则可以抑制发送警告。这有助于节省带宽。 session.setFetchWarnings()控制警告是在服务器上丢弃还是发送到客户端。 session.getFetchWarnings()用于了解当前活动的设置。

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);