Sends a "Scan" request to DynamoDB to "fetch" a collection.

@param {Object} dynamoDbParams DynamoDB [scan](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#scan-property) parameters.
@param {Object} options Additional `fetch` options.
172565
function (dynamoDbParams, options) {
		var _options = { scan: dynamoDbParams };
		_.extend( _options, options );
		return this.fetch( _options );
	}
504248
public function scanAll($conditions = '',
                            array $params = [],
                            $indexName = DynamoDbIndex::PRIMARY_INDEX,
                            $isConsistentRead = false,
                            $isAscendingOrder = true,
                            $parallel = 1)
    {
        $ret = new \SplDoublyLinkedList();
        $this->scanAndRun(
            function ($item) use ($ret) {
                $ret->push($item);
            },
            $conditions,
            $params,
            $indexName,
            $isConsistentRead,
            $isAscendingOrder,
            $parallel
        );
        
        return $ret;
    }
1034367
function (queryKey, params, fn) {
    this.connection.query(templates[queryKey], params, function (err, result) {
      if (err) {
        fn(err, null);
      } else {
        fn(null, result.length ? result[0] : null);
      }
    });
  }
989278
function(params, callback) {
			var self = this;
			var collections = [];
		  // Get the collections for this dbName
	  	this.db.listCollections().toArray(function(err, colls) {
			  // Loop through the collections
	  		for (var n = 0; n < colls.length; n++) {

	  			var options = colls[n].options || {};
	  			// Remove the old name.
	  			delete options.create;
		  		// Remove the dbName from the collection name.
	  			options.name = parseName(colls[n].name);
	  			// Set the name as the _id.
	  			options._id = options.name;

	  			// Add it to the list.
	  	  	collections.push(options);
	  	  }

		  	// Async function to add stats to each collection.
		  	var addStats = function(coll, callback){
		  		// Switch databases
		  		var collection = self.db.collection(coll.name);
		  		// Get the stats. null if empty.
		  		collection.stats(function(err, stats){
		  			// Add the stats to the corresponding database.
		  			coll.stats = stats;
			  		callback(err, coll);
		  		});
		  	};

		  	async.each(collections, addStats, function(err){
	  	    if (err) {
	  	    	callback({error:err.errmsg});
	  	    } else {
	  	    	// Sort the collections
	  	    	collections.sort(function (a, b) {
	  	    		return (a.name > b.name) ? 1 : -1;
	  	    	});
	  	    	// Send the collections
					  return callback(null, collections);
	  	    }
		  	});
	  	});
		}
1284169
function putItem(model, options) {
	options || ( options = {} );
	if ( options.serializeDates !== false ) {
		// If serializeDates is NOT `false`, use `true` by default.
		options.serializeDates = true;
	}

	var newKey, // If the model `isNew`, a new key is generated.
		request,
		hashName, // Name of the hash attribute.
		rangeName, // Name of the range attribute.
		keyPromise,
		deferred = new _.Deferred(),
		/**
		 * Container object to store the attributes that are changed as part of saving the model.
		 */
		changed = {},
		/**
		 * Parameters to use in the DynamoDB PutItem request
		 */
		params = {
			/**
			 * Convert the model into an object.
			 * If `options.serializeDates` is `true`, `Date` values are converted into strings.
			 */
			Item: model.toJSON( options ),
			TableName: model._tableName()
		};

	if ( model.isNew() ) { // If the model is new, a new key attribute(s) must be generated
		hashName = _.result( model, 'hashAttribute' ) || _.result( model, 'idAttribute' );
		rangeName = _.result( model, 'rangeAttribute' );

		/**
		 * Convenience method to set the `newKey` attribute(s), once it's generated.
		 */
		function setNewKey(_newKey) {
			if ( rangeName ) {
				/**
				 * If the model has a range attribute, _newKey must be an object that contains
				 * the hash and range attributes.
				 */
				_.extend( changed, _newKey );
			} else {
				/**
				 * If the model doesn't have a range attribute, _newKey must be the value of the hash attribute.
				 */
				changed[ hashName ] = _newKey;
			}

			// Add the new key attribute(s) to the Item to be sent to DynamoDB
			_.extend( params.Item, options.serializeDates === true ? serializeAllDates( model, _.clone( changed ) ) : changed );
		}

		// Generate new key attribute(s)
		newKey = model.newKey( options );

		if ( isPromise( newKey ) ) {
			/**
			 * If `newKey` is a promise, wait until it's resolved to execute `setNewKey`
			 * and assign the resulting promise to `keyPromise`.
			 */
			keyPromise = newKey.then( setNewKey );
		} else {
			// If `newKey` is NOT a promise, call `setNewKey` right away.
			setNewKey( newKey );
		}
	}

	wrapComplete( model, options );
	_.extend( params, options.dynamodb );

	request = dynamo().putItem( params );

	request.on('complete', function (response) {
		var ctx = options.context || model;

		if ( response.error ) {
			deferred.rejectWith( ctx, [ response, options ] );
		} else {
			/**
			 * Backbone's "internal" success callback takes the changed attributes as the first argument.
			 * Make the entire AWS `response` available as `options.awsResponse`.
			 */
			options.awsResponse = response;
			deferred.resolveWith( ctx, [ changed, options ] );
		}
	});

	if ( !keyPromise ) {
		// If there's no `keyPromise`, send the request right away.
		request.send();
	} else {
		// If there's a `keyPromise`, wait until it is "done" before sending the request.
		keyPromise.done(function () {
			request.send();
		}).fail(function () {
			var ctx = options.context || model;
			deferred.rejectWith( ctx, arguments );
		});
	}

	deferred.done( options.success ).fail( options.error ).always( options.complete );

	return deferred.promise( request );
}
121794
public void createMongoDBCollection(String colectionName, DataTable options) {
        BasicDBObject aux = new BasicDBObject();
        // Recorremos las options para castearlas y añadirlas a la collection
        List<List<String>> rowsOp = options.raw();
        for (int i = 0; i < rowsOp.size(); i++) {
            List<String> rowOp = rowsOp.get(i);
            if (rowOp.get(0).equals("size") || rowOp.get(0).equals("max")) {
                int intproperty = Integer.parseInt(rowOp.get(1));
                aux.append(rowOp.get(0), intproperty);
            } else {
                Boolean boolProperty = Boolean.parseBoolean(rowOp.get(1));
                aux.append(rowOp.get(0), boolProperty);
            }
        }
        dataBase.createCollection(colectionName, aux);
    }
1308301
function run(query, params) {
        let stmt = sql.prepare(query);
        params = normalizeParams(params);
        stmt.run(params);
        stmt.free();
    }
549550
public ScanResultPage<T> scanPage(DynamoDBScanExpression scanExpression) {
        return mapper.<T>scanPage(model.targetType(), scanExpression);
    }
1183139
function (connectionInfo, query, params) {
    var connection;

    // Connection validation
    if (typeof connectionInfo.host !== 'string' || connectionInfo.host.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad hostname provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }
    if (typeof connectionInfo.user !== 'string' || connectionInfo.user.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad username provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }

    if (typeof connectionInfo.password !== 'string') {
        return respond({
            success: false,
            data: {
                err: 'Bad password provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }
    if (typeof connectionInfo.database !== 'string' || connectionInfo.database.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'Bad database provided.',
                query: query,
                connection: connectionInfo
            }
        });
    }


    // Return if no sql query specified
    if (query.length === 0) {
        return respond({
            success: false,
            data: {
                err: 'No SQL query specified.'
            }
        });
    }

    // Create the connection to the database
    connection = mysql.createConnection(connectionInfo);

    // Connect to the database
    connection.connect();

    // Do the query
    connection.query(query, params, function (err, rows, fields) {
        // End the connection
        connection.end();

        // Return the error and stop
        if (err) {
            return respond({
                success: false,
                data: {
                    err: err,
                    query: query,
                    connection: connectionInfo
                }

            });
        }

        // Do the callback
        respond({
            success: true,
            data: {
                rows: rows,
                fields: fields
            }
        });
    });
}
1359172
function (methodName, params, execOptions) {
                var requestId = this._getRequestId(methodName, params);
                var promise = this._getRequestPromise(requestId);

                if (!promise) {
                    this._addToBatch(methodName, params);
                    promise = this._createPromise(requestId);
                    this._run(execOptions);
                }

                return promise;
            }
802639
function getNextId(db, collectionName, fieldName, callback) {
    if (typeof fieldName == "function") {
        callback = fieldName;
        fieldName = null;
    }

    fieldName = fieldName || getOption(collectionName, "field");
    var collection = db.collection(defaultSettings.collection);
    var step = getOption(collectionName, "step");

    collection.findAndModify(
        {_id: collectionName, field: fieldName},
        null,
        {$inc: {seq: step}},
        {upsert: true, new: true},
        function (err, result) {
            if (err) {
                if (err.code == 11000) {
                    process.nextTick(getNextId.bind(null, db, collectionName, fieldName, callback));
                } else {
                    callback(err);
                }
            } else {
                if (result.value && result.value.seq) {
                    callback(null, result.value.seq);
                } else {
                    callback(null, result.seq);
                }
            }
        }
    );
}
580344
function execute(sql, params) {

	if (0 === sql.trim().length) {
		console.error("\nNo SQL to process\n");
		yargs.showHelp();
		process.exit(1);
	}

	for (var i = 1; i < params.length; i++) {
		var a = params[i];
		if (a[0] !== '"' && a[0] !== "'") {
			if (+a == a) { // jshint ignore:line
				params[i] = +a;
			}
		}
	}

	alasql.promise(sql, params)
		.then(function (res) {
			if (!alasql.options.stdout) {
				console.log(formatOutput(res));
			}
			process.exit(0);
		}).catch(function (err) {
			let errorJsonObj = JSON.parse(JSON.stringify(err, Object.getOwnPropertyNames(err)));
			console.error(formatOutput({
				error: errorJsonObj
			}));
			process.exit(1);
		});
}
1269213
function addQueryParams(req, res, next) {
  _assign(res.locals, req.params, req.query);
  next();
}
901
function( key, options ) {
			options || ( options = {} );
			var rel = this.getRelation( key ),
				keyContents = rel && rel.keyContents,
				toFetch = keyContents && _.select( _.isArray( keyContents ) ? keyContents : [ keyContents ], function( item ) {
						var id = _.isString( item ) || _.isNumber( item ) ? item : item[ rel.relatedModel.prototype.idAttribute ];
						return id && !Backbone.Relational.store.find( rel.relatedModel, id );
					}, this );
			
			if ( toFetch && toFetch.length ) {
				// Create a model for each entry in 'keyContents' that is to be fetched
				var models = _.map( toFetch, function( item ) {
						if ( typeof( item ) === 'object' ) {
							var model = new rel.relatedModel( item );
						}
						else {
							var attrs = {};
							attrs[ rel.relatedModel.prototype.idAttribute ] = item;
							var model = new rel.relatedModel( attrs );
						}
						return model;
					}, this );
				
				// Try if the 'collection' can provide a url to fetch a set of models in one request.
				if ( rel.related instanceof Backbone.Collection && _.isFunction( rel.related.url ) ) {
					var setUrl = rel.related.url( models );
				}
				
				// An assumption is that when 'Backbone.Collection.url' is a function, it can handle building of set urls.
				// To make sure it can, test if the url we got by supplying a list of models to fetch is different from
				// the one supplied for the default fetch action (without args to 'url').
				if ( setUrl && setUrl !== rel.related.url() ) {
					var opts = _.defaults( {
							error: function() {
									var args = arguments;
									_.each( models, function( model ) {
											model.destroy();
											options.error && options.error.apply( model, args );
										})
								},
							url: setUrl
						},
						options,
						{ add: true }
					);
					
					var requests = [ rel.related.fetch( opts ) ];
				}
				else {
					var requests = _.map( models, function( model ) {
							var opts = _.defaults( {
								error: function() {
										model.destroy();
										options.error && options.error.apply( model, arguments );
									}
								},
								options
							);
							return model.fetch( opts );
						}, this );
				}
			}
			
			return _.isUndefined( requests ) ? [] : requests;
		}
436413
function(params) {
		var me = this;

		if (Object.keys(model.columns).length == 0) {
			logger.error("Attempting to initialize `" + model.ident + "` instance before filling schema!");
			return null;
		} else if (model.primary === undefined) {
			logger.error("No primary key found for `" + model.ident + "`!");
			return null;
		}

		Object.defineProperty(me, 'values', {
			value: {},
			enumerable: false,
			writable: true,
			configurable: true,
		}); // Raw column values, accessed by setter/getter functions.

		params = params || {};

		/* --- Instance Methods --- */

		/**
		 * Saves the object's properties corresponding to table columns into the database.
		 */
		function save() {
			var act = new NobleMachine(function() {
				setStrs = [];

				for (var key in model.columns) {
					if ([model.primary].indexOf(key) == -1 && me[key] !== undefined) {
						setStrs.push('`' + key + '`' + " = " + nrutil.serialize(me[key]));
					}
				}

				if (model.columns['updatedAt'])
					setStrs.push('`updatedAt` = NOW()');

				var sql;
				if (me[model.primary]) {
					sql = "UPDATE " + model.table
							+ " SET " + setStrs.join(',')
							+ " WHERE `" + model.primary + "` = " + me[model.primary];
				} else {
					if (model.columns['createdAt'])
						setStrs.push('`createdAt` = NOW()');

					sql = "INSERT"
							+ " INTO " + model.table
							+ " SET " + setStrs.join(',');
				}


				act.toNext(db_query(sql));
			});

			act.next(function(result) {
				//log.debug("RESULT: " + JSON.stringify(result));

				if (result.insert_id) {
					me[model.primary] = result.insert_id;
				} else if (!me[model.primary]) {
					act.toError("No insert_id, and no extant primary key!");
					return;
				}

				
				logger.log("Successfully saved `" + model.ident + "` record `" + me[model.primary] + "`");

				act.toNext(me);
			});

			act.error(function(err) {
				logger.error("Error saving `" + model.ident + "` record: " + JSON.stringify(err));
				act.emitError(err);
			});

			return act;
		}

		/**
		 * Reloads the object's properties with the current database values.
		 */
		function reload() {
			var params = {}

			params[model.primary] = me[model.primary]
		
			var act = new NobleMachine(model.find(params));

			act.next(function(newInst) {
				if (newInst) {
					for (var col in model.columns) {
						me[col] = newInst[col];
					}

					act.toNext(me);
				} else {
					for (var key in model.columns) {
						me[key] = undefined
					}

					act.toNext(null);
				}
			});

			return act;
		}

		/**
		 * Removes this object's corresponding database row.
		 */
		function destroy() {
			var act = new NobleMachine(function() {
				if (me.onDestroy) {
					var preact = me.onDestroy();
					if (preact && preact.start instanceof Function) {
						act.toNext(preact)
						return;
					}
				}
			});

			act.next(function() {
				var sql = "DELETE FROM " + model.table
						+ " WHERE `" + model.primary + "` = " + me[model.primary];

				act.toNext(db_query(sql));
			});

			act.next(function() {
				logger.log("Successfully deleted `" + model.ident + "` record `" + me[model.primary] + "`");

				for (var param in me) {
					delete me[param];	
				}
			});

			act.error(function(err) {
				logger.error("Error deleting `" + model.ident + "` record: " + JSON.stringify(err));
				act.emitError(err);
			});

			return act;
		}

		// Generic setter for SQL-correspondent values. Forces typecasting for database compatibility.
		function setValue(key, val) {
			//util.log(key + ": " + JSON.stringify(val));

			if (val === null) {
				me.values[key] = null;
			} else if (val === undefined) {
				me.values[key] = undefined;
			} else {
				type = model.columns[key]['DATA_TYPE'];

				switch (type) {
					case 'datetime':
					case 'timestamp':
						me.values[key] = new Date(val);
						break;
					case 'text':
					case 'varchar':
						me.values[key] = val.toString();
						break;
					case 'int':
					case 'tinyint':
						if (model.columns[key]['COLUMN_TYPE'] == 'tinyint(1)') {
							me.values[key] = !!val // Boolean
						} else {
							me.values[key] = parseInt(val);
						}
						break;
					default:
						me.values[key] = val;
				}
			}
		}

		// Generic getter for SQL-correspondent values.
		function getValue(key) {
			return me.values[key];
		}

		for (var key in model.columns) {
			me.__defineSetter__(key, setValue.bind(me, key));
			me.__defineGetter__(key, getValue.bind(me, key));

			if (params[key] !== undefined) {
				setValue(key, params[key]);
			}
		}

		_.extend(me, {
			save: save,
			reload: reload,
			destroy: destroy,
			setValue: setValue
		});

		if (defFunc !== undefined) {
			defFunc(me);
		}

		return me;
	}
584760
@SneakyThrows
    public AmazonDynamoDB createAmazonDynamoDb(final AbstractDynamoDbProperties props) {
        if (props.isLocalInstance()) {
            LOGGER.debug("Creating DynamoDb standard client with endpoint [{}] and region [{}]",
                props.getEndpoint(), props.getRegion());
            val endpoint = new AwsClientBuilder.EndpointConfiguration(
                props.getEndpoint(), props.getRegion());
            return AmazonDynamoDBClientBuilder.standard()
                .withEndpointConfiguration(endpoint)
                .build();
        }

        val provider = ChainingAWSCredentialsProvider.getInstance(props.getCredentialAccessKey(),
            props.getCredentialSecretKey(), props.getCredentialsPropertiesFile());

        LOGGER.trace("Creating DynamoDb client configuration...");
        val cfg = AmazonClientConfigurationBuilder.buildClientConfiguration(props);

        LOGGER.debug("Creating DynamoDb client instance...");
        val clientBuilder = AmazonDynamoDBClientBuilder
            .standard()
            .withClientConfiguration(cfg)
            .withCredentials(provider);

        val region = StringUtils.defaultIfBlank(props.getRegionOverride(), props.getRegion());

        if (StringUtils.isNotBlank(props.getEndpoint())) {
            LOGGER.trace("Setting DynamoDb client endpoint [{}]", props.getEndpoint());
            clientBuilder.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(props.getEndpoint(), region));
        }

        if (StringUtils.isNotBlank(region)) {
            LOGGER.trace("Setting DynamoDb client region [{}]", props.getRegion());
            clientBuilder.withRegion(region);
        }
        return clientBuilder.build();
    }
1136364
def query(options, collection_name, num_to_skip,
          num_to_return, query, field_selector, opts, check_keys=False):
    
    data = struct.pack("<I", options)
    data += bson._make_c_string(collection_name)
    data += struct.pack("<i", num_to_skip)
    data += struct.pack("<i", num_to_return)
    encoded = bson.BSON.encode(query, check_keys, opts)
    data += encoded
    max_bson_size = len(encoded)
    if field_selector is not None:
        encoded = bson.BSON.encode(field_selector, False, opts)
        data += encoded
        max_bson_size = max(len(encoded), max_bson_size)
    (request_id, query_message) = __pack_message(2004, data)
    return (request_id, query_message, max_bson_size)