diff --git a/spanner/cloud-client/snippets.py b/spanner/cloud-client/snippets.py index 7e6dd79db3a3..61e5aff59509 100644 --- a/spanner/cloud-client/snippets.py +++ b/spanner/cloud-client/snippets.py @@ -119,6 +119,27 @@ def read_data(instance_id, database_id): print(u'SingerId: {}, AlbumId: {}, AlbumTitle: {}'.format(*row)) +def read_stale_data(instance_id, database_id): + """Reads sample data from the database. The data is exactly 10 seconds + stale.""" + import datetime + + spanner_client = spanner.Client() + instance = spanner_client.instance(instance_id) + database = instance.database(database_id) + staleness = datetime.timedelta(seconds=10) + + with database.snapshot(exact_staleness=staleness) as snapshot: + keyset = spanner.KeySet(all_=True) + results = snapshot.read( + table='Albums', + columns=('SingerId', 'AlbumId', 'AlbumTitle',), + keyset=keyset) + + for row in results: + print(u'SingerId: {}, AlbumId: {}, AlbumTitle: {}'.format(*row)) + + def query_data_with_new_column(instance_id, database_id): """Queries sample data from the database using SQL. @@ -424,6 +445,7 @@ def read_only_transaction(instance_id, database_id): subparsers.add_parser('insert_data', help=insert_data.__doc__) subparsers.add_parser('query_data', help=query_data.__doc__) subparsers.add_parser('read_data', help=read_data.__doc__) + subparsers.add_parser('read_stale_data', help=read_stale_data.__doc__) subparsers.add_parser('add_column', help=add_column.__doc__) subparsers.add_parser('update_data', help=update_data.__doc__) subparsers.add_parser( @@ -454,6 +476,8 @@ def read_only_transaction(instance_id, database_id): query_data(args.instance_id, args.database_id) elif args.command == 'read_data': read_data(args.instance_id, args.database_id) + elif args.command == 'read_stale_data': + read_stale_data(args.instance_id, args.database_id) elif args.command == 'add_column': add_column(args.instance_id, args.database_id) elif args.command == 'update_data': diff --git a/spanner/cloud-client/snippets_test.py b/spanner/cloud-client/snippets_test.py index 8a50e0714819..3a1912e05534 100644 --- a/spanner/cloud-client/snippets_test.py +++ b/spanner/cloud-client/snippets_test.py @@ -73,6 +73,17 @@ def test_read_data(temporary_database, capsys): assert 'Total Junk' in out +def test_read_stale_data(temporary_database, capsys): + snippets.read_stale_data(SPANNER_INSTANCE, temporary_database.database_id) + + out, _ = capsys.readouterr() + + # It shouldn't be in the output because it was *just* inserted by the + # temporary database fixture and this sample reads 10 seconds into the + # past. + assert 'Total Junk' not in out + + @pytest.fixture(scope='module') def temporary_database_with_column(temporary_database): snippets.add_column(SPANNER_INSTANCE, temporary_database.database_id)