|
24 | 24 | namespace Google\Cloud\Samples\Spanner; |
25 | 25 |
|
26 | 26 | use Google\Cloud\Spanner\SpannerClient; |
| 27 | +use Google\Cloud\Spanner\Proto; |
27 | 28 | use Testing\Data\User; |
28 | 29 | use Testing\Data\Book; |
29 | 30 |
|
30 | 31 | /** |
31 | 32 | * Queries sample data from the database using proto columns. |
32 | 33 | * Example: |
33 | 34 | * ``` |
34 | | - * query_data_with_proto_columns($instanceId, $databaseId); |
| 35 | + * query_data_with_proto_columns($instanceId, $databaseId, $userId); |
35 | 36 | * ``` |
36 | 37 | * |
37 | 38 | * @param string $instanceId The Spanner instance ID. |
38 | 39 | * @param string $databaseId The Spanner database ID. |
| 40 | + * @param int $userId The ID of the user to query. |
39 | 41 | */ |
40 | | -function query_data_with_proto_columns(string $instanceId, string $databaseId): void |
41 | | -{ |
| 42 | +function query_data_with_proto_columns( |
| 43 | + string $instanceId, |
| 44 | + string $databaseId, |
| 45 | + int $userId = 1 |
| 46 | +): void { |
42 | 47 | $spanner = new SpannerClient(); |
43 | 48 | $instance = $spanner->instance($instanceId); |
44 | 49 | $database = $instance->database($databaseId); |
45 | 50 |
|
46 | | - // this ensures that the User class has been loaded into the descriptor pool |
47 | | - \GPBMetadata\Data\User::initOnce(); |
48 | | - |
49 | | - $nameValue = 'TestUser 3'; |
50 | 51 | // [START spanner_query_data_with_proto_columns] |
| 52 | + $userProto = (new User()) |
| 53 | + ->setName('Test User ' . $userId); |
| 54 | + |
51 | 55 | $results = $database->execute( |
52 | | - 'SELECT * FROM Users ' |
53 | | - . 'WHERE User.name = @name', |
| 56 | + 'SELECT * FROM Users, UNNEST(Books) as Book ' |
| 57 | + . 'WHERE User.name = @user.name ' |
| 58 | + . 'AND Book.title = @bookTitle', |
54 | 59 | [ |
55 | 60 | 'parameters' => [ |
56 | | - 'name' => $nameValue |
| 61 | + 'user' => $userProto, |
| 62 | + 'bookTitle' => 'Book 1', |
57 | 63 | ], |
58 | 64 | ] |
59 | 65 | ); |
60 | 66 | foreach ($results as $row) { |
61 | 67 | /** @var User $user */ |
62 | | - $user = $row['User']; |
| 68 | + $user = $row['User']->get(); |
| 69 | + // Print the decoded Protobuf message as JSON |
63 | 70 | printf('User: %s' . PHP_EOL, $user->serializeToJsonString()); |
64 | | - /** @var Book $book */ |
| 71 | + /** @var Proto<Book> $book */ |
65 | 72 | foreach ($row['Books'] ?? [] as $book) { |
66 | | - printf('Book: %s' . PHP_EOL, $book->serializeToJsonString()); |
| 73 | + // Print the raw row value |
| 74 | + printf('Book: %s' . PHP_EOL, $book->getValue()); |
67 | 75 | } |
68 | 76 | } |
69 | 77 | // [END spanner_query_data_with_proto_columns] |
|
0 commit comments