Skip to content

Instantly share code, notes, and snippets.

@ajdavis
Last active November 8, 2018 16:21
Show Gist options
  • Save ajdavis/8b3628870bc3a6cc2fa63898364379ca to your computer and use it in GitHub Desktop.
Save ajdavis/8b3628870bc3a6cc2fa63898364379ca to your computer and use it in GitHub Desktop.
C examples for single-threaded Sessions API v2 proposal
bool
user_func (mongoc_client_session_t *session,
void *data,
bson_t *reply /* OUT */,
bson_error_t *error /* OUT */)
{
/* the void pointer is used to pass any user data */
user_defined_t *user_data = (user_defined_t *) data;
/* this is just another reference to the same client defined in main(),
* nothing special here except convenience */
mongoc_client_t *client = mongoc_client_session_get_client (session);
mongoc_collection_t *c = mongoc_client_get_collection (client, "db", "coll");
bson_t doc = BSON_INITIALIZER;
bson_t opts = BSON_INITIALIZER;
bool r;
/* must explicitly pass session in function's opts */
mongoc_client_session_append (session, &opts);
r = mongoc_collection_insert_one (c, &doc, &opts, reply, error);
bson_destroy (&opts);
/* with_transaction knows from the return value and from the reply contents
* whether this failed and whether to retry the txn */
return r;
}
int
main ()
{
mongoc_client_t *client = mongoc_client_new (NULL);
mongoc_client_session_t *session = mongoc_client_start_session (
client, NULL /* options */);
bson_error_t error;
bson_t reply;
bool r;
/* some optional data if the application desires */
user_defined_t user_data;
/* with_transaction can retry user_func if it fails with a transient txn
* error, or else aborts the transaction and returns false. it commits, with
* proper retry logic, if user_func succeeds */
r = mongoc_client_session_with_transaction (session,
user_func,
&user_data,
&reply,
&error);
if (!r) {
fprintf (stderr, "uh-oh!: %s\n", error.message);
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment