<commit_before>var InsertCommand = require('../commands/insert_command').InsertCommand
  , DeleteCommand = require('../commands/delete_command').DeleteCommand
  , UpdateCommand = require('../commands/update_command').UpdateCommand
  , DbCommand = require('../commands/db_command').DbCommand
  , utils = require('../utils')
  , hasWriteCommands = require('../utils').hasWriteCommands
  , shared = require('./shared');

/**
 * Precompiled regexes
 * @ignore
 **/
var eErrorMessages = /No matching object found/;

// ***************************************************
// Insert function
// ***************************************************
var insert = function insert (docs, options, callback) {
  if ('function' === typeof options) callback = options, options = {};
  if(options == null) options = {};
  if(!('function' === typeof callback)) callback = null;

  // Get a connection
  var connection = this.db.serverConfig.checkoutWriter();
  var useLegacyOps = options.useLegacyOps == null || options.useLegacyOps == false ? false : true;
  // If we support write commands let's perform the insert using it  
  if(!useLegacyOps && hasWriteCommands(connection) 
    && !Buffer.isBuffer(docs) 
    && !(Array.isArray(docs) && docs.length > 0 && Buffer.isBuffer(docs[0]))) {
      insertWithWriteCommands(this, Array.isArray(docs) ? docs : [docs], options, callback);
      return this
  } 

  // Backwards compatibility
  insertAll(this, Array.isArray(docs) ? docs : [docs], options, callback);
  return this;
};

//
// Uses the new write commands available from 2.6 >
//
var insertWithWriteCommands = function(self, docs, options, callback) {
  // Get the intended namespace for the operation
  var namespace = self.collectionName;

  // Ensure we have no \x00 bytes in the name causing wrong parsing
  if(!!~namespace.indexOf("\x00")) {
    return callback(new Error("namespace cannot contain a null character"), null);
  }

  // Check if we have passed in continue on error
  var continueOnError = typeof options['keepGoing'] == 'boolean' 
    ? options['keepGoing'] : false;
  continueOnError = typeof options['continueOnError'] == 'boolean' 
    ? options['continueOnError'] : continueOnError;

  // Do we serialzie functions
  var serializeFunctions = typeof options.serializeFunctions != 'boolean' 
    ? self.serializeFunctions : options.serializeFunctions;

  // Checkout a write connection
  var connection = self.db.serverConfig.checkoutWriter();  

  // Do we return the actual result document
  var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false;

  // Collect errorOptions
  var errorOptions = shared._getWriteConcern(self, options);

  // If we have a write command with no callback and w:0 fail
  if(errorOptions.w && errorOptions.w != 0 && callback == null) {
    throw new Error("writeConcern requires callback")
  }

  // Add the documents and decorate them with id's if they have none
  for(var index = 0, len = docs.length; index < len; ++index) {
    var doc = docs[index];

    // Add id to each document if it's not already defined
    if (!(Buffer.isBuffer(doc))
      && doc['_id'] == null
      && self.db.forceServerObjectId != true
      && options.forceServerObjectId != true) {
        doc['_id'] = self.pkFactory.createPk();
    }
  }

  // Single document write
  if(docs.length == 1) {
    // Create the write command
    var write_command = {
        insert: namespace
      , writeConcern: errorOptions
      , ordered: !continueOnError
      , documents: docs
    }

    // Execute the write command
    return self.db.command(write_command
      , { connection:connection
        , checkKeys: typeof options.checkKeys == 'boolean' ? options.checkKeys : true
        , serializeFunctions: serializeFunctions
        , writeCommand: true }
      , function(err, result) {  
        if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null);
        if(errorOptions.w == 0) return;
        if(callback == null) return;
        if(err != null) {
          return callback(err, null);
        }

        // Result has an error
        if(!result.ok || Array.isArray(result.writeErrors) && result.writeErrors.length > 0) {
          var error = utils.toError(result.writeErrors[0].errmsg);
          error.code = result.writeErrors[0].code;
          error.err = result.writeErrors[0].errmsg;
          // Return the error
          return callback(error, null);
        }

        if(fullResult) return callback(null, result);
        // Return the results for a whole batch
        callback(null, docs)
    });    
  } else {
    try {
      // Multiple document write (use bulk)
      var bulk = !continueOnError ? self.initializeOrderedBulkOp() : self.initializeUnorderedBulkOp();
      // Add all the documents
      for(var i = 0; i < docs.length;i++) {
        bulk.insert(docs[i]);
      }

      // Execute the command
      bulk.execute(errorOptions, function(err, result) {
        if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null);
        if(errorOptions.w == 0) return;
        if(callback == null) return;
        if(err) return callback(err, null);
        if(result.hasWriteErrors()) {
          var error = result.getWriteErrors()[0];
          error.code = result.getWriteErrors()[0].code;
          error.err = result.getWriteErrors()[0].errmsg;        
          // Return the error
          return callback(error, null);
        }

        if(fullResult) return callback(null, result.getRawResponse());
        // Return the results for a whole batch
        callback(null, docs)
      });
    } catch(err) {
      callback(utils.toError(err), null);
    }
  }
}

//<commit_msg>Provides fullResult even in an error state which is useful in Bulk inserts to reconcile requests that succeeded before the failure.<commit_after>var InsertCommand = require('../commands/insert_command').InsertCommand
  , DeleteCommand = require('../commands/delete_command').DeleteCommand
  , UpdateCommand = require('../commands/update_command').UpdateCommand
  , DbCommand = require('../commands/db_command').DbCommand
  , utils = require('../utils')
  , hasWriteCommands = require('../utils').hasWriteCommands
  , shared = require('./shared');

/**
 * Precompiled regexes
 * @ignore
 **/
var eErrorMessages = /No matching object found/;

// ***************************************************
// Insert function
// ***************************************************
var insert = function insert (docs, options, callback) {
  if ('function' === typeof options) callback = options, options = {};
  if(options == null) options = {};
  if(!('function' === typeof callback)) callback = null;

  // Get a connection
  var connection = this.db.serverConfig.checkoutWriter();
  var useLegacyOps = options.useLegacyOps == null || options.useLegacyOps == false ? false : true;
  // If we support write commands let's perform the insert using it  
  if(!useLegacyOps && hasWriteCommands(connection) 
    && !Buffer.isBuffer(docs) 
    && !(Array.isArray(docs) && docs.length > 0 && Buffer.isBuffer(docs[0]))) {
      insertWithWriteCommands(this, Array.isArray(docs) ? docs : [docs], options, callback);
      return this
  } 

  // Backwards compatibility
  insertAll(this, Array.isArray(docs) ? docs : [docs], options, callback);
  return this;
};

//
// Uses the new write commands available from 2.6 >
//
var insertWithWriteCommands = function(self, docs, options, callback) {
  // Get the intended namespace for the operation
  var namespace = self.collectionName;

  // Ensure we have no \x00 bytes in the name causing wrong parsing
  if(!!~namespace.indexOf("\x00")) {
    return callback(new Error("namespace cannot contain a null character"), null);
  }

  // Check if we have passed in continue on error
  var continueOnError = typeof options['keepGoing'] == 'boolean' 
    ? options['keepGoing'] : false;
  continueOnError = typeof options['continueOnError'] == 'boolean' 
    ? options['continueOnError'] : continueOnError;

  // Do we serialzie functions
  var serializeFunctions = typeof options.serializeFunctions != 'boolean' 
    ? self.serializeFunctions : options.serializeFunctions;

  // Checkout a write connection
  var connection = self.db.serverConfig.checkoutWriter();  

  // Do we return the actual result document
  var fullResult = typeof options.fullResult == 'boolean' ? options.fullResult : false;

  // Collect errorOptions
  var errorOptions = shared._getWriteConcern(self, options);

  // If we have a write command with no callback and w:0 fail
  if(errorOptions.w && errorOptions.w != 0 && callback == null) {
    throw new Error("writeConcern requires callback")
  }

  // Add the documents and decorate them with id's if they have none
  for(var index = 0, len = docs.length; index < len; ++index) {
    var doc = docs[index];

    // Add id to each document if it's not already defined
    if (!(Buffer.isBuffer(doc))
      && doc['_id'] == null
      && self.db.forceServerObjectId != true
      && options.forceServerObjectId != true) {
        doc['_id'] = self.pkFactory.createPk();
    }
  }

  // Single document write
  if(docs.length == 1) {
    // Create the write command
    var write_command = {
        insert: namespace
      , writeConcern: errorOptions
      , ordered: !continueOnError
      , documents: docs
    }

    // Execute the write command
    return self.db.command(write_command
      , { connection:connection
        , checkKeys: typeof options.checkKeys == 'boolean' ? options.checkKeys : true
        , serializeFunctions: serializeFunctions
        , writeCommand: true }
      , function(err, result) {  
        if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null);
        if(errorOptions.w == 0) return;
        if(callback == null) return;
        if(err != null) {
          return callback(err, null);
        }

        // Result has an error
        if(!result.ok || Array.isArray(result.writeErrors) && result.writeErrors.length > 0) {
          var error = utils.toError(result.writeErrors[0].errmsg);
          error.code = result.writeErrors[0].code;
          error.err = result.writeErrors[0].errmsg;
          
          if (fullResult) return callback(error, result.getRawResponse());
          // Return the error
          return callback(error, null);
        }

        if(fullResult) return callback(null, result);
        // Return the results for a whole batch
        callback(null, docs)
    });    
  } else {
    try {
      // Multiple document write (use bulk)
      var bulk = !continueOnError ? self.initializeOrderedBulkOp() : self.initializeUnorderedBulkOp();
      // Add all the documents
      for(var i = 0; i < docs.length;i++) {
        bulk.insert(docs[i]);
      }

      // Execute the command
      bulk.execute(errorOptions, function(err, result) {
        if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null);
        if(errorOptions.w == 0) return;
        if(callback == null) return;
        if(err) return callback(err, null);
        if(result.hasWriteErrors()) {
          var error = result.getWriteErrors()[0];
          error.code = result.getWriteErrors()[0].code;
          error.err = result.getWriteErrors()[0].errmsg;        
          
          if (fullResult) return callback(error, result.getRawResponse());
          // Return the error
          return callback(error, null);
        }

        if(fullResult) return callback(null, result.getRawResponse());
        // Return the results for a whole batch
        callback(null, docs)
      });
    } catch(err) {
      callback(utils.toError(err), null);
    }
  }
}

//
{'fraction_non_alphanumeric': 0.1415560095335376, 'fraction_numerical': 0.0040858018386108275, 'mean_word_length': 2.9746278755074425, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7634733', 'n_tokens_mistral': 3286, 'n_tokens_neox': 3193, 'n_words': 904}