Execute write operation
174204
function executeWriteOperation(args, options, callback) {
  if (typeof options === 'function') (callback = options), (options = {});
  options = options || {};

  // TODO: once we drop Node 4, use destructuring either here or in arguments.
  const self = args.self;
  const op = args.op;
  const ns = args.ns;
  const ops = args.ops;

  if (self.state === DESTROYED) {
    return callback(new MongoError(f('topology was destroyed')));
  }

  const willRetryWrite =
    !args.retrying &&
    !!options.retryWrites &&
    options.session &&
    isRetryableWritesSupported(self) &&
    !options.session.inTransaction();

  if (!self.s.replicaSetState.hasPrimary()) {
    if (self.s.disconnectHandler) {
      // Not connected but we have a disconnecthandler
      return self.s.disconnectHandler.add(op, ns, ops, options, callback);
    } else if (!willRetryWrite) {
      // No server returned we had an error
      return callback(new MongoError('no primary server found'));
    }
  }

  const handler = (err, result) => {
    if (!err) return callback(null, result);
    if (!isRetryableError(err)) {
      return callback(err);
    }

    if (willRetryWrite) {
      const newArgs = Object.assign({}, args, { retrying: true });
      return executeWriteOperation(newArgs, options, callback);
    }

    // Per SDAM, remove primary from replicaset
    if (self.s.replicaSetState.primary) {
      self.s.replicaSetState.remove(self.s.replicaSetState.primary, { force: true });
    }

    return callback(err);
  };

  if (callback.operationId) {
    handler.operationId = callback.operationId;
  }

  // increment and assign txnNumber
  if (willRetryWrite) {
    options.session.incrementTransactionNumber();
    options.willRetryWrite = willRetryWrite;
  }

  self.s.replicaSetState.primary[op](ns, ops, options, handler);
}
724941
def do_execute(self):
        
        result = None
        f = None
        try:
            if bool(self.resolve_option("append")):
                f = open(str(self.resolve_option("output")), "a")
            else:
                f = open(str(self.resolve_option("output")), "w")
            f.write(str(self.input.payload))
            f.write("\n")
        except Exception as e:
            result = self.full_name + "\n" + traceback.format_exc()
        finally:
            if f is not None:
                f.close()
        return result
1137668
def _writen(fd, data):
    """"""
    while data:
        n = os.write(fd, data)
        data = data[n:]
1013322
async def write(self, data):
        
        self.writer.write((bytes([ord(data)])))
        await self.writer.drain()
552790
def _encode_batched_write_command(
        namespace, operation, command, docs, check_keys, opts, ctx):
    
    buf = StringIO()

    to_send, _ = _batched_write_command_impl(
        namespace, operation, command, docs, check_keys, opts, ctx, buf)
    return buf.getvalue(), to_send
1244698
def write_output(self):
        """"""
        for data in self.output_data.values():
            self.create_output(data.get('key'), data.get('value'), data.get('type'))
199239
def _execute(self, ifile, process):
        
        self._record_writer.write_records(process(self._records(ifile)))
        self.finish()
485762
def write_output(self):
        
        # output
        self.tcex.log.debug('output_strings: {}'.format(self.output_strings))

        self.tcex.playbook.create_output('string.operation', self.args.tc_action)
        self.tcex.playbook.create_output('string.outputs', self.output_strings)
        if self.output_strings:
            self.tcex.playbook.create_output('string.outputs.0', self.output_strings[0])
        self.tcex.playbook.create_output('string.outputs.count', len(self.output_strings))
1283770
def _do_bulk_write_command(
        namespace, operation, command, docs, check_keys, opts, ctx):
    """"""
    if ctx.sock_info.max_wire_version > 5:
        return _do_batched_op_msg(
            namespace, operation, command, docs, check_keys, opts, ctx)
    return _do_batched_write_command(
        namespace, operation, command, docs, check_keys, opts, ctx)
649620
def _execute(self, args, log=True):
        """"""
        if not self._ready:
            self.open_or_create()
        output = ''
        error = ''
        try:
            proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            output, error = proc.communicate()
            returncode = proc.returncode
            if returncode:
                raise subprocess.CalledProcessError(returncode, proc, (output, error))
            return to_text(output)
        except OSError as e:
            # raise a more meaningful error with the program name
            prog = args[0]
            if prog[0] != os.sep:
                prog = os.path.join(self.path, prog)
            raise OSError('%s: %s' % (prog, six.u(str(e))))
        except subprocess.CalledProcessError as e:
            output, error = e.output
            e.output = output
            raise e
        finally:
            if log:
                try:
                    self._write_to_log(to_text(output))
                    self._write_to_error(to_text(error))
                except NameError:
                    pass
1066944
def _write(self, *args, **kwargs):
        
        if self.filter_fn(*args, **kwargs):
            self.stream.write(*args, **kwargs)
128919
def do_execute(self):
        
        for s in self.resolve_option("strings"):
            self._output.append(Token(s))
        return None
21027
def write_command(self, command: Command):
        '''
        '''
        _logger.debug('Write command.')
        data = command.to_bytes()
        yield from self._connection.write(data)
        self._data_event_dispatcher.notify_write(data)
562591
def execute_edit(args, root_dir=None):
    
    # Get editor
    EDITOR = os.environ.get('EDITOR', 'vim')
    # Get command from server
    key = args['key']
    status = command_factory('status')({}, root_dir=root_dir)

    # Check if queue is not empty, the entry exists and is queued or stashed
    if not isinstance(status['data'], str) and key in status['data']:
        if status['data'][key]['status'] in ['queued', 'stashed']:
            command = status['data'][key]['command']
        else:
            print("Entry is not 'queued' or 'stashed'")
            sys.exit(1)
    else:
        print('No entry with this key')
        sys.exit(1)

    with tempfile.NamedTemporaryFile(suffix=".tmp") as tf:
        tf.write(command.encode('utf-8'))
        tf.flush()
        call([EDITOR, tf.name])

        # do the parsing with `tf` using regular File operations.
        # for instance:
        tf.seek(0)
        edited_command = tf.read().decode('utf-8')

    print_command_factory('edit')({
        'key': key,
        'command': edited_command,
    }, root_dir=root_dir)
20767
def _do_batched_write_command(namespace, operation, command,
                              docs, check_keys, opts, ctx):
    
    max_bson_size = ctx.max_bson_size
    max_write_batch_size = ctx.max_write_batch_size
    # Max BSON object size + 16k - 2 bytes for ending NUL bytes.
    # Server guarantees there is enough room: SERVER-10643.
    max_cmd_size = max_bson_size + _COMMAND_OVERHEAD

    ordered = command.get('ordered', True)

    buf = StringIO()
    # Save space for message length and request id
    buf.write(_ZERO_64)
    # responseTo, opCode
    buf.write(b"\x00\x00\x00\x00\xd4\x07\x00\x00")
    # No options
    buf.write(_ZERO_32)
    # Namespace as C string
    buf.write(b(namespace))
    buf.write(_ZERO_8)
    # Skip: 0, Limit: -1
    buf.write(_SKIPLIM)

    # Where to write command document length
    command_start = buf.tell()
    buf.write(bson.BSON.encode(command))

    # Start of payload
    buf.seek(-1, 2)
    # Work around some Jython weirdness.
    buf.truncate()
    try:
        buf.write(_OP_MAP[operation])
    except KeyError:
        raise InvalidOperation('Unknown command')

    if operation in (_UPDATE, _DELETE):
        check_keys = False

    # Where to write list document length
    list_start = buf.tell() - 4

    to_send = []

    def send_message():
        """Finalize and send the current OP_QUERY message.
        """
        # Close list and command documents
        buf.write(_ZERO_16)

        # Write document lengths and request id
        length = buf.tell()
        buf.seek(list_start)
        buf.write(struct.pack('<i', length - list_start - 1))
        buf.seek(command_start)
        buf.write(struct.pack('<i', length - command_start))
        buf.seek(4)
        request_id = _randint()
        buf.write(struct.pack('<i', request_id))
        buf.seek(0)
        buf.write(struct.pack('<i', length))
        return ctx.write_command(request_id, buf.getvalue(), to_send)

    # If there are multiple batches we'll
    # merge results in the caller.
    results = []

    idx = 0
    idx_offset = 0
    has_docs = False
    for doc in docs:
        has_docs = True
        # Encode the current operation
        key = b(str(idx))
        value = bson.BSON.encode(doc, check_keys, opts)
        # Send a batch?
        enough_data = (buf.tell() + len(key) + len(value) + 2) >= max_cmd_size
        enough_documents = (idx >= max_write_batch_size)
        if enough_data or enough_documents:
            if not idx:
                write_op = "insert" if operation == _INSERT else None
                _raise_document_too_large(
                    write_op, len(value), max_bson_size)
            result = send_message()
            results.append((idx_offset, result))
            if ordered and "writeErrors" in result:
                return results

            # Truncate back to the start of list elements
            buf.seek(list_start + 4)
            buf.truncate()
            idx_offset += idx
            idx = 0
            key = b'0'
            to_send = []
        buf.write(_BSONOBJ)
        buf.write(key)
        buf.write(_ZERO_8)
        buf.write(value)
        to_send.append(doc)
        idx += 1

    if not has_docs:
        raise InvalidOperation("cannot do an empty bulk write")

    results.append((idx_offset, send_message()))
    return results
781447
def execute_command(self, generator, write_concern, session):
        
        # nModified is only reported for write commands, not legacy ops.
        full_result = {
            "writeErrors": [],
            "writeConcernErrors": [],
            "nInserted": 0,
            "nUpserted": 0,
            "nMatched": 0,
            "nModified": 0,
            "nRemoved": 0,
            "upserted": [],
        }
        op_id = _randint()

        def retryable_bulk(session, sock_info, retryable):
            self._execute_command(
                generator, write_concern, session, sock_info, op_id,
                retryable, full_result)

        client = self.collection.database.client
        with client._tmp_session(session) as s:
            client._retry_with_session(
                self.is_retryable, retryable_bulk, s, self)

        if full_result["writeErrors"] or full_result["writeConcernErrors"]:
            _raise_bulk_write_error(full_result)
        return full_result
1319986
function ExecuteWriter(queryId, params, consistency) {
  this.queryId = queryId;
  this.params = params || [];
  this.consistency = consistency;
  this.streamId = null;
  if (consistency === null || typeof consistency === 'undefined') {
    this.consistency = types.consistencies.getDefault();
  }
}