handleBatch method

Future handleBatch()

Handle batch.

Implementation

Future handleBatch() async {
  //devPrint(arguments);
  var database = getDatabaseOrThrow();
  var operations = getOperations();
  List<Map<String, Object?>>? results;
  var noResult = getNoResult();
  var continueOnError = getContinueOnError();
  if (!noResult) {
    results = <Map<String, Object?>>[];
  }
  for (var operation in operations) {
    Map<String, Object?> getErrorMap(SqfliteFfiException e) {
      return <String, Object?>{
        'error': <String, Object?>{
          'message': '$e',
          if (e.sql != null || e.sqlArguments != null)
            'data': {
              'sql': e.sql,
              if (e.sqlArguments != null) 'arguments': e.sqlArguments
            }
        }
      };
    }

    void addResult(dynamic result) {
      if (!noResult) {
        results!.add(<String, Object?>{'result': result});
      }
    }

    void addError(dynamic e, [dynamic st]) {
      if (_debug && st != null) {
        print('stack: $st');
      }
      SqfliteFfiException wrap(dynamic e) {
        return wrapAnyException(e)
          ..sql = operation.sql
          ..sqlArguments = operation.sqlArguments;
      }

      if (continueOnError) {
        if (!noResult) {
          results!.add(getErrorMap(wrap(e)));
        }
      } else {
        throw wrapAnyException(e)
          ..sql = operation.sql
          ..sqlArguments = operation.sqlArguments;
      }
    }

    switch (operation.method) {
      case methodInsert:
        {
          try {
            await database.handleExecute(
                sql: operation.sql!, sqlArguments: operation.sqlArguments);
            if (!noResult) {
              addResult(database.getLastInsertId());
            }
          } catch (e, st) {
            addError(e, st);
          }

          break;
        }
      case methodExecute:
        {
          try {
            await database.handleExecute(
                sql: operation.sql!, sqlArguments: operation.sqlArguments);
            addResult(null);
          } catch (e) {
            addError(e);
          }

          break;
        }
      case methodQuery:
        {
          try {
            var result = await database.handleQuery(
                sql: operation.sql!, sqlArguments: operation.sqlArguments);
            addResult(result);
          } catch (e) {
            addError(e);
          }

          break;
        }
      case methodUpdate:
        {
          try {
            await database.handleExecute(
                sql: operation.sql!, sqlArguments: operation.sqlArguments);
            if (!noResult) {
              addResult(database.getUpdatedRows());
            }
          } catch (e) {
            addError(e);
          }
          break;
        }
      default:
        throw 'batch operation ${operation.method} not supported';
    }
  }
  return results;
}