summaryrefslogtreecommitdiff
path: root/docs/tutorial/examples/tut_hl_client.c
blob: 68ceb8f1e644c1347a96849bdb914655b3ce5533 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <mongo.h>

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

static void
do_inserts (mongo_sync_connection *conn)
{
  bson *base;
  gint i;

  base = bson_build
    (BSON_TYPE_STRING, "tutorial-program", "tut_hl_client.c", -1,
     BSON_TYPE_INT32, "the answer to life, the universe and everything", 42,
     BSON_TYPE_NONE);
  bson_finish (base);

  for (i = 0; i < 1000; i++)
    {
      bson *n;

      n = bson_new_from_data (bson_data (base), bson_size (base) - 1);
      bson_append_int32 (n, "counter", i);
      bson_finish (n);

      if (!mongo_sync_cmd_insert (conn, "lmc.tutorial", n, NULL))
        {
          fprintf (stderr, "Error inserting document %d: %s\n", i,
                   strerror (errno));
          exit (1);
        }
      bson_free (n);
    }
  bson_free (base);
}

static void
do_query (mongo_sync_connection *conn)
{
  mongo_sync_cursor *c;
  bson *query;
  gchar *error = NULL;

  query = bson_build
    (BSON_TYPE_STRING, "tutorial-program", "tut_hl_client.c", -1,
     BSON_TYPE_NONE);
  bson_finish (query);

  c = mongo_sync_cursor_new (conn, "lmc.tutorial",
                             mongo_sync_cmd_query (conn, "lmc.tutorial", 0,
                                                   0, 10, query, NULL));
  if (!c)
    {
      fprintf (stderr, "Error creating the query cursor: %s\n",
               strerror (errno));
      exit (1);
    }
  bson_free (query);

  while (mongo_sync_cursor_next (c))
    {
      bson *b = mongo_sync_cursor_get_data (c);
      bson_cursor *bc;
      gint32 cnt;

      if (!b)
        {
          int e = errno;

          mongo_sync_cmd_get_last_error (conn, "lmc", &error);
          fprintf (stderr, "Error retrieving cursor data: %s\n",
                   (error) ? error : strerror (e));
          exit (1);
        }

      bc = bson_find (b, "counter");
      bson_cursor_get_int32 (bc, &cnt);
      printf ("\rCounter: %d", cnt);

      bson_cursor_free (bc);
      bson_free (b);
    }
  printf ("\n");

  mongo_sync_cursor_free (c);
}

int
main (void)
{
  mongo_sync_connection *conn;

  conn = mongo_sync_connect ("localhost", 27017, FALSE);
  if (!conn)
    {
      fprintf (stderr, "Connection failed: %s\n", strerror (errno));
      return 1;
    }

  do_inserts (conn);
  do_query (conn);

  mongo_sync_disconnect (conn);
  return 0;
}