Example #1
0
void
test_bson_null (void)
{
  bson *b;

  b = bson_new ();
  ok (bson_append_null (b, "null"),
      "bson_append_null() works");
  bson_finish (b);

  cmp_ok (bson_size (b), "==", 11, "BSON NULL element size check");
  ok (memcmp (bson_data (b),
	      "\013\000\000\000\012\156\165\154\154\000\000",
	      bson_size (b)) == 0,
      "BSON NULL element contents check");

  bson_free (b);

  b = bson_new ();
  ok (bson_append_null (b, NULL) == FALSE,
      "bson_append_null() should fail without a key name");
  ok (bson_append_null (NULL, "null") == FALSE,
      "bson_append_null() should fail without a BSON object");
  bson_finish (b);
  cmp_ok (bson_size (b), "==", 5,
	  "BSON object should be empty");

  ok (bson_append_null (b, "null") == FALSE,
      "Appending to a finished element should fail");

  bson_free (b);
}
void
test_bson_timestamp (void)
{
  bson *b;
  gint64 l = 9876543210;

  b = bson_new ();
  ok (bson_append_timestamp (b, "ts", l), "bson_append_timestamp() works");
  bson_finish (b);

  cmp_ok (bson_size (b), "==", 17, "BSON timestamp element size check");
  ok (memcmp (bson_data (b),
              "\021\000\000\000\021\164\163\000\352\026\260\114\002\000\000"
              "\000\000",
              bson_size (b)) == 0,
      "BSON timestamp element contents check");

  bson_free (b);

  b = bson_new ();
  ok (bson_append_timestamp (b, NULL, l) == FALSE,
      "bson_append_timestamp() with a NULL key should fail");
  ok (bson_append_timestamp (NULL, "ts", l) == FALSE,
      "bson_append_timestamp() without a BSON object should fail");
  bson_finish (b);
  cmp_ok (bson_size (b), "==", 5,
          "BSON object should be empty");

  ok (bson_append_timestamp (b, "ts", l) == FALSE,
      "Appending to a finished element should fail");

  bson_free (b);
}
Example #3
0
static void
test_bson_build_child_array (void)
{
   bson_t b;
   bson_t child;
   bson_t *b2;
   bson_t *child2;

   bson_init(&b);
   assert(bson_append_array_begin(&b, "foo", -1, &child));
   assert(bson_append_utf8(&child, "0", -1, "baz", -1));
   assert(bson_append_array_end(&b, &child));

   b2 = bson_new();
   child2 = bson_new();
   assert(bson_append_utf8(child2, "0", -1, "baz", -1));
   assert(bson_append_array(b2, "foo", -1, child2));
   bson_destroy(child2);

   assert(b.len == b2->len);
   assert_bson_equal(&b, b2);

   bson_destroy(&b);
   bson_destroy(b2);
}
void
test_func_mongo_sync_max_insert_size (void)
{
  mongo_sync_connection *conn;
  const bson *docs[10];
  bson *b1, *b2, *b3;

  b1 = bson_new ();
  bson_append_string (b1, "func_mongo_sync_max_insert_size", "works", -1);

  bson_finish (b1);
  b2 = bson_new ();
  bson_append_int32 (b2, "int32", 1984);
  bson_finish (b2);
  b3 = bson_new ();
  bson_finish (b3);

  conn = mongo_sync_connect (config.primary_host, config.primary_port,
			     FALSE);

  /*
   * cmd_insert_n()
   */
  mongo_sync_conn_set_max_insert_size (conn, bson_size (b1) +
				       bson_size (b3) + 1);

  docs[0] = b1;
  docs[1] = b2;
  docs[2] = b3;

  ok (mongo_sync_cmd_insert_n (conn, config.ns, 3, docs) == TRUE,
      "mongo_sync_cmd_insert_n() works with a small max_insert_size");

  mongo_sync_conn_set_max_insert_size (conn, 1);
  errno = 0;
  ok (mongo_sync_cmd_insert_n (conn, config.ns, 3, docs) == FALSE,
      "mongo_sync_cmd_insert_n() should fail if any one document is too big");
  cmp_ok (errno, "==", EMSGSIZE,
	  "errno is set to EMSGSIZE");

  /*
   * cmd_insert()
   */
  mongo_sync_conn_set_max_insert_size (conn, bson_size (b1) +
				       bson_size (b3) + 1);
  ok (mongo_sync_cmd_insert (conn, config.ns, b1, b2, b3, NULL) == TRUE,
      "mongo_sync_cmd_insert() works with a small max_insert_size");

  mongo_sync_conn_set_max_insert_size (conn, 1);
  errno = 0;
  ok (mongo_sync_cmd_insert (conn, config.ns, b1, b2, b3, NULL) == FALSE,
      "mongo_sync_cmd_insert() should fail if any one document is too big");
  cmp_ok (errno, "==", EMSGSIZE,
	  "errno is set to EMSGSIZE");

  mongo_sync_disconnect (conn);
  bson_free (b1);
  bson_free (b2);
  bson_free (b3);
}
void
test_mongo_sync_cmd_kill_cursors_net (void)
{
  mongo_packet *p;
  mongo_sync_connection *conn;
  bson *b;
  gint i;
  mongo_reply_packet_header rh;
  gint64 cid;

  begin_network_tests (3);

  conn = mongo_sync_connect (config.primary_host, config.primary_port, TRUE);
  mongo_sync_conn_set_auto_reconnect (conn, TRUE);

  b = bson_new ();
  for (i = 0; i < 40; i++)
    {
      bson_reset (b);
      bson_append_string (b, "test-name", __FILE__, -1);
      bson_append_int32 (b, "seq", i);
      bson_finish (b);

      mongo_sync_cmd_insert (conn, config.ns, b, NULL);
    }
  bson_free (b);

  b = bson_new ();
  bson_append_string (b, "test-name", __FILE__, -1);
  bson_finish (b);

  p = mongo_sync_cmd_query (conn, config.ns,
			    MONGO_WIRE_FLAG_QUERY_NO_CURSOR_TIMEOUT,
			    0, 2, b, NULL);
  mongo_wire_reply_packet_get_header (p, &rh);
  cid = rh.cursor_id;
  mongo_wire_packet_free (p);

  ok (mongo_sync_cmd_kill_cursors (conn, 1, cid) == TRUE,
      "mongo_sync_kill_cursors() works");

  p = mongo_sync_cmd_query (conn, config.ns,
			    MONGO_WIRE_FLAG_QUERY_NO_CURSOR_TIMEOUT,
			    0, 2, b, NULL);
  bson_free (b);
  mongo_wire_reply_packet_get_header (p, &rh);
  cid = rh.cursor_id;
  mongo_wire_packet_free (p);
  shutdown (conn->super.fd, SHUT_RDWR);
  sleep (3);

  ok (mongo_sync_cmd_kill_cursors (conn, 1, cid) == TRUE,
      "mongo_sync_cmd_kill_cursors() automatically reconnects");

  mongo_sync_disconnect (conn);

  test_mongo_sync_cmd_kill_cursors_net_secondary ();

  end_network_tests ();
}
Example #6
0
mrb_value mrb_mongo_collection_update(mrb_state *mrb, mrb_value self) {
  mrb_mongo_collection_data *data = DATA_PTR(self);
  mrb_value selector_hash, update_hash;
  mrb_bool upsert;
  bson_t *selector, *update;
  bson_error_t error;
  mongoc_update_flags_t flags;

  flags = MONGOC_UPDATE_MULTI_UPDATE;

  mrb_get_args(mrb, "HH|b", &selector_hash, &update_hash, &upsert);
  if (!mrb_hash_p(selector_hash)) {
    selector_hash = mrb_hash_new(mrb);
  }
  if (upsert) flags = flags | MONGOC_UPDATE_UPSERT;

  selector = bson_new();
  update = bson_new();
  mrb_hash_to_bson(mrb, selector_hash, selector);
  mrb_hash_to_bson(mrb, update_hash, update);

  if (!mongoc_collection_update(data->collection, flags, selector, update, NULL, &error)) {
    bson_destroy(selector);
    bson_destroy(update);
    mrb_raise(mrb, E_RUNTIME_ERROR, error.message);
  }

  bson_destroy(selector);
  bson_destroy(update);

  return mrb_nil_value();
}
void
test_bson_utc_datetime (void)
{
  bson *b;

  b = bson_new ();
  ok (bson_append_utc_datetime (b, "date", 1294860709000),
      "bson_append_utc_datetime() works");
  bson_finish (b);

  cmp_ok (bson_size (b), "==", 19, "BSON UTC datetime element size check");
  ok (memcmp (bson_data (b),
              "\023\000\000\000\011\144\141\164\145\000\210\154\266\173\055"
              "\001\000\000\000",
              bson_size (b)) == 0,
      "BSON UTC datetime element contents check");

  bson_free (b);

  b = bson_new ();
  ok (bson_append_utc_datetime (b, NULL, 1294860709000) == FALSE,
      "bson_append_utc_datetime() with a NULL key should fail");
  ok (bson_append_utc_datetime (NULL, "date", 1294860709000) == FALSE,
      "bson_append_utc_datetime() without a BSON object should fail");
  bson_finish (b);
  cmp_ok (bson_size (b), "==", 5,
          "BSON object should be empty");

  ok (bson_append_utc_datetime (b, "date", 1294860709000) == FALSE,
      "Appending to a finished element should fail");

  bson_free (b);
}
Example #8
0
static int
set_disq_comment_func(
        struct xuser_cnts_state *data,
        int user_id,
        const unsigned char *disq_comment)
{
    struct xuser_mongo_cnts_state *state = (struct xuser_mongo_cnts_state *) data;
    struct team_extra *extra = do_get_entry(state, user_id);
    if (!extra) return -1;
    if (!extra->disq_comment && !disq_comment) {
        return 0;
    }
    if (extra->disq_comment && !disq_comment) {
        ASSERT(ej_uuid_is_nonempty(extra->uuid));
        xfree(extra->disq_comment); extra->disq_comment = NULL;
        bson *doc = bson_new();
        bson_append_string(doc, "disq_comment", "", 0);
        bson_finish(doc);
        return do_update(state, extra, "$unset", doc);
    }
    if (extra->disq_comment && !strcmp(extra->disq_comment, disq_comment))
        return 0;
    xfree(extra->disq_comment);
    extra->disq_comment = xstrdup(disq_comment);
    if (ej_uuid_is_nonempty(extra->uuid)) {
        bson *doc = bson_new();
        bson_append_string(doc, "disq_comment", extra->disq_comment, strlen(extra->disq_comment));
        bson_finish(doc);
        return do_update(state, extra, NULL, doc);
    } else {
        return do_insert(state, extra);
    }
}
void
test_bson_document (void)
{
  bson *b, *e1, *e2;

  e1 = bson_new ();
  bson_append_int32 (e1, "i32", 1984);
  bson_append_string (e1, "str", "hello world", -1);
  bson_finish (e1);

  e2 = bson_new ();
  bson_append_string (e2, "foo", "bar", -1);
  ok (bson_append_document (e2, "subd", e1),
      "bson_append_document() works");
  bson_finish (e2);
  bson_free (e1);

  b = bson_new ();
  ok (bson_append_document (b, "doc", e2),
      "bson_append_document() works still");
  bson_finish (b);
  bson_free (e2);

  cmp_ok (bson_size (b), "==", 69, "BSON document element size check");
  ok (memcmp (bson_data (b),
	      "\105\000\000\000\003\144\157\143\000\073\000\000\000\002\146"
	      "\157\157\000\004\000\000\000\142\141\162\000\003\163\165\142"
	      "\144\000\043\000\000\000\020\151\063\062\000\300\007\000\000"
	      "\002\163\164\162\000\014\000\000\000\150\145\154\154\157\040"
	      "\167\157\162\154\144\000\000\000\000",
	      bson_size (b)) == 0,
      "BSON document element contents check");

  bson_free (b);

  e1 = bson_new ();
  bson_append_int32 (e1, "foo", 42);
  b = bson_new ();

  ok (bson_append_document (b, "doc", e1) == FALSE,
      "bson_append_document() with an unfinished document should fail");
  bson_finish (e1);
  ok (bson_append_document (b, NULL, e1) == FALSE,
      "bson_append_document() with a NULL key should fail");
  ok (bson_append_document (b, "doc", NULL) == FALSE,
      "bson_append_document() with a NULL document should fail");
  ok (bson_append_document (NULL, "doc", e1) == FALSE,
      "bson_append_document() without a BSON object should fail");
  bson_finish (b);

  cmp_ok (bson_size (b), "==", 5,
	  "BSON object should be empty");

  ok (bson_append_document (b, "doc", e1) == FALSE,
      "Appending to a finished element should fail");

  bson_free (e1);
  bson_free (b);
}
Example #10
0
void
test_bson_array (void)
{
  bson *b, *e1, *e2;

  e1 = bson_new ();
  bson_append_int32 (e1, "0", 1984);
  bson_append_string (e1, "1", "hello world", -1);
  bson_finish (e1);

  e2 = bson_new ();
  bson_append_string (e2, "0", "bar", -1);
  ok (bson_append_array (e2, "1", e1),
      "bson_append_array() works");
  bson_finish (e2);
  bson_free (e1);

  b = bson_new ();
  ok (bson_append_array (b, "0", e2),
      "bson_append_array() works still");
  bson_finish (b);
  bson_free (e2);

  cmp_ok (bson_size (b), "==", 58, "BSON array element size check");
  ok (memcmp (bson_data (b),
	      "\072\000\000\000\004\060\000\062\000\000\000\002\060\000\004"
	      "\000\000\000\142\141\162\000\004\061\000\037\000\000\000\020"
	      "\060\000\300\007\000\000\002\061\000\014\000\000\000\150\145"
	      "\154\154\157\040\167\157\162\154\144\000\000\000\000",
	      bson_size (b)) == 0,
      "BSON array element contents check");

  bson_free (b);

  e1 = bson_new ();
  bson_append_int32 (e1, "0", 1984);
  b = bson_new ();

  ok (bson_append_array (b, "array", e1) == FALSE,
      "bson_append_array() with an unfinished array should fail");
  bson_finish (e1);
  ok (bson_append_array (b, NULL, e1) == FALSE,
      "bson_append_array() with a NULL name should fail");
  ok (bson_append_array (b, "foo", NULL) == FALSE,
      "bson_append_array() with a NULL array should fail");
  ok (bson_append_array (NULL, "foo", e1) == FALSE,
      "bson_append_array() with a NULL BSON should fail");
  bson_finish (b);
  cmp_ok (bson_size (b), "==", 5,
	  "BSON object should be empty");

  ok (bson_append_array (b, "array", e1) == FALSE,
      "Appending to a finished element should fail");

  bson_free (e1);
  bson_free (b);
}
Example #11
0
int main(int argc, char *argv[]) {
	mongoc_client_t *client;
	mongoc_collection_t *collection;
	mongoc_cursor_t *cursor;
	const bson_t *doc;
	bson_t *query;
	char *str;

	mongoc_init();

	client = mongoc_client_new("mongodb://localhost:27017/");
	collection = mongoc_client_get_collection(client, "stockopedia",
			"instruments");

	query = bson_new();
	bson_t *fields = bson_new();
	BSON_APPEND_INT32(fields, "RIC", 1);

	cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 0, 0,
			query, fields, NULL);

	bson_iter_t iter;
	const bson_value_t *value;

	while (mongoc_cursor_next(cursor, &doc)) {
		str = bson_as_json(doc, NULL);
		printf("%s\n", str);

		if (bson_iter_init(&iter, doc)) {
			while (bson_iter_next(&iter)) {
				printf("Found a field named: %s\n", bson_iter_key(&iter));

				value = bson_iter_value(&iter);
				if (value->value_type == BSON_TYPE_UTF8) {
					printf("It's a UTF8 : '%s'\n", value->value.v_utf8.str);
				}
			}
		}

		//printf("Found element key : '%s'\n", bson_iter_key(&iter));

//		if (bson_iter_init(&iter, doc)) {
//
//		}

		bson_free(str);
	}

	//Now fetch quotes for each RIC

	bson_destroy(query);
	mongoc_cursor_destroy(cursor);
	mongoc_collection_destroy(collection);
	mongoc_client_destroy(client);

	return 0;
}
Example #12
0
/* {{{ proto void BulkWrite::update(array|object $query, array|object $newObj[, array $updateOptions = array()])
   Adds an update operation to bulk */
PHP_METHOD(BulkWrite, update)
{
	php_phongo_bulkwrite_t  *intern;
	zval                     *query;
	zval                     *newObj;
	zval                     *updateOptions = NULL;
	mongoc_update_flags_t     flags = MONGOC_UPDATE_NONE;
	bson_t                   *bquery;
	bson_t                   *bupdate;
	SUPPRESS_UNUSED_WARNING(return_value_ptr) SUPPRESS_UNUSED_WARNING(return_value) SUPPRESS_UNUSED_WARNING(return_value_used)


	intern = Z_BULKWRITE_OBJ_P(getThis());

	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "AA|a!", &query, &newObj, &updateOptions) == FAILURE) {
		return;
	}


	bquery = bson_new();
	bupdate = bson_new();

	phongo_zval_to_bson(query, PHONGO_BSON_NONE, bquery, NULL TSRMLS_CC);
	phongo_zval_to_bson(newObj, PHONGO_BSON_NONE, bupdate, NULL TSRMLS_CC);

	if (updateOptions) {
		flags |= php_array_fetch_bool(updateOptions, "multi") ?  MONGOC_UPDATE_MULTI_UPDATE : 0;
		flags |= php_array_fetch_bool(updateOptions, "upsert") ? MONGOC_UPDATE_UPSERT : 0;
	}

	if (flags & MONGOC_UPDATE_MULTI_UPDATE) {
		mongoc_bulk_operation_update(intern->bulk, bquery, bupdate, !!(flags & MONGOC_UPDATE_UPSERT));
	} else {
		bson_iter_t iter;
		zend_bool   replaced = 0;

		if (bson_iter_init(&iter, bupdate)) {
			while (bson_iter_next (&iter)) {
				if (!strchr (bson_iter_key (&iter), '$')) {
					mongoc_bulk_operation_replace_one(intern->bulk, bquery, bupdate, !!(flags & MONGOC_UPDATE_UPSERT));
					replaced = 1;
					break;
				}
			}
		}

		if (!replaced) {
			mongoc_bulk_operation_update_one(intern->bulk, bquery, bupdate, !!(flags & MONGOC_UPDATE_UPSERT));
		}
	}

	intern->num_ops++;

	bson_clear(&bquery);
	bson_clear(&bupdate);
}
Example #13
0
static void
test_bson_as_json (void)
{
   bson_oid_t oid;
   bson_decimal128_t decimal128;
   bson_t *b;
   bson_t *b2;
   char *str;
   size_t len;
   int i;

   decimal128.high = 0x3040000000000000ULL;
   decimal128.low  = 0x000000000000000B;
   bson_oid_init_from_string(&oid, "123412341234abcdabcdabcd");

   b = bson_new();
   assert(bson_append_utf8(b, "utf8", -1, "bar", -1));
   assert(bson_append_int32(b, "int32", -1, 1234));
   assert(bson_append_int64(b, "int64", -1, 4321));
   assert(bson_append_double(b, "double", -1, 123.4));
   assert(bson_append_undefined(b, "undefined", -1));
   assert(bson_append_null(b, "null", -1));
   assert(bson_append_oid(b, "oid", -1, &oid));
   assert(bson_append_bool(b, "true", -1, true));
   assert(bson_append_bool(b, "false", -1, false));
   assert(bson_append_time_t(b, "date", -1, time(NULL)));
   assert(bson_append_timestamp(b, "timestamp", -1, (uint32_t)time(NULL), 1234));
   assert(bson_append_regex(b, "regex", -1, "^abcd", "xi"));
   assert(bson_append_dbpointer(b, "dbpointer", -1, "mycollection", &oid));
   assert(bson_append_minkey(b, "minkey", -1));
   assert(bson_append_maxkey(b, "maxkey", -1));
   assert(bson_append_symbol(b, "symbol", -1, "var a = {};", -1));
   assert(bson_append_decimal128(b, "decimal128", -1, &decimal128));

   b2 = bson_new();
   assert(bson_append_int32(b2, "0", -1, 60));
   assert(bson_append_document(b, "document", -1, b2));
   assert(bson_append_array(b, "array", -1, b2));

   {
      const uint8_t binary[] = { 0, 1, 2, 3, 4 };
      assert(bson_append_binary(b, "binary", -1, BSON_SUBTYPE_BINARY,
                                binary, sizeof binary));
   }

   for (i = 0; i < 1000; i++) {
      str = bson_as_json(b, &len);
      bson_free(str);
   }

   bson_destroy(b);
   bson_destroy(b2);
}
void
test_bson_string (void)
{
  bson *b;

  /* Test #1: A single string element, with default size. */
  b = bson_new ();
  ok (bson_append_string (b, "hello", "world", -1),
      "bson_append_string() works");
  bson_finish (b);
  cmp_ok (bson_size (b), "==", 22, "BSON string element size check");
  ok (memcmp (bson_data (b),
              "\026\000\000\000\002\150\145\154\154\157\000\006\000\000\000"
              "\167\157\162\154\144\000\000",
              bson_size (b)) == 0,
      "BSON string element contents check");
  bson_free (b);

  /* Test #2: A single string element, with explicit length. */
  b = bson_new ();
  ok (bson_append_string (b, "goodbye",
                          "cruel world, this garbage is gone.",
                          strlen ("cruel world")),
      "bson_append_string() with explicit length works");
  bson_finish (b);

  cmp_ok (bson_size (b), "==", 30, "BSON string element size check, #2");
  ok (memcmp (bson_data (b),
              "\036\000\000\000\002\147\157\157\144\142\171\145\000\014\000"
              "\000\000\143\162\165\145\154\040\167\157\162\154\144\000\000",
              bson_size (b)) == 0,
      "BSON string element contents check, #2");
  bson_free (b);

  /* Test #3: Negative test, passing invalid arguments. */
  b = bson_new ();
  ok (bson_append_string (b, "hello", "world", -42) == FALSE,
      "bson_append_string() should fail with invalid length");
  ok (bson_append_string (b, "hello", NULL, -1) == FALSE,
      "bson_append_string() should fail without a string");
  ok (bson_append_string (b, NULL, "world", -1) == FALSE,
      "bson_append_string() should fail without a key name");
  ok (bson_append_string (NULL, "hello", "world", -1) == FALSE,
      "bson_append_string() should fail without a BSON object");
  bson_finish (b);
  cmp_ok (bson_size (b), "==", 5,
          "BSON object should be empty");

  ok (bson_append_string (b, "hello", "world", -1) == FALSE,
      "Appending to a finished element should fail");

  bson_free (b);
}
Example #15
0
int database_find_blockchain_transaction(struct database* db, unsigned char* hash, size_t max_height, struct transaction** tx, size_t* height)
{
    mongoc_collection_t* collection = mongoc_client_get_collection(db->client, database_name(db), "transactions");

    // Build a query doc
    bson_t* query = bson_new();

    // Set the hash
    BSON_APPEND_BINARY(query, "hash", BSON_SUBTYPE_BINARY, (uint8_t*)hash, 32);

    // Force the height to be valid (on the main chain)
    bson_t* height_doc = bson_new();
    BSON_APPEND_DOCUMENT_BEGIN(query, "height", height_doc);
    BSON_APPEND_INT32(height_doc, "$lte", (int)max_height);
    BSON_APPEND_INT32(height_doc, "$gte", 0);
    bson_append_document_end(query, height_doc);

    // Perform find
    mongoc_cursor_t* cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);

    bson_error_t error;
    if(cursor == NULL || mongoc_cursor_error(cursor, &error)) {
        printf("MongoDB error: %s\n", (cursor == NULL) ? "NULL cursor" : error.message);
        return -1;
    }

    bson_t const* doc;
    int found = 0;
    while(mongoc_cursor_next(cursor, &doc) != 0) {
        if(height != NULL) {
            bson_iter_t iter;
            if(!bson_iter_init_find(&iter, doc, "height") || !BSON_ITER_HOLDS_INT32(&iter)) {
                printf("MongoDB error: tx doesn't have height!\n");
                return -1;
            }
            *height = (size_t)bson_iter_int32(&iter);
        }

        if(tx != NULL) {
            *tx = transaction_from_bson(doc);
        }

        found = 1;
        break;
    }

    mongoc_cursor_destroy(cursor);
    bson_destroy(height_doc);
    bson_destroy(query);
    mongoc_collection_destroy(collection);
    return found;
}
Example #16
0
// Find the spend of a specified output_reference within a given blockheight range (main chain only)
// if found, load tx and the input that spends it
int database_find_blockchain_spend(struct database* db, struct transaction_output_reference* output_reference, size_t start_height, size_t max_height, struct transaction** tx)
{
    mongoc_collection_t* collection = mongoc_client_get_collection(db->client, database_name(db), "transactions");

    // Build a query doc
    bson_t* query = bson_new();

    // Build a query that tries to find where this output_reference is spent
    unsigned char hash[32];
    transaction_output_reference_hash(output_reference, hash);

    bson_t* output_reference_doc = bson_new();
    BSON_APPEND_DOCUMENT_BEGIN(query, "inputs.output_reference", output_reference_doc);
    BSON_APPEND_BINARY(output_reference_doc, "hash", BSON_SUBTYPE_BINARY, (uint8_t*)hash, 32);
    BSON_APPEND_INT32(output_reference_doc, "index", transaction_output_reference_index(output_reference));
    bson_append_document_end(query, output_reference_doc);

    // Force the height to be valid
    bson_t* height_doc = bson_new();
    BSON_APPEND_DOCUMENT_BEGIN(query, "height", height_doc);
    BSON_APPEND_INT32(height_doc, "$lte", (int)max_height);
    BSON_APPEND_INT32(height_doc, "$gte", start_height);
    bson_append_document_end(query, height_doc);

    // Perform find
    mongoc_cursor_t* cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);

    bson_error_t error;
    if(cursor == NULL || mongoc_cursor_error(cursor, &error)) {
        printf("MongoDB error: %s\n", (cursor == NULL) ? "NULL cursor" : error.message);
        return -1;
    }

    bson_t const* doc;
    int found = 0;
    while(mongoc_cursor_next(cursor, &doc) != 0) {
        if(tx != NULL) {
            *tx = transaction_from_bson(doc);
        }

        found = 1;
        break;
    }

    mongoc_cursor_destroy(cursor);
    bson_destroy(height_doc);
    bson_destroy(output_reference_doc);
    bson_destroy(query);
    mongoc_collection_destroy(collection);
    return found;
}
Example #17
0
static void
test_bson_iter_mixed (void)
{
   bson_iter_t iter;
   bson_decimal128_t iter_value;
   bson_decimal128_t value;
   bson_t *b;
   bson_t *b2;

   b = bson_new();
   b2 = bson_new();

   value.high = 0;
   value.low = 1;

   assert(bson_append_utf8(b2, "foo", -1, "bar", -1));
   assert(bson_append_code(b, "0", -1, "var a = {};"));
   assert(bson_append_code_with_scope(b, "1", -1, "var b = {};", b2));
   assert(bson_append_int32(b, "2", -1, 1234));
   assert(bson_append_int64(b, "3", -1, 4567));
   assert(bson_append_time_t(b, "4", -1, 123456));
   assert(bson_append_decimal128(b, "5", -1, &value));
   assert(bson_iter_init(&iter, b));
   assert(bson_iter_next(&iter));
   assert(BSON_ITER_HOLDS_CODE(&iter));
   assert(bson_iter_next(&iter));
   assert(BSON_ITER_HOLDS_CODEWSCOPE(&iter));
   assert(bson_iter_next(&iter));
   assert(BSON_ITER_HOLDS_INT32(&iter));
   assert(bson_iter_next(&iter));
   assert(BSON_ITER_HOLDS_INT64(&iter));
   assert(bson_iter_next(&iter));
   assert(BSON_ITER_HOLDS_DATE_TIME(&iter));
   assert(bson_iter_next(&iter));
   assert(BSON_ITER_HOLDS_DECIMAL128(&iter));
   assert(!bson_iter_next(&iter));
   assert(bson_iter_init_find(&iter, b, "3"));
   assert(!strcmp(bson_iter_key(&iter), "3"));
   assert(bson_iter_int64(&iter) == 4567);
   assert(bson_iter_next(&iter));
   assert(BSON_ITER_HOLDS_DATE_TIME(&iter));
   assert(bson_iter_time_t(&iter) == 123456);
   assert(bson_iter_date_time(&iter) == 123456000);
   assert(bson_iter_next(&iter));
   /* This test uses memcmp because libbson lacks decimal128 comparison. */
   bson_iter_decimal128(&iter, &iter_value);
   assert(memcmp(&iter_value, &value, sizeof(value)) == 0);
   assert(!bson_iter_next(&iter));
   bson_destroy(b);
   bson_destroy(b2);
}
Example #18
0
void SettingsOutput::SetSubbasinIDs()
{
	bson_t *b = bson_new();
	bson_t *child = bson_new();
	bson_t *child2 = bson_new();
	bson_t *child3 = bson_new();
	BSON_APPEND_DOCUMENT_BEGIN(b, "$query", child);
	BSON_APPEND_DOCUMENT_BEGIN(child, PARAM_FLD_NAME, child2);
	BSON_APPEND_ARRAY_BEGIN(child2, "$in", child3);
	BSON_APPEND_UTF8(child3,PARAM_FLD_NAME, VAR_OUTLETID);
	BSON_APPEND_UTF8(child3,PARAM_FLD_NAME, VAR_SUBBSNID_NUM);
	bson_append_array_end(child2, child3);
	bson_append_document_end(child, child2);
	bson_append_document_end(b, child);
	//printf("%s\n",bson_as_json(b,NULL));

	mongoc_cursor_t *cursor;
	const bson_t *bsonTable;
	mongoc_collection_t *collection;

	collection = mongoc_client_get_collection(m_conn, m_dbName.c_str(), DB_TAB_PARAMETERS);
	cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 0, 0, b, NULL, NULL);

	bson_iter_t iter;
	while (mongoc_cursor_more(cursor) && mongoc_cursor_next(cursor, &bsonTable))
	{
		string nameTmp = "";
		int numTmp = -1;
		if (bson_iter_init_find(&iter, bsonTable, PARAM_FLD_NAME))
			nameTmp = GetStringFromBSONITER(&iter);
		if (bson_iter_init_find(&iter, bsonTable, PARAM_FLD_VALUE))
			numTmp = GetIntFromBSONITER(&iter);
		if(!StringMatch(nameTmp, "") && numTmp != -1)
		{
			if(StringMatch(nameTmp, VAR_OUTLETID))
				m_outletID = GetIntFromBSONITER(&iter);
			else if (StringMatch(nameTmp, VAR_SUBBSNID_NUM))
				m_nSubbasins = GetIntFromBSONITER(&iter);
		}
		else
			throw ModelException("SettingOutput","SetSubbasinIDs","No valid values found in MongoDB!");
	}
	bson_destroy(child);
	bson_destroy(child2);
	bson_destroy(child3);
	bson_destroy(b);
	mongoc_collection_destroy(collection);
	mongoc_cursor_destroy(cursor);
	return;
}
Example #19
0
static void
test_bson_append_document (void)
{
   bson_t *b;
   bson_t *b2;

   b = bson_new();
   b2 = bson_new();
   assert(bson_append_document(b, "document", -1, b2));
   bson_destroy(b2);
   b2 = get_bson("test21.bson");
   assert_bson_equal(b, b2);
   bson_destroy(b);
   bson_destroy(b2);
}
void
test_bson_binary (void)
{
  bson *b;

  b = bson_new ();
  ok (bson_append_binary (b, "binary0", BSON_BINARY_SUBTYPE_GENERIC,
                          (guint8 *)"foo\0bar", 7),
      "bson_append_binary(), type 0 works");
  ok (bson_append_binary (b, "binary2", BSON_BINARY_SUBTYPE_BINARY,
                          (guint8 *)"\0\0\0\7foo\0bar", 11),
      "bson_append_binary(), type 2 works");
  bson_finish (b);

  cmp_ok (bson_size (b), "==", 51, "BSON binary element size check");
  ok (memcmp (bson_data (b),
              "\063\000\000\000\005\142\151\156\141\162\171\060\000\007\000"
              "\000\000\000\146\157\157\000\142\141\162\005\142\151\156\141"
              "\162\171\062\000\013\000\000\000\002\000\000\000\007\146\157"
              "\157\000\142\141\162\000",
              bson_size (b)) == 0,
      "BSON binary element contents check");

  bson_free (b);

  b = bson_new ();
  ok (bson_append_binary (b, NULL, BSON_BINARY_SUBTYPE_GENERIC,
                          (guint8 *)"foo\0bar", 7) == FALSE,
      "bson_append_binary() without a key name should fail");
  ok (bson_append_binary (b, "binary1", BSON_BINARY_SUBTYPE_GENERIC,
                          NULL, 10) == FALSE,
      "bson_append_binary () without binary data should fail");
  ok (bson_append_binary (b, "binary3", BSON_BINARY_SUBTYPE_GENERIC,
                          (guint8 *)"foo\0bar", -1) == FALSE,
      "bson_append_binary () with an invalid length should fail");
  ok (bson_append_binary (NULL, "binary1", BSON_BINARY_SUBTYPE_GENERIC,
                          (guint8 *)"foo\0bar", 7) == FALSE,
      "bson_append_binary () without a BSON object should fail");
  bson_finish (b);
  cmp_ok (bson_size (b), "==", 5,
          "BSON object should be empty");

  ok (bson_append_binary (b, "binary", BSON_BINARY_SUBTYPE_GENERIC,
                          (guint8 *)"foo\0bar", 7) == FALSE,
      "Appending to a finished element should fail");

  bson_free (b);
}
static bool
_mongoc_cursor_cursorid_refresh_from_command (mongoc_cursor_t *cursor,
                                              const bson_t    *command)
{
   mongoc_cursor_cursorid_t *cid;

   ENTRY;

   cid = (mongoc_cursor_cursorid_t *)cursor->iface_data;
   BSON_ASSERT (cid);

   if (cid->array) {
      bson_destroy (cid->array);
   }

   cid->array = bson_new ();

   /* server replies to find / aggregate with {cursor: {id: N, firstBatch: []}},
    * to getMore command with {cursor: {id: N, nextBatch: []}}. */
   if (_mongoc_cursor_run_command (cursor, command, cid->array) &&
       _mongoc_cursor_cursorid_start_batch (cursor)) {

      RETURN (true);
   } else {
      if (!cursor->error.domain) {
         bson_set_error (&cursor->error,
                         MONGOC_ERROR_PROTOCOL,
                         MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
                         "Invalid reply to %s command.",
                         _mongoc_get_command_name (command));
      }

      RETURN (false);
   }
}
Example #22
0
/* Check a correct CONNECT message */
static gboolean
sim_parser_connect_test1 (void)
{
  bson_t *bson_connect = bson_new ();
  bson_t child;
  uint8_t uuid[]={0x07,0x92,0xd6,0x72,0xf4,0xce,0x11,0xe4,0x9d,0xe2,0x00,0x0c,0x29,0xd9,0x46,0xde};
  SimParser *parser = NULL;
  SimCommand *cmd = NULL;
  gboolean result = FALSE;
  bson_append_document_begin (bson_connect,"connect", -1, &child);
  BSON_APPEND_INT32 (&child, "id", 10);
  BSON_APPEND_INT32 (&child, "type", SIM_SESSION_TYPE_WEB);
  BSON_APPEND_UTF8 (&child, "version", "5.0.1");
  if (bson_append_binary (&child, "sensor_id", -1, BSON_SUBTYPE_UUID, uuid, 16) == FALSE)
    return FALSE;
  bson_append_document_end (bson_connect, &child);
  /* Check */
  bson_iter_t iter;
  bson_iter_init (&iter, bson_connect);
  do{
    if ((parser = sim_parser_new()) == NULL)
    { 
      result = FALSE;
      break;
    }
    if ((cmd = sim_parser_bson (parser, bson_get_data (bson_connect), bson_connect->len)) == NULL)
    {
      result = FALSE;
      break;
    }
    if (cmd->type !=  SIM_COMMAND_TYPE_CONNECT)
    {
      result = FALSE;
      break;
    }
    if (cmd->data.connect.sensor_ver->major != 5 || cmd->data.connect.sensor_ver->minor != 0 || cmd->data.connect.sensor_ver->micro != 1)
    {
      result = FALSE;
      break;
    }
    if (cmd->data.connect.sensor_id == NULL)
    {
      result = FALSE;
      break;
    }
    /* Check uuid */
    SimUuid * uuidbin =  sim_uuid_new_from_bin (uuid);
    gboolean test =  sim_uuid_equal (uuidbin, cmd->data.connect.sensor_id);
    g_object_unref (uuidbin);
    if (!test)
    {
      result = FALSE;
      break;
    }
    result = TRUE;
  } while (0);
  bson_destroy (bson_connect);
  g_object_unref (parser);
  return result;
}
Example #23
0
int
main (int   argc,
      char *argv[])
{
    mongoc_client_t *client;
    mongoc_collection_t *collection;
    mongoc_cursor_t *cursor;
    const bson_t *doc;
    bson_t *query;
    char *str;

    mongoc_init ();

    client = mongoc_client_new ("mongodb://localhost:3001/");
    collection = mongoc_client_get_collection (client, "meteor", "sensors");
    query = bson_new ();
    cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);

    while (mongoc_cursor_next (cursor, &doc)) {
        str = bson_as_json (doc, NULL);
        printf ("%s\n", str);
        bson_free (str);
    }

    bson_destroy (query);
    mongoc_cursor_destroy (cursor);
    mongoc_collection_destroy (collection);
    mongoc_client_destroy (client);

    return 0;
}
Example #24
0
void
test_mongo_sync_cmd_custom (void)
{
  mongo_sync_connection *c;
  bson *cmd;

  c = test_make_fake_sync_conn (-1, FALSE);
  cmd = bson_new ();
  bson_append_int32 (cmd, "getnonce", 1);
  bson_finish (cmd);

  ok (mongo_sync_cmd_custom (NULL, "test", cmd) == NULL,
      "mongo_sync_cmd_custom() fails with a NULL connection");
  ok (mongo_sync_cmd_custom (c, NULL, cmd) == NULL,
      "mongo_sync_cmd_custom() fails with a NULL namespace");

  ok (mongo_sync_cmd_custom (c, "test", cmd) == NULL,
      "mongo_sync_cmd_custom() fails with a bogus FD");
  mongo_sync_conn_set_slaveok (c, TRUE);
  ok (mongo_sync_cmd_custom (c, "test", cmd) == NULL,
      "mongo_sync_cmd_custom() fails with a bogus FD");

  bson_free (cmd);
  mongo_sync_disconnect (c);

  test_mongo_sync_cmd_custom_net ();
}
Example #25
0
static void saveAlarmLog(mongoc_collection_t *coll,char* se_id,int code,char * tel,char * msg,char* userId,char * device_name,char* name,char * de_id){
     bson_t *sdoc = bson_new ();
     bson_oid_t a_oid;
     bson_oid_init (&a_oid, NULL);
     BSON_APPEND_OID (sdoc, "_id", &a_oid);
     //BSON_APPEND_OID (sdoc, "device_id", de_oid);
     //BSON_APPEND_UTF8 (sdoc, "name", name);
     //BSON_APPEND_INT32 (sdoc, "sensorType", sensorType);
     BSON_APPEND_INT32 (sdoc, "code", code);
     BSON_APPEND_UTF8 (sdoc, "mobile", tel);
     BSON_APPEND_UTF8 (sdoc, "sendmsg", msg);
     BSON_APPEND_UTF8 (sdoc, "user_id", userId);
     BSON_APPEND_UTF8 (sdoc, "se_id", se_id);
     BSON_APPEND_UTF8 (sdoc, "de_id", de_id);
     BSON_APPEND_UTF8 (sdoc, "device_name", device_name);
     BSON_APPEND_UTF8 (sdoc, "sensor_name", name);
     time_t timep;
     time(&timep);
     BSON_APPEND_DOUBLE (sdoc, "time", timep);
     bson_error_t serror;
     if (!mongoc_collection_insert (coll, MONGOC_INSERT_NONE, sdoc, NULL, &serror)) {
        fprintf (stderr, "%s\n", serror.message);
     }
     bson_destroy (sdoc);
}
void HHVM_METHOD(MongoDBDriverReadPreference, _setReadPreferenceTags, const Array &tagSets)
{
	MongoDBDriverReadPreferenceData* data = Native::data<MongoDBDriverReadPreferenceData>(this_);
	bson_t *bson;

	/* Check validity */
	if (!hippo_mongo_driver_readpreference_are_valid(tagSets)) {
		throw MongoDriver::Utils::throwInvalidArgumentException("tagSets must be an array of zero or more documents");
	}

	/* Validate that readPreferenceTags are not used with PRIMARY readPreference */
	if (mongoc_read_prefs_get_mode(data->m_read_preference) == MONGOC_READ_PRIMARY) {
		throw MongoDriver::Utils::throwInvalidArgumentException("tagSets may not be used with primary mode");
	}

	/* Convert argument */
	VariantToBsonConverter converter(tagSets, HIPPO_BSON_NO_FLAGS);
	bson = bson_new();
	converter.convert(bson);

	/* Set and check errors */
	mongoc_read_prefs_set_tags(data->m_read_preference, bson);
	bson_destroy(bson);
	if (!mongoc_read_prefs_is_valid(data->m_read_preference)) {
		/* Throw exception */
		throw MongoDriver::Utils::throwInvalidArgumentException("Read preference is not valid");
	}
}
Example #27
0
static int
set_clar_status_func(
        struct xuser_cnts_state *data,
        int user_id,
        int clar_id,
        const ej_uuid_t *p_clar_uuid)
{
    struct xuser_mongo_cnts_state *state = (struct xuser_mongo_cnts_state *) data;
    struct team_extra *extra = do_get_entry(state, user_id);
    if (!extra) return -1;
    if (!p_clar_uuid) return -1;
    int r = team_extra_add_clar_uuid(extra, p_clar_uuid);
    if (r <= 0) return r;
    if (ej_uuid_is_nonempty(extra->uuid)) {
        bson *arr = ej_bson_unparse_array_uuid(extra->clar_uuids, extra->clar_uuids_size);
        bson *doc = bson_new();
        bson_append_array(doc, "clar_uuids", arr);
        bson_free(arr); arr = NULL;
        bson_finish(doc);
        return do_update(state, extra, NULL, doc);
    } else {
        return do_insert(state, extra);
    }
    return -1;
}
Example #28
0
void
test_bson_find (void)
{
  bson *b;
  bson_cursor *c;

  ok (bson_find (NULL, NULL) == NULL,
      "bson_find() with NULL parameters should fail");
  ok (bson_find (NULL, "key") == NULL,
      "bson_find() with a NULL BSON object should fail");
  b = bson_new ();
  ok (bson_find (b, "key") == NULL,
      "bson_find() with an unfinished BSON object should fail");
  bson_free (b);

  b = test_bson_generate_full ();
  ok (bson_find (b, NULL) == FALSE,
      "bson_find() with a NULL key should fail");
  ok (bson_find (b, "__invalid__") == FALSE,
      "bson_find() with a non-existent key should fail");
  ok ((c = bson_find (b, "alert")) != NULL,
      "bson_find() works");

  bson_cursor_free (c);
  bson_free (b);
}
Example #29
0
mrb_value mrb_mongo_collection_insert(mrb_state *mrb, mrb_value self) {
  mrb_mongo_collection_data *data = DATA_PTR(self);
  mrb_value record_hash, inserted_hash;
  bson_t *doc;
  bson_oid_t oid;
  bson_error_t error;

  mrb_get_args(mrb, "H", &record_hash);

  doc = bson_new();
  mrb_hash_to_bson(mrb, record_hash, doc);

  //add id if not supplied
  if (!bson_has_field(doc, "_id")) {
    bson_oid_init(&oid, NULL);
    bson_append_oid(doc, "_id", -1, &oid);
  }

  if (!mongoc_collection_insert(data->collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
    bson_destroy(doc);
    mrb_raise(mrb, E_RUNTIME_ERROR, error.message);
  }

  inserted_hash = mrb_hash_new(mrb);
  bson_to_mrb_hash(mrb, doc, inserted_hash);
  bson_destroy(doc);

  return inserted_hash;
}
void
test_mongo_sync_cmd_kill_cursors_net_secondary (void)
{
  mongo_packet *p;
  mongo_sync_connection *conn;
  bson *b;

  mongo_reply_packet_header rh;
  gint64 cid;

  skip (!config.secondary_host, 1,
	"Secondary server not configured");

  conn = mongo_sync_connect (config.secondary_host, config.secondary_port,
			     TRUE);
  b = bson_new ();
  bson_append_string (b, "test-name", __FILE__, -1);
  bson_finish (b);

  p = mongo_sync_cmd_query (conn, config.ns,
			    MONGO_WIRE_FLAG_QUERY_NO_CURSOR_TIMEOUT,
			    0, 2, b, NULL);
  bson_free (b);
  mongo_wire_reply_packet_get_header (p, &rh);
  cid = rh.cursor_id;
  mongo_wire_packet_free (p);

  ok (mongo_sync_cmd_kill_cursors (conn, 1, cid) == TRUE,
      "mongo_sync_cmd_kill_cursors() works on secondary too");

  mongo_sync_disconnect (conn);

  endskip;
}