Applies retryWrites: true to a command if retryWrites is set on the command's database.

@param {object} target The target command to which we will apply retryWrites.
@param {object} db The database from which we can inherit a retryWrites value.
357543
function applyRetryableWrites(target, db) {
  if (db && db.s.options.retryWrites) {
    target.retryWrites = true;
  }

  return target;
}
1151871
function proceedIfDbValid(db, callback) {
  db.head('', function(err) {
    err = error.convertResponseError(err, function(err) {
      if (err && err.statusCode === 404) {
        // Override the error type and mesasge for the DB not found case
        var msg = `Database ${db.config.url.replace(/\/\/.+@/g, '//****:****@')}` +
        `/${db.config.db} does not exist. ` +
        'Check the URL and database name have been specified correctly.';
        var noDBErr = new Error(msg);
        noDBErr.name = 'DatabaseNotFound';
        return noDBErr;
      } else {
        // Delegate to the default error factory if it wasn't a 404
        return error.convertResponseError(err);
      }
    });
    // Callback with or without (i.e. undefined) error
    callback(err);
  });
}
417014
def _update_retryable(
            self, criteria, document, upsert=False,
            check_keys=True, multi=False, manipulate=False,
            write_concern=None, op_id=None, ordered=True,
            bypass_doc_val=False, collation=None, array_filters=None,
            session=None):
        """"""
        def _update(session, sock_info, retryable_write):
            return self._update(
                sock_info, criteria, document, upsert=upsert,
                check_keys=check_keys, multi=multi, manipulate=manipulate,
                write_concern=write_concern, op_id=op_id, ordered=ordered,
                bypass_doc_val=bypass_doc_val, collation=collation,
                array_filters=array_filters, session=session,
                retryable_write=retryable_write)

        return self.__database.client._retryable_write(
            (write_concern or self.write_concern).acknowledged and not multi,
            _update, session)
553684
function dropDatabase (db, fn) {
  db.connection.db.executeDbCommand({
    dropDatabase: 1
  }, function(err, result) {
    db.disconnect()
    fn && fn(err, result)
  })
}
578407
function validate(cmd, args, info) {
  AbstractCommand.prototype.validate.apply(this, arguments);
  if(args[0]) {
    var arg = ('' + args[0]).toLowerCase();
    if(arg !== Constants.SHUTDOWN.SAVE && arg !== Constants.SHUTDOWN.NOSAVE) {
      throw CommandSyntax;
    }

    // rewrite with boolean
    args[0] = (arg === Constants.SHUTDOWN.SAVE);
  }
}
1103416
function(type, name, opts, cb) {
  var key = [type, name].join('-');
  logger.debug('Storing command in DB: ' + key);
  storage.set(key, { command: type, target: name, options: opts }, cb);
}
938420
function DB() {
  this.requests = {}
  process.on('message', function(message) {
    if (message.type !== 'cache:response') {
      return
    }

    /** @type {{error: Error, response: string, uid: string, method: string}} */
    var data = message.data
    // The requests for this UID may not exist because there can be multiple
    // instances of Impromptu.
    if (!(this.requests[data.method] && this.requests[data.method][data.uid])) {
      return
    }

    var callbacks = this.requests[data.method][data.uid]
    for (var i = 0; i < callbacks.length; i++) {
      var callback = callbacks[i]
      callback(data.error, data.response)
    }

    delete this.requests[data.method][data.uid]
  }.bind(this))
}
1167527
function(db, opt_err) {

    if (df.hasFired()) {
      goog.log.warning(me.logger, 'database already set.');
    } else if (goog.isDef(opt_err)) {
      goog.log.warning(me.logger, opt_err ? opt_err.message : 'Error received.');
      me.idx_db_ = null;
      df.errback(opt_err);
    } else {
      goog.asserts.assertObject(db, 'db');
      me.idx_db_ = db;
      me.idx_db_.onabort = function(e) {
        goog.log.finest(me.logger, me + ': abort');
        var request = /** @type {IDBRequest} */ (e.target);
        me.onError(request.error);
      };
      me.idx_db_.onerror = function(e) {
        if (ydn.db.con.IndexedDb.DEBUG) {
          goog.global.console.log(e);
        }
        goog.log.finest(me.logger, me + ': error');
        var request = /** @type {IDBRequest} */ (e.target);
        me.onError(request.error);
      };

      /**
       * @this {null}
       * @param {IDBVersionChangeEvent} event event.
       */
      me.idx_db_.onversionchange = function(event) {
        // Handle version changes while a web app is open in another tab
        // https://developer.mozilla.org/en-US/docs/IndexedDB/Using_IndexedDB#
        // Version_changes_while_a_web_app_is_open_in_another_tab
        //
        if (ydn.db.con.IndexedDb.DEBUG) {
          goog.global.console.log([this, event]);
        }
        goog.log.finest(me.logger, me + ' closing connection for onversionchange to: ' +
            event.version);
        if (me.idx_db_) {
          me.idx_db_.onabort = null;
          me.idx_db_.onblocked = null;
          me.idx_db_.onerror = null;
          me.idx_db_.onversionchange = null;
          me.onVersionChange(event);
          if (!event.defaultPrevented) {
            me.idx_db_.close();
            me.idx_db_ = null;
            var e = new Error();
            e.name = event.type;
            me.onFail(e);
          }
        }
      };
      df.callback(parseFloat(old_version));
    }

  }
616876
def _retry_with_session(self, retryable, func, session, bulk):
        
        retryable = (retryable and self.retry_writes
                     and session and not session._in_transaction)
        last_error = None
        retrying = False

        def is_retrying():
            return bulk.retrying if bulk else retrying
        # Increment the transaction id up front to ensure any retry attempt
        # will use the proper txnNumber, even if server or socket selection
        # fails before the command can be sent.
        if retryable:
            session._start_retryable_write()
            if bulk:
                bulk.started_retryable_write = True

        while True:
            try:
                server = self._select_server(writable_server_selector, session)
                supports_session = (
                    session is not None and
                    server.description.retryable_writes_supported)
                with self._get_socket(server, session) as sock_info:
                    if retryable and not supports_session:
                        if is_retrying():
                            # A retry is not possible because this server does
                            # not support sessions raise the last error.
                            raise last_error
                        retryable = False
                    return func(session, sock_info, retryable)
            except ServerSelectionTimeoutError:
                if is_retrying():
                    # The application may think the write was never attempted
                    # if we raise ServerSelectionTimeoutError on the retry
                    # attempt. Raise the original exception instead.
                    raise last_error
                # A ServerSelectionTimeoutError error indicates that there may
                # be a persistent outage. Attempting to retry in this case will
                # most likely be a waste of time.
                raise
            except ConnectionFailure as exc:
                if not retryable or is_retrying():
                    raise
                if bulk:
                    bulk.retrying = True
                else:
                    retrying = True
                last_error = exc
            except BulkWriteError as exc:
                if not retryable or is_retrying():
                    raise
                # Check the last writeConcernError to determine if this
                # BulkWriteError is retryable.
                wces = exc.details['writeConcernErrors']
                wce = wces[-1] if wces else {}
                if wce.get('code', 0) not in helpers._RETRYABLE_ERROR_CODES:
                    raise
                if bulk:
                    bulk.retrying = True
                else:
                    retrying = True
                last_error = exc
            except OperationFailure as exc:
                if not retryable or is_retrying():
                    raise
                if exc.code not in helpers._RETRYABLE_ERROR_CODES:
                    raise
                if bulk:
                    bulk.retrying = True
                else:
                    retrying = True
                last_error = exc
34258
private static boolean rewriteTableAlias(StmtSubqueryScan scan) {
        final AbstractParsedStmt stmt = scan.getSubqueryStmt();
        return stmt instanceof ParsedSelectStmt && (new MVQueryRewriter((ParsedSelectStmt)stmt)).rewrite();
    }
1035836
function (cmd, callback) {
    if (!cmd || !_.isObject(cmd)) {
      var err = new Error('Please pass a valid command!');
      debug(err);
      throw err;
    }

    if (!callback || !_.isFunction(callback)) {
      var err = new Error('Please pass a valid callback!');
      debug(err);
      throw err;
    }

    var target = this.getTargetInformation(cmd);

    var commandHandler = this.tree.getCommandHandler(target);

    // if (!commandHandler) {
    //   commandHandler = this.tree.getCommandHandlerByOldTarget(target);
    // }

    if (!commandHandler) {
      var err = new Error('No command handler found for ' + target.name);
      debug(err);
      return callback(err);
    }

    if (!this.commandBumper) {
      return commandHandler.handle(cmd, callback);
    }

    var key = target.context + target.aggregate + target.aggregateId + dotty.get(cmd, this.definition.id);

    this.commandBumper.add(key, function (err, added) {
      if (err) {
        return callback(err);
      }

      if (!added) {
        return callback(new DuplicateCommandError('Command already seen!'));
      }

      commandHandler.handle(cmd, callback);
    });
  }
1215654
function clear(dbid) {
  return new Promise((resolve, reject) => {
    return instance[dbid].then(db => {
      const req = db.transaction(db.name, 'readwrite')
          .objectStore(db.name).clear();
        req.onsuccess = () => resolve();
        req.onerror = event => reject(event);
    });
  });
}
700806
private void rewriteInternal(
      final BatchHelper batchHelper,
      final KeySetView<IOException, Boolean> innerExceptions,
      final String srcBucketName, final String srcObjectName,
      final String dstBucketName, final String dstObjectName)
      throws IOException {
    Storage.Objects.Rewrite rewriteObject =
        configureRequest(
            gcs.objects().rewrite(srcBucketName, srcObjectName, dstBucketName, dstObjectName, null),
            srcBucketName);
    if (storageOptions.getMaxBytesRewrittenPerCall() > 0) {
      rewriteObject.setMaxBytesRewrittenPerCall(storageOptions.getMaxBytesRewrittenPerCall());
    }

    // TODO(b/79750454) do not batch rewrite requests because they time out in batches.
    batchHelper.queue(
        rewriteObject,
        new JsonBatchCallback<RewriteResponse>() {
          @Override
          public void onSuccess(RewriteResponse rewriteResponse, HttpHeaders responseHeaders) {
            String srcString = StorageResourceId.createReadableString(srcBucketName, srcObjectName);
            String dstString = StorageResourceId.createReadableString(dstBucketName, dstObjectName);

            if (rewriteResponse.getDone()) {
              logger.atFine().log("Successfully copied %s to %s", srcString, dstString);
            } else {
              // If an object is very large, we need to continue making successive calls to
              // rewrite until the operation completes.
              logger.atFine().log(
                  "Copy (%s to %s) did not complete. Resuming...", srcString, dstString);
              try {
                Storage.Objects.Rewrite rewriteObjectWithToken =
                    configureRequest(
                        gcs.objects()
                            .rewrite(
                                srcBucketName, srcObjectName, dstBucketName, dstObjectName, null),
                        srcBucketName);
                if (storageOptions.getMaxBytesRewrittenPerCall() > 0) {
                  rewriteObjectWithToken.setMaxBytesRewrittenPerCall(
                      storageOptions.getMaxBytesRewrittenPerCall());
                }
                rewriteObjectWithToken.setRewriteToken(rewriteResponse.getRewriteToken());
                batchHelper.queue(rewriteObjectWithToken, this);
              } catch (IOException e) {
                innerExceptions.add(e);
              }
            }
          }

          @Override
          public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
            onCopyFailure(innerExceptions, e, srcBucketName, srcObjectName);
          }
        });
  }
341098
function validateDataTarget(connections, dataTarget, cb) {
  var DataTarget = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_TARGET);
  var testDataTarget = new DataTarget(dataTarget);
  //Validating Without Saving
  testDataTarget.validate(function(err) {
    if (err) {
      return cb(buildErrorResponse({
        error: err,
        userDetail: "Invalid Data Target Creation Data.",
        systemDetail: err.errors,
        code: ERROR_CODES.FH_FORMS_INVALID_PARAMETERS
      }));
    }

    return cb(undefined, dataTarget);
  });
}
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
1165572
function validate(cmd, args, info) {
  AbstractCommand.prototype.validate.apply(this, arguments);
  var index = parseInt(args[0]);
  if(isNaN(index) || index < 0 || index >= info.conf.databases) {
    throw DatabaseIndex;
  }
  // update the index with the integer value
  // connection expects an integer
  args[0] = index;
}
80683
function (config) {
        // at this stage, the `db` variable should not exist. expecting fresh setup or post teardown setup.
        if (Transaction.databases[config.identity]) {
            // @todo - emit wrror event instead of console.log
            console.log('Warn: duplicate setup of connection found in Transactions.setup');
            this.teardown();
        }

        var _db;

        // clone the configuration
        config = util.clone(config);
        delete config.replication;

        // allow special transaction related config
        util.each(config, function (value, name, config) {
            if (!/^transaction.+/g.test(name)) { return; }

            // remove transaction config prefix
            var baseName = name.replace(/^transaction/g, '');
            baseName = baseName.charAt(0).toLowerCase() + baseName.slice(1);

            delete config[name];
            config[baseName] = value;
        });

        _db = db.createSource(config);

        // Save a few configurations
        _db && (_db.transactionConfig = {
            rollbackOnError: config.rollbackTransactionOnError
        });

        Transaction.databases[config.identity] = _db;
    }