1<?php
2/**
3 * The following example demonstrates how you might use query scan consistency
4 * when your fetching code sensitive to data mutations. For example, you are
5 * updating someonce score and it is necessary to apply change immediately and
6 * do not allow stale information in the queries.
7 *
8 * In this example we will implement helper for autoincrementing document IDs.
9 *
10 * Read about how it works here:
11 * http://developer.couchbase.com/documentation/server/4.0/architecture/querying-data-with-n1ql.html#story-h2-2
12 */
13
14/*
15 * Create a new Cluster object to represent the connection to our
16 * cluster and specify any needed options such as SSL.
17 */
18$cluster = new \Couchbase\Cluster('couchbase://localhost');
19/*
20 * We open the default bucket to store our docuemtns in.
21 */
22$bucket = $cluster->openBucket('default');
23
24
25function get_next_doc_id($bucket, $consistency)
26{
27    /*
28     * Order all documents in the bucket by their IDs lexicographically
29     * from higher to lower and select first result.
30     */
31    $query = \Couchbase\N1qlQuery::fromString('select meta(`default`).id from `default` order by meta(`default`).id desc limit 1');
32    $query->consistency($consistency);
33    $res = $bucket->query($query);
34    $id = 1; // for empty bucket lets consider next ID be 1.
35    if (count($res->rows) > 0) {
36        // If there are documents in the bucket just increment it.
37        $id = (int)$res->rows[0]->id + 1;
38    }
39    return sprintf("%08d", $id);
40}
41
42/*
43 * First round with NOT_BOUNDED consistency, which is default.
44 * Obviously this round will complete faster.
45 */
46printf("using NOT_BOUNDED consistency (generates 'STALE ID...' messages)\n");
47for ($prev_id = "", $i = 0; $i < 10; $i++, $prev_id = $next_id) {
48    printf(".");
49    $next_id = get_next_doc_id($bucket, \Couchbase\N1qlQuery::NOT_BOUNDED);
50    if ($prev_id == $next_id) {
51        /*
52         * In this case the program reports STALE ID for almost every iteration.
53         */
54        printf("STALE ID: %d\n", $next_id);
55    }
56    $bucket->upsert($next_id, array('i' => $i));
57}
58
59/*
60 * Second round with REQUEST_PLUS consistency, and it will not
61 * generate STALE ID messages.
62 */
63printf("using REQUEST_PLUS consistency (works as expected)\n");
64for ($prev_id = "", $i = 0; $i < 10; $i++, $prev_id = $next_id) {
65    printf(".");
66    $next_id = get_next_doc_id($bucket, \Couchbase\N1qlQuery::REQUEST_PLUS);
67    if ($prev_id == $next_id) {
68        printf("STALE ID: %d\n", $next_id);
69    }
70    $bucket->upsert($next_id, array('i' => $i));
71}
72