1<?php
2
3/**
4 * The tests are relying on two buckets created:
5 *
6 *   - `people` with password 'secret'
7 *   - `orders` with password '123456'
8 *
9 * Also primary indexes have to be created on them.
10 */
11class SearchTest extends PHPUnit_Framework_TestCase {
12    public function __construct() {
13        $testDsn = getenv('CB_DSN');
14        if ($testDsn === FALSE) {
15            $testDsn = 'couchbase://localhost/';
16        }
17        $this->cluster = new \Couchbase\Cluster($testDsn);
18    }
19
20    protected function populatePeople() {
21        $bucket = $this->cluster->openBucket('people', 'secret');
22        $bucket->upsert("john", ['name' => 'John Doe', 'city' => 'New York']);
23        $bucket->upsert("jane", ['name' => 'Jane Doe', 'city' => 'Miami']);
24    }
25
26    protected function populateOrders() {
27        $bucket = $this->cluster->openBucket('orders', '123456');
28        $bucket->upsert("soap-12", ['name' => 'Green Soap', 'person_id' => 'john']);
29        $bucket->upsert("soap-42", ['name' => 'Red Soap', 'person_id' => 'jane']);
30        $bucket->upsert("rope-3",  ['name' => 'Rope 5m', 'person_id' => 'john']);
31    }
32
33
34    function testCrossBucketQuery() {
35        $this->populatePeople();
36        $this->populateOrders();
37
38        $authenticator = new \Couchbase\ClassicAuthenticator();
39        $authenticator->bucket('people', 'secret');
40        $authenticator->bucket('orders', '123456');
41        $this->cluster->authenticate($authenticator);
42
43        $bucket = $this->cluster->openBucket('orders');
44
45        $query = \Couchbase\N1qlQuery::fromString(
46            "SELECT * FROM `orders` JOIN `people` ON KEYS `orders`.person_id ORDER BY `orders`.name");
47        $query->consistency(\Couchbase\N1qlQuery::REQUEST_PLUS);
48        $query->crossBucket(true);
49
50        $res = $bucket->query($query);
51
52        $this->assertEquals('Green Soap', $res->rows[0]->orders->name);
53        $this->assertEquals('John Doe', $res->rows[0]->people->name);
54
55        $this->assertEquals('Red Soap', $res->rows[1]->orders->name);
56        $this->assertEquals('Jane Doe', $res->rows[1]->people->name);
57
58        $this->assertEquals('Rope 5m', $res->rows[2]->orders->name);
59        $this->assertEquals('John Doe', $res->rows[2]->people->name);
60    }
61}