Beispiel #1
0
static void
_mongoc_populate_query_error (const bson_t *doc,
                              int32_t       error_api_version,
                              bson_error_t *error)
{
   mongoc_error_domain_t domain =
      error_api_version >= MONGOC_ERROR_API_VERSION_2
      ? MONGOC_ERROR_SERVER
      : MONGOC_ERROR_QUERY;
   uint32_t code = MONGOC_ERROR_QUERY_FAILURE;
   bson_iter_t iter;
   const char *msg = "Unknown query failure";

   ENTRY;

   BSON_ASSERT (doc);

   if (bson_iter_init_find (&iter, doc, "code") &&
       BSON_ITER_HOLDS_INT32 (&iter)) {
      code = (uint32_t) bson_iter_int32 (&iter);
   }

   if (bson_iter_init_find (&iter, doc, "$err") &&
       BSON_ITER_HOLDS_UTF8 (&iter)) {
      msg = bson_iter_utf8 (&iter, NULL);
   }

   bson_set_error (error, domain, code, "%s", msg);

   EXIT;
}
static void
test_rtt_calculation_cb (bson_t *test)
{
   mongoc_server_description_t *description;
   bson_iter_t iter;

   BSON_ASSERT (test);

   description = (mongoc_server_description_t *)bson_malloc0(sizeof *description);
   mongoc_server_description_init(description, "localhost:27017", 1);

   /* parse RTT into server description */
   assert(bson_iter_init_find(&iter, test, "avg_rtt_ms"));
   description->round_trip_time_msec = bson_iter_int64(&iter);

   /* update server description with new rtt */
   assert(bson_iter_init_find(&iter, test, "new_rtt_ms"));
   mongoc_server_description_update_rtt(description, bson_iter_int64(&iter));

   /* ensure new RTT was calculated correctly */
   assert(bson_iter_init_find(&iter, test, "new_avg_rtt"));
   assert(description->round_trip_time_msec == bson_iter_int64(&iter));

   mongoc_server_description_destroy(description);
}
Beispiel #3
0
static void
test_bson_iter_overwrite_decimal128 (void)
{
   bson_iter_t iter;
   bson_t b;
   bson_decimal128_t value;
   bson_decimal128_t new_value;
   bson_decimal128_t iter_value;

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

   new_value.high = 0;
   new_value.low = 2;

   bson_init(&b);
   assert(bson_append_decimal128(&b, "key", -1, &value));
   assert(bson_iter_init_find(&iter, &b, "key"));
   assert(BSON_ITER_HOLDS_DECIMAL128(&iter));
   bson_iter_overwrite_decimal128(&iter, &new_value);
   assert(bson_iter_init_find(&iter, &b, "key"));
   assert(BSON_ITER_HOLDS_DECIMAL128(&iter));
   assert(bson_iter_decimal128(&iter, &iter_value));
   assert(memcmp(&iter_value, &new_value, sizeof(new_value)) == 0);
   bson_destroy(&b);
}
static void
_mongoc_cursor_populate_error (mongoc_cursor_t *cursor,
                               const bson_t    *doc,
                               bson_error_t    *error)
{
   bson_uint32_t code = MONGOC_ERROR_QUERY_FAILURE;
   bson_iter_t iter;
   const char *msg = "Unknown query failure";

   BSON_ASSERT (cursor);
   BSON_ASSERT (doc);
   BSON_ASSERT (error);

   if (bson_iter_init_find (&iter, doc, "code") &&
       BSON_ITER_HOLDS_INT32 (&iter)) {
      code = bson_iter_int32 (&iter);
   }

   if (bson_iter_init_find (&iter, doc, "$err") &&
       BSON_ITER_HOLDS_UTF8 (&iter)) {
      msg = bson_iter_utf8 (&iter, NULL);
   }

   if (cursor->is_command &&
       bson_iter_init_find (&iter, doc, "errmsg") &&
       BSON_ITER_HOLDS_UTF8 (&iter)) {
      msg = bson_iter_utf8 (&iter, NULL);
   }

   bson_set_error(error, MONGOC_ERROR_QUERY, code, "%s", msg);
}
Beispiel #5
0
static void
test_bson_copy_to_excluding (void)
{
   bson_iter_t iter;
   bson_bool_t r;
   bson_t b;
   bson_t c;
   int i;

   bson_init(&b);
   bson_append_int32(&b, "a", 1, 1);
   bson_append_int32(&b, "b", 1, 2);

   bson_copy_to_excluding(&b, &c, "b", NULL);
   r = bson_iter_init_find(&iter, &c, "a");
   assert(r);
   r = bson_iter_init_find(&iter, &c, "b");
   assert(!r);

   i = bson_count_keys(&b);
   assert_cmpint(i, ==, 2);

   i = bson_count_keys(&c);
   assert_cmpint(i, ==, 1);

   bson_destroy(&b);
   bson_destroy(&c);
}
static void
test_write_concern_basic (void)
{
    mongoc_write_concern_t *write_concern;
    const bson_t *b;
    bson_iter_t iter;

    write_concern = mongoc_write_concern_new();

    /*
     * Test defaults.
     */
    assert(write_concern);
    assert(!mongoc_write_concern_get_fsync(write_concern));
    assert(!mongoc_write_concern_get_journal(write_concern));
    assert(mongoc_write_concern_get_w(write_concern) == MONGOC_WRITE_CONCERN_W_DEFAULT);
    assert(!mongoc_write_concern_get_wtimeout(write_concern));
    assert(!mongoc_write_concern_get_wmajority(write_concern));

    mongoc_write_concern_set_fsync(write_concern, TRUE);
    assert(mongoc_write_concern_get_fsync(write_concern));
    mongoc_write_concern_set_fsync(write_concern, FALSE);
    assert(!mongoc_write_concern_get_fsync(write_concern));

    mongoc_write_concern_set_journal(write_concern, TRUE);
    assert(mongoc_write_concern_get_journal(write_concern));
    mongoc_write_concern_set_journal(write_concern, FALSE);
    assert(!mongoc_write_concern_get_journal(write_concern));

    /*
     * Test changes to w.
     */
    mongoc_write_concern_set_w(write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY);
    assert(mongoc_write_concern_get_wmajority(write_concern));
    mongoc_write_concern_set_w(write_concern, MONGOC_WRITE_CONCERN_W_DEFAULT);
    assert(!mongoc_write_concern_get_wmajority(write_concern));
    mongoc_write_concern_set_wmajority(write_concern, 1000);
    assert(mongoc_write_concern_get_wmajority(write_concern));
    assert(mongoc_write_concern_get_wtimeout(write_concern) == 1000);
    mongoc_write_concern_set_wtimeout(write_concern, 0);
    assert(!mongoc_write_concern_get_wtimeout(write_concern));
    mongoc_write_concern_set_w(write_concern, MONGOC_WRITE_CONCERN_W_DEFAULT);
    assert(mongoc_write_concern_get_w(write_concern) == MONGOC_WRITE_CONCERN_W_DEFAULT);
    mongoc_write_concern_set_w(write_concern, 3);
    assert(mongoc_write_concern_get_w(write_concern) == 3);

    /*
     * Check generated bson.
     */
    mongoc_write_concern_set_fsync(write_concern, TRUE);
    mongoc_write_concern_set_journal(write_concern, TRUE);
    b = _mongoc_write_concern_freeze(write_concern);
    assert(bson_iter_init_find(&iter, b, "fsync") && BSON_ITER_HOLDS_BOOL(&iter) && bson_iter_bool(&iter));
    assert(bson_iter_init_find(&iter, b, "j") && BSON_ITER_HOLDS_BOOL(&iter) && bson_iter_bool(&iter));
    assert(bson_iter_init_find(&iter, b, "w") && BSON_ITER_HOLDS_INT32(&iter) && bson_iter_int32(&iter) == 3);
    assert(b);

    mongoc_write_concern_destroy(write_concern);
}
Beispiel #7
0
/*
 *-----------------------------------------------------------------------
 *
 * Run the JSON tests from the SDAM Monitoring spec.
 *
 *-----------------------------------------------------------------------
 */
static void
test_sdam_monitoring_cb (bson_t *test)
{
   mongoc_client_t *client;
   mongoc_topology_t *topology;
   bson_t phase;
   bson_t phases;
   bson_t outcome;
   bson_iter_t phase_iter;
   bson_iter_t phase_field_iter;
   bson_iter_t outcome_iter;
   bson_iter_t iter;
   bson_t events_expected;
   context_t context;

   /* parse out the uri and use it to create a client */
   BSON_ASSERT (bson_iter_init_find (&iter, test, "uri"));
   client = mongoc_client_new (bson_iter_utf8 (&iter, NULL));
   topology = client->topology;
   context_init (&context);
   client_set_topology_event_callbacks (client, &context);

   /* for each phase, parse and validate */
   BSON_ASSERT (bson_iter_init_find (&iter, test, "phases"));
   bson_iter_bson (&iter, &phases);
   bson_iter_init (&phase_iter, &phases);

   while (bson_iter_next (&phase_iter)) {
      bson_iter_bson (&phase_iter, &phase);

      /* this test doesn't exercise this code path naturally, see below in
       * _test_topology_events for a non-hacky test of this event */
      _mongoc_topology_description_monitor_opening (&topology->description);
      process_sdam_test_ismaster_responses (&phase,
                                            &client->topology->description);

      /* parse out "outcome" and validate */
      BSON_ASSERT (bson_iter_init_find (&phase_field_iter, &phase, "outcome"));
      bson_iter_bson (&phase_field_iter, &outcome);
      bson_iter_init (&outcome_iter, &outcome);

      while (bson_iter_next (&outcome_iter)) {
         if (strcmp ("events", bson_iter_key (&outcome_iter)) == 0) {
            bson_iter_bson (&outcome_iter, &events_expected);
            check_json_apm_events (&context.events, &events_expected);
         } else {
            fprintf (stderr,
                     "ERROR: unparsed test field %s\n",
                     bson_iter_key (&outcome_iter));
            BSON_ASSERT (false);
         }
      }
   }

   mongoc_client_destroy (client);
   context_destroy (&context);
}
Beispiel #8
0
static void
test_bson_append_iter (void)
{
   bson_iter_t iter;
   bson_bool_t r;
   bson_t b;
   bson_t c;

   bson_init(&b);
   bson_append_int32(&b, "a", 1, 1);
   bson_append_int32(&b, "b", 1, 2);
   bson_append_int32(&b, "c", 1, 3);
   bson_append_utf8(&b, "d", 1, "hello", 5);

   bson_init(&c);

   r = bson_iter_init_find(&iter, &b, "a");
   assert(r);
   r = bson_append_iter(&c, NULL, 0, &iter);
   assert(r);

   r = bson_iter_init_find(&iter, &b, "c");
   assert(r);
   r = bson_append_iter(&c, NULL, 0, &iter);
   assert(r);

   r = bson_iter_init_find(&iter, &b, "d");
   assert(r);
   r = bson_append_iter(&c, "world", -1, &iter);
   assert(r);

   bson_iter_init(&iter, &c);
   r = bson_iter_next(&iter);
   assert(r);
   assert_cmpstr("a", bson_iter_key(&iter));
   assert_cmpint(BSON_TYPE_INT32, ==, bson_iter_type(&iter));
   assert_cmpint(1, ==, bson_iter_int32(&iter));
   r = bson_iter_next(&iter);
   assert(r);
   assert_cmpstr("c", bson_iter_key(&iter));
   assert_cmpint(BSON_TYPE_INT32, ==, bson_iter_type(&iter));
   assert_cmpint(3, ==, bson_iter_int32(&iter));
   r = bson_iter_next(&iter);
   assert(r);
   assert_cmpint(BSON_TYPE_UTF8, ==, bson_iter_type(&iter));
   assert_cmpstr("world", bson_iter_key(&iter));
   assert_cmpstr("hello", bson_iter_utf8(&iter, NULL));

   bson_destroy(&b);
   bson_destroy(&c);
}
Beispiel #9
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;
}
static void
test_write_concern_bson_omits_defaults (void)
{
   mongoc_write_concern_t *write_concern;
   const bson_t *gle;
   const bson_t *bson;
   bson_iter_t iter;

   write_concern = mongoc_write_concern_new();

   /*
    * Check generated bson.
    */
   ASSERT(write_concern);

   gle = _mongoc_write_concern_get_gle(write_concern);
   ASSERT(bson_iter_init_find(&iter, gle, "getlasterror") && BSON_ITER_HOLDS_INT32(&iter) && bson_iter_int32(&iter) == 1);
   ASSERT(!bson_iter_init_find(&iter, gle, "fsync"));
   ASSERT(!bson_iter_init_find(&iter, gle, "j"));
   ASSERT(!bson_iter_init_find(&iter, gle, "w"));
   ASSERT(gle);

   bson = _mongoc_write_concern_get_bson(write_concern);
   ASSERT(!bson_iter_init_find(&iter, bson, "getlasterror"));
   ASSERT(!bson_iter_init_find(&iter, bson, "fsync"));
   ASSERT(!bson_iter_init_find(&iter, bson, "j"));
   ASSERT(!bson_iter_init_find(&iter, gle, "w"));
   ASSERT(bson);

   mongoc_write_concern_destroy(write_concern);
}
static void
test_write_concern_bson_includes_false_fsync_and_journal (void)
{
   mongoc_write_concern_t *write_concern;
   const bson_t *gle;
   const bson_t *bson;
   bson_iter_t iter;

   write_concern = mongoc_write_concern_new();

   /*
    * Check generated bson.
    */
   ASSERT(write_concern);
   mongoc_write_concern_set_fsync(write_concern, false);
   mongoc_write_concern_set_journal(write_concern, false);

   gle = _mongoc_write_concern_get_gle(write_concern);
   ASSERT(bson_iter_init_find(&iter, gle, "getlasterror") && BSON_ITER_HOLDS_INT32(&iter) && bson_iter_int32(&iter) == 1);
   ASSERT(bson_iter_init_find(&iter, gle, "fsync") && BSON_ITER_HOLDS_BOOL(&iter) && !bson_iter_bool(&iter));
   ASSERT(bson_iter_init_find(&iter, gle, "j") && BSON_ITER_HOLDS_BOOL(&iter) && !bson_iter_bool(&iter));
   ASSERT(!bson_iter_init_find(&iter, gle, "w"));
   ASSERT(gle);

   bson = _mongoc_write_concern_get_bson(write_concern);
   ASSERT(!bson_iter_init_find(&iter, bson, "getlasterror"));
   ASSERT(bson_iter_init_find(&iter, bson, "fsync") && BSON_ITER_HOLDS_BOOL(&iter) && !bson_iter_bool(&iter));
   ASSERT(bson_iter_init_find(&iter, bson, "j") && BSON_ITER_HOLDS_BOOL(&iter) && !bson_iter_bool(&iter));
   ASSERT(!bson_iter_init_find(&iter, bson, "w"));
   ASSERT(bson);

   mongoc_write_concern_destroy(write_concern);
}
Beispiel #12
0
static void
test_bson_iter_overwrite_bool (void)
{
   bson_iter_t iter;
   bson_t b;

   bson_init(&b);
   assert(bson_append_bool(&b, "key", -1, true));
   assert(bson_iter_init_find(&iter, &b, "key"));
   assert(BSON_ITER_HOLDS_BOOL(&iter));
   bson_iter_overwrite_bool(&iter, false);
   assert(bson_iter_init_find(&iter, &b, "key"));
   assert(BSON_ITER_HOLDS_BOOL(&iter));
   assert_cmpint(bson_iter_bool(&iter), ==, false);
   bson_destroy(&b);
}
Beispiel #13
0
static void
test_bson_iter_overwrite_double (void)
{
   bson_iter_t iter;
   bson_t b;

   bson_init(&b);
   assert(bson_append_double(&b, "key", -1, 1234.1234));
   assert(bson_iter_init_find(&iter, &b, "key"));
   assert(BSON_ITER_HOLDS_DOUBLE(&iter));
   bson_iter_overwrite_double(&iter, 4641.1234);
   assert(bson_iter_init_find(&iter, &b, "key"));
   assert(BSON_ITER_HOLDS_DOUBLE(&iter));
   assert_cmpint(bson_iter_double(&iter), ==, 4641.1234);
   bson_destroy(&b);
}
bool
bson_find_create_table (bson_t      *bson_schema,
                        const char  *table_name,
                        bson_iter_t *iter_col)
{
    bson_iter_t iter_json, iter_ary, iter_sql, iter_table_prop;

    bson_iter_init_find (&iter_json, bson_schema, "json") || DIE;
    BSON_ITER_HOLDS_ARRAY (&iter_json) || DIE;
    bson_iter_recurse (&iter_json, &iter_ary) || DIE;
    while (bson_iter_next (&iter_ary)) {
        (BSON_ITER_HOLDS_DOCUMENT (&iter_ary) || DIE);
        bson_iter_recurse (&iter_ary, &iter_sql) || DIE;
        if (bson_iter_find (&iter_sql, "create_table") &&
            (BSON_ITER_HOLDS_DOCUMENT (&iter_sql) || DIE) &&
            (bson_iter_recurse (&iter_sql, &iter_table_prop) || DIE) &&
            (bson_iter_find (&iter_table_prop, "table_name") || DIE) &&
            (BSON_ITER_HOLDS_UTF8 (&iter_table_prop) || DIE) &&
            (strcmp (bson_iter_utf8 (&iter_table_prop, NULL), table_name) == 0) &&
            (bson_iter_find (&iter_table_prop, "columns") || DIE) &&
            (BSON_ITER_HOLDS_ARRAY (&iter_table_prop) || DIE)) {
            bson_iter_recurse (&iter_table_prop, iter_col) || DIE;
            return true;
        }
    }
    return (false);
}
/* Test method that returns the server's version string */
static String HHVM_METHOD(MongoClient, getServerVersion) {
  bool result;
  bson_t buildInfo, reply;
  bson_error_t error;
  bson_iter_t iter;
  String retval;

  auto client = get_client(this_);

  bson_init(&buildInfo);
  bson_append_int32(&buildInfo, "buildInfo", 9, 1);

  result = mongoc_client_command_simple(client->get(), "test", &buildInfo, nullptr, &reply, &error);

  bson_destroy(&buildInfo);

  if ( ! result) {
    throw Exception("Command error: %s", error.message);
  }

  if (bson_iter_init_find(&iter, &reply, "version")) {
    retval = String(bson_iter_utf8(&iter, nullptr), CopyString);
  }

  bson_destroy(&reply);

  return retval;
}
static void
copy_labels_plus_unknown_commit_result (const bson_t *src, bson_t *dst)
{
   bson_iter_t iter;
   bson_iter_t src_label;
   bson_t dst_labels;
   char str[16];
   uint32_t i = 0;
   const char *key;

   BSON_APPEND_ARRAY_BEGIN (dst, "errorLabels", &dst_labels);
   BSON_APPEND_UTF8 (&dst_labels, "0", UNKNOWN_COMMIT_RESULT);

   /* append any other errorLabels already in "src" */
   if (bson_iter_init_find (&iter, src, "errorLabels") &&
       bson_iter_recurse (&iter, &src_label)) {
      while (bson_iter_next (&src_label) && BSON_ITER_HOLDS_UTF8 (&src_label)) {
         if (strcmp (bson_iter_utf8 (&src_label, NULL),
                     UNKNOWN_COMMIT_RESULT) != 0) {
            i++;
            bson_uint32_to_string (i, &key, str, sizeof str);
            BSON_APPEND_UTF8 (
               &dst_labels, key, bson_iter_utf8 (&src_label, NULL));
         }
      }
   }

   bson_append_array_end (dst, &dst_labels);
}
Beispiel #17
0
static void
test_bson_iter_overwrite_int64 (void)
{
   bson_iter_t iter;
   bson_t b;

   bson_init(&b);
   assert(bson_append_int64(&b, "key", -1, 1234));
   assert(bson_iter_init_find(&iter, &b, "key"));
   assert(BSON_ITER_HOLDS_INT64(&iter));
   bson_iter_overwrite_int64(&iter, 4641);
   assert(bson_iter_init_find(&iter, &b, "key"));
   assert(BSON_ITER_HOLDS_INT64(&iter));
   assert_cmpint(bson_iter_int64(&iter), ==, 4641);
   bson_destroy(&b);
}
bool
_mongoc_cursor_array_prime (mongoc_cursor_t *cursor)
{
   bool ret = true;
   mongoc_cursor_array_t *arr;
   bson_iter_t iter;

   ENTRY;

   arr = (mongoc_cursor_array_t *)cursor->iface_data;
   if (!arr->has_array) {
      arr->has_array = true;

      ret = _mongoc_cursor_next (cursor, &arr->result);

      if (!(ret &&
            bson_iter_init_find (&iter, arr->result, arr->field_name) &&
            BSON_ITER_HOLDS_ARRAY (&iter) &&
            bson_iter_recurse (&iter, &arr->iter))) {
         ret = false;
      }
   }

   return ret;
}
Beispiel #19
0
/* {{{ proto WriteError[] WriteResult::getWriteErrors()
   Returns any write errors that occurred */
PHP_METHOD(WriteResult, getWriteErrors)
{
	bson_iter_t iter, child;
	php_phongo_writeresult_t *intern;
	SUPPRESS_UNUSED_WARNING(return_value_ptr) SUPPRESS_UNUSED_WARNING(return_value_used)


	intern = Z_WRITERESULT_OBJ_P(getThis());

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}


	array_init(return_value);

	if (bson_iter_init_find(&iter, intern->reply, "writeErrors") && BSON_ITER_HOLDS_ARRAY(&iter) && bson_iter_recurse(&iter, &child)) {
		while (bson_iter_next(&child)) {
			bson_t cbson;
			uint32_t len;
			const uint8_t *data;
#if PHP_VERSION_ID >= 70000
			zval writeerror;
#else
			zval *writeerror = NULL;
#endif

			if (!BSON_ITER_HOLDS_DOCUMENT(&child)) {
				continue;
			}

			bson_iter_document(&child, &len, &data);

			if (!bson_init_static(&cbson, data, len)) {
				continue;
			}

#if PHP_VERSION_ID >= 70000
			object_init_ex(&writeerror, php_phongo_writeerror_ce);

			if (!phongo_writeerror_init(&writeerror, &cbson TSRMLS_CC)) {
				zval_ptr_dtor(&writeerror);
				continue;
			}

			add_next_index_zval(return_value, &writeerror);
#else
			MAKE_STD_ZVAL(writeerror);
			object_init_ex(writeerror, php_phongo_writeerror_ce);

			if (!phongo_writeerror_init(writeerror, &cbson TSRMLS_CC)) {
				zval_ptr_dtor(&writeerror);
				continue;
			}

			add_next_index_zval(return_value, writeerror);
#endif
		}
	}
}
Beispiel #20
0
void
_mongoc_write_command_insert_append (mongoc_write_command_t *command,
                                     const bson_t *document)
{
   bson_iter_t iter;
   bson_oid_t oid;
   bson_t tmp;

   ENTRY;

   BSON_ASSERT (command);
   BSON_ASSERT (command->type == MONGOC_WRITE_COMMAND_INSERT);
   BSON_ASSERT (document);
   BSON_ASSERT (document->len >= 5);

   /*
    * If the document does not contain an "_id" field, we need to generate
    * a new oid for "_id".
    */
   if (!bson_iter_init_find (&iter, document, "_id")) {
      bson_init (&tmp);
      bson_oid_init (&oid, NULL);
      BSON_APPEND_OID (&tmp, "_id", &oid);
      bson_concat (&tmp, document);
      _mongoc_buffer_append (&command->payload, bson_get_data (&tmp), tmp.len);
      bson_destroy (&tmp);
   } else {
      _mongoc_buffer_append (
         &command->payload, bson_get_data (document), document->len);
   }

   command->n_documents++;

   EXIT;
}
/*
 * Start iterating the reply to an "aggregate", "find", "getMore" etc. command:
 *
 *    {cursor: {id: 1234, ns: "db.collection", firstBatch: [...]}}
 */
bool
_mongoc_cursor_cursorid_start_batch (mongoc_cursor_t *cursor)
{
   mongoc_cursor_cursorid_t *cid;
   bson_iter_t iter;
   bson_iter_t child;
   const char *ns;
   uint32_t nslen;

   cid = (mongoc_cursor_cursorid_t *)cursor->iface_data;

   BSON_ASSERT (cid);

   if (bson_iter_init_find (&iter, &cid->array, "cursor") &&
       BSON_ITER_HOLDS_DOCUMENT (&iter) &&
       bson_iter_recurse (&iter, &child)) {
      while (bson_iter_next (&child)) {
         if (BSON_ITER_IS_KEY (&child, "id")) {
            cursor->rpc.reply.cursor_id = bson_iter_as_int64 (&child);
         } else if (BSON_ITER_IS_KEY (&child, "ns")) {
            ns = bson_iter_utf8 (&child, &nslen);
            _mongoc_set_cursor_ns (cursor, ns, nslen);
         } else if (BSON_ITER_IS_KEY (&child, "firstBatch") ||
                    BSON_ITER_IS_KEY (&child, "nextBatch")) {
            if (BSON_ITER_HOLDS_ARRAY (&child) &&
                bson_iter_recurse (&child, &cid->batch_iter)) {
               cid->in_batch = true;
            }
         }
      }
   }

   return cid->in_batch;
}
static void
test_validate (void)
{
   mongoc_collection_t *collection;
   mongoc_client_t *client;
   bson_iter_t iter;
   bson_error_t error;
   bson_t doc = BSON_INITIALIZER;
   bson_t opts = BSON_INITIALIZER;
   bson_t reply;
   bool r;

   client = mongoc_client_new (gTestUri);
   ASSERT (client);

   collection = get_test_collection (client, "test_validate");
   ASSERT (collection);

   r = mongoc_collection_insert(collection, MONGOC_INSERT_NONE, &doc, NULL, &error);
   assert (r);

   BSON_APPEND_BOOL (&opts, "full", true);

   r = mongoc_collection_validate (collection, &opts, &reply, &error);
   assert (r);

   assert (bson_iter_init_find (&iter, &reply, "ns"));
   assert (bson_iter_init_find (&iter, &reply, "valid"));

   bson_destroy (&reply);

   bson_reinit (&opts);
   BSON_APPEND_UTF8 (&opts, "full", "bad_value");

   r = mongoc_collection_validate (collection, &opts, &reply, &error);
   assert (!r);
   assert (error.domain == MONGOC_ERROR_BSON);
   assert (error.code == MONGOC_ERROR_BSON_INVALID);

   r = mongoc_collection_drop (collection, &error);
   assert (r);

   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);
   bson_destroy (&doc);
   bson_destroy (&opts);
}
Beispiel #23
0
/* {{{ proto array WriteResult::getUpsertedIds()
   Returns the identifiers generated by the server for upsert operations. */
PHP_METHOD(WriteResult, getUpsertedIds)
{
	bson_iter_t iter, child;
	php_phongo_writeresult_t *intern;
	SUPPRESS_UNUSED_WARNING(return_value_ptr) SUPPRESS_UNUSED_WARNING(return_value_used)


	intern = Z_WRITERESULT_OBJ_P(getThis());

	if (zend_parse_parameters_none() == FAILURE) {
		return;
	}


	array_init(return_value);

	if (bson_iter_init_find(&iter, intern->reply, "upserted") && BSON_ITER_HOLDS_ARRAY(&iter) && bson_iter_recurse(&iter, &child)) {
		while (bson_iter_next(&child)) {
			int32_t index;
			bson_iter_t outer;

			if (!BSON_ITER_HOLDS_DOCUMENT(&child) || !bson_iter_recurse(&child, &outer)) {
				continue;
			}
			if (!bson_iter_find(&outer, "index") || !BSON_ITER_HOLDS_INT32(&outer)) {
				continue;
			}

			index = bson_iter_int32(&outer);

			if (!bson_iter_find(&outer, "_id")) {
				continue;
			}

			if (BSON_ITER_HOLDS_OID(&outer)) {
#if PHP_VERSION_ID >= 70000
				zval zid;

				php_phongo_objectid_new_from_oid(&zid, bson_iter_oid(&outer) TSRMLS_CC);
				add_index_zval(return_value, index, &zid);
#else
				zval *zid = NULL;
				MAKE_STD_ZVAL(zid);

				php_phongo_objectid_new_from_oid(zid, bson_iter_oid(&outer) TSRMLS_CC);
				add_index_zval(return_value, index, zid);
#endif
			} else if (BSON_ITER_HOLDS_INT32(&outer)) {
				int32_t val = bson_iter_int32(&outer);

				add_index_long(return_value, index, val);
			} else if (BSON_ITER_HOLDS_INT64(&outer)) {
				int64_t val = bson_iter_int64(&outer);

				ADD_INDEX_INT64(return_value, index, val);
			}
		}
	}
}
Beispiel #24
0
static bool
_mongoc_cursor_unwrap_failure (mongoc_cursor_t *cursor)
{
   bson_iter_t iter;
   bson_t b;

   ENTRY;

   bson_return_val_if_fail(cursor, false);

   if (cursor->rpc.header.opcode != MONGOC_OPCODE_REPLY) {
      bson_set_error(&cursor->error,
                     MONGOC_ERROR_PROTOCOL,
                     MONGOC_ERROR_PROTOCOL_INVALID_REPLY,
                     "Received rpc other than OP_REPLY.");
      RETURN(true);
   }

   if ((cursor->rpc.reply.flags & MONGOC_REPLY_QUERY_FAILURE)) {
      if (_mongoc_rpc_reply_get_first(&cursor->rpc.reply, &b)) {
         _mongoc_cursor_populate_error(cursor, &b, &cursor->error);
         bson_destroy(&b);
      } else {
         bson_set_error(&cursor->error,
                        MONGOC_ERROR_QUERY,
                        MONGOC_ERROR_QUERY_FAILURE,
                        "Unknown query failure.");
      }
      RETURN(true);
   } else if (cursor->is_command) {
      if (_mongoc_rpc_reply_get_first (&cursor->rpc.reply, &b)) {
         if (bson_iter_init_find (&iter, &b, "ok")) {
            if (bson_iter_as_bool (&iter)) {
               RETURN (false);
            } else {
               _mongoc_cursor_populate_error (cursor, &b, &cursor->error);
               bson_destroy (&b);
               RETURN (true);
            }
         }
      } else {
         bson_set_error (&cursor->error,
                         MONGOC_ERROR_BSON,
                         MONGOC_ERROR_BSON_INVALID,
                         "Failed to decode document from the server.");
         RETURN (true);
      }
   }

   if ((cursor->rpc.reply.flags & MONGOC_REPLY_CURSOR_NOT_FOUND)) {
      bson_set_error(&cursor->error,
                     MONGOC_ERROR_CURSOR,
                     MONGOC_ERROR_CURSOR_INVALID_CURSOR,
                     "The cursor is invalid or has expired.");
      RETURN(true);
   }

   RETURN(false);
}
Beispiel #25
0
static void
test_bson_append_code_with_scope (void)
{
   const bson_uint8_t *scope_buf = NULL;
   bson_uint32_t scopelen = 0;
   bson_uint32_t len = 0;
   bson_iter_t iter;
   bson_bool_t r;
   const char *code = NULL;
   bson_t *b;
   bson_t *b2;
   bson_t *scope;

   /* Test with empty bson, which converts to just CODE type. */
   b = bson_new();
   scope = bson_new();
   assert(bson_append_code_with_scope(b, "code", -1, "var a = {};", scope));
   b2 = get_bson("test30.bson");
   assert_bson_equal(b, b2);
   r = bson_iter_init_find(&iter, b, "code");
   assert(r);
   assert(BSON_ITER_HOLDS_CODE(&iter)); /* Not codewscope */
   bson_destroy(b);
   bson_destroy(b2);
   bson_destroy(scope);



   /* Test with non-empty scope */
   b = bson_new();
   scope = bson_new();
   assert(bson_append_utf8(scope, "foo", -1, "bar", -1));
   assert(bson_append_code_with_scope(b, "code", -1, "var a = {};", scope));
   b2 = get_bson("test31.bson");
   assert_bson_equal(b, b2);
   r = bson_iter_init_find(&iter, b, "code");
   assert(r);
   assert(BSON_ITER_HOLDS_CODEWSCOPE(&iter));
   code = bson_iter_codewscope(&iter, &len, &scopelen, &scope_buf);
   assert(len == 11);
   assert(scopelen == scope->len);
   assert(!strcmp(code, "var a = {};"));
   bson_destroy(b);
   bson_destroy(b2);
   bson_destroy(scope);
}
/*---------------------------------------------------------------------------
 *
 * _change_stream_init --
 *
 *       Called after @stream has the collection name, database name, read
 *       preferences, and read concern set. Creates the change streams
 *       cursor.
 *
 *--------------------------------------------------------------------------
 */
void
_change_stream_init (mongoc_change_stream_t *stream,
                     const bson_t *pipeline,
                     const bson_t *opts)
{
   BSON_ASSERT (pipeline);

   stream->max_await_time_ms = -1;
   stream->batch_size = -1;
   bson_init (&stream->pipeline_to_append);
   bson_init (&stream->resume_token);
   bson_init (&stream->err_doc);

   if (!_mongoc_change_stream_opts_parse (
          stream->client, opts, &stream->opts, &stream->err)) {
      return;
   }

   stream->full_document = BCON_NEW ("fullDocument", stream->opts.fullDocument);

   if (!bson_empty (&(stream->opts.resumeAfter))) {
      bson_append_document (
         &stream->resume_token, "resumeAfter", 11, &(stream->opts.resumeAfter));
   }

   _mongoc_timestamp_set (&stream->operation_time,
                          &(stream->opts.startAtOperationTime));

   stream->batch_size = stream->opts.batchSize;
   stream->max_await_time_ms = stream->opts.maxAwaitTimeMS;

   /* Accept two forms of user pipeline:
    * 1. A document like: { "pipeline": [...] }
    * 2. An array-like document: { "0": {}, "1": {}, ... }
    * If the passed pipeline is invalid, we pass it along and let the server
    * error instead.
    */
   if (!bson_empty (pipeline)) {
      bson_iter_t iter;
      if (bson_iter_init_find (&iter, pipeline, "pipeline") &&
          BSON_ITER_HOLDS_ARRAY (&iter)) {
         if (!BSON_APPEND_VALUE (&stream->pipeline_to_append,
                                 "pipeline",
                                 bson_iter_value (&iter))) {
            CHANGE_STREAM_ERR ("pipeline");
         }
      } else {
         if (!BSON_APPEND_ARRAY (
                &stream->pipeline_to_append, "pipeline", pipeline)) {
            CHANGE_STREAM_ERR ("pipeline");
         }
      }
   }

   if (stream->err.code == 0) {
      (void) _make_cursor (stream);
   }
}
Beispiel #27
0
static struct ofields* get_data(struct results* res)
{
	struct ofields* fields;
	const char* msg;
	const char* prog;
	const char* syslog_tag;
	int64_t date_r;
	bson_iter_t c;

	fields = malloc (sizeof (struct ofields));
	bson_iter_init_find (&c, res->result, "msg");
	if (!(msg = bson_iter_utf8 (&c, NULL)))
	{
		perror ("bson_cursor_get_string()");
		exit (1);
	}

	bson_iter_init_find (&c, res->result, "sys");
	if (!(prog = bson_iter_utf8 (&c, NULL)))
	{
		perror ("bson_cursor_get_string()");
		exit (1);
	}

	bson_iter_init_find (&c, res->result, "syslog_tag");
	if (!(syslog_tag = bson_iter_utf8 (&c, NULL)))
	{
		perror ("bson_cursor_get_string()");
		exit (1);
	}

	bson_iter_init_find (&c, res->result, "time_rcvd");
	if (!(date_r = bson_iter_date_time (&c)))
	{
		perror ("bson_cursor_get_utc_datetime()");
		exit (1);
	}

	fields->msg = msg;
	fields->prog = prog;
	fields->syslog_tag = syslog_tag;
	fields->date_r = date_r;

	return fields;
}
Beispiel #28
0
/* Construct the aggregate command in cmd:
 * { aggregate: collname, pipeline: [], cursor: { batchSize: x } } */
static void
_make_command (mongoc_change_stream_t *stream, bson_t *command)
{
   bson_iter_t iter;
   bson_t change_stream_stage; /* { $changeStream: <change_stream_doc> } */
   bson_t change_stream_doc;
   bson_t pipeline;
   bson_t cursor_doc;

   bson_init (command);
   bson_append_utf8 (command,
                     "aggregate",
                     9,
                     stream->coll->collection,
                     stream->coll->collectionlen);
   bson_append_array_begin (command, "pipeline", 8, &pipeline);

   /* Append the $changeStream stage */
   bson_append_document_begin (&pipeline, "0", 1, &change_stream_stage);
   bson_append_document_begin (
      &change_stream_stage, "$changeStream", 13, &change_stream_doc);
   bson_concat (&change_stream_doc, &stream->full_document);
   if (!bson_empty (&stream->resume_token)) {
      bson_concat (&change_stream_doc, &stream->resume_token);
   }
   bson_append_document_end (&change_stream_stage, &change_stream_doc);
   bson_append_document_end (&pipeline, &change_stream_stage);

   /* Append user pipeline if it exists */
   if (bson_iter_init_find (&iter, &stream->pipeline_to_append, "pipeline") &&
       BSON_ITER_HOLDS_ARRAY (&iter)) {
      bson_iter_t child_iter;
      uint32_t key_int = 1;
      char buf[16];
      const char *key_str;

      BSON_ASSERT (bson_iter_recurse (&iter, &child_iter));
      while (bson_iter_next (&child_iter)) {
         /* The user pipeline may consist of invalid stages or non-documents.
          * Append anyway, and rely on the server error. */
         size_t keyLen =
            bson_uint32_to_string (key_int, &key_str, buf, sizeof (buf));
         bson_append_value (
            &pipeline, key_str, (int) keyLen, bson_iter_value (&child_iter));
         ++key_int;
      }
   }

   bson_append_array_end (command, &pipeline);

   /* Add batch size if needed */
   bson_append_document_begin (command, "cursor", 6, &cursor_doc);
   if (stream->batch_size > 0) {
      bson_append_int32 (&cursor_doc, "batchSize", 9, stream->batch_size);
   }
   bson_append_document_end (command, &cursor_doc);
}
Beispiel #29
0
void
ha_replica_set_wait_for_healthy (ha_replica_set_t *replica_set)
{
   bson_iter_t iter;
   bson_iter_t ar;
   bson_iter_t member;
   const char *stateStr;
   bson_t status;

again:
   sleep(1);

   if (!ha_replica_set_get_status(replica_set, &status)) {
      MONGOC_INFO("Failed to get replicaSet status. "
                  "Sleeping 1 second.");
      goto again;
   }

#if 0
   {
      char *str;

      str = bson_as_json(&status, NULL);
      printf("%s\n", str);
      bson_free(str);
   }
#endif

   if (!bson_iter_init_find(&iter, &status, "members") ||
       !BSON_ITER_HOLDS_ARRAY(&iter) ||
       !bson_iter_recurse(&iter, &ar)) {
      bson_destroy(&status);
      MONGOC_INFO("ReplicaSet has not yet come online. "
                  "Sleeping 1 second.");
      goto again;
   }

   while (bson_iter_next(&ar)) {
      if (BSON_ITER_HOLDS_DOCUMENT(&ar) &&
          bson_iter_recurse(&ar, &member) &&
          bson_iter_find(&member, "stateStr") &&
          (stateStr = bson_iter_utf8(&member, NULL))) {
         if (!!strcmp(stateStr, "PRIMARY") &&
             !!strcmp(stateStr, "SECONDARY") &&
             !!strcmp(stateStr, "ARBITER")) {
            bson_destroy(&status);
            MONGOC_INFO("Found unhealthy node. Sleeping 1 second.");
            goto again;
         }
      }
   }

   bson_destroy(&status);
}
/**
 * mongoc_database_has_collection:
 * @database: (in): A #mongoc_database_t.
 * @name: (in): The name of the collection to check for.
 * @error: (out) (allow-none): A location for a #bson_error_t, or %NULL.
 *
 * Checks to see if a collection exists within the database on the MongoDB
 * server.
 *
 * This will return %false if their was an error communicating with the
 * server, or if the collection does not exist.
 *
 * If @error is provided, it will first be zeroed. Upon error, error.domain
 * will be set.
 *
 * Returns: %true if @name exists, otherwise %false. @error may be set.
 */
bool
mongoc_database_has_collection (mongoc_database_t *database,
                                const char        *name,
                                bson_error_t      *error)
{
    mongoc_collection_t *collection;
    mongoc_read_prefs_t *read_prefs;
    mongoc_cursor_t *cursor;
    const bson_t *doc;
    bson_iter_t iter;
    bool ret = false;
    const char *cur_name;
    bson_t q = BSON_INITIALIZER;
    char ns[140];

    ENTRY;

    BSON_ASSERT (database);
    BSON_ASSERT (name);

    if (error) {
        memset (error, 0, sizeof *error);
    }

    bson_snprintf (ns, sizeof ns, "%s.%s", database->name, name);
    ns[sizeof ns - 1] = '\0';

    read_prefs = mongoc_read_prefs_new (MONGOC_READ_PRIMARY);
    collection = mongoc_client_get_collection (database->client,
                 database->name,
                 "system.namespaces");
    cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, &q,
                                     NULL, read_prefs);

    while (!mongoc_cursor_error (cursor, error) &&
            mongoc_cursor_more (cursor)) {
        while (mongoc_cursor_next (cursor, &doc) &&
                bson_iter_init_find (&iter, doc, "name") &&
                BSON_ITER_HOLDS_UTF8 (&iter)) {
            cur_name = bson_iter_utf8(&iter, NULL);
            if (!strcmp(cur_name, ns)) {
                ret = true;
                GOTO(cleanup);
            }
        }
    }

cleanup:
    mongoc_cursor_destroy (cursor);
    mongoc_collection_destroy (collection);
    mongoc_read_prefs_destroy (read_prefs);

    RETURN(ret);
}