diff --git a/gcloud/bigtable/happybase/connection.py b/gcloud/bigtable/happybase/connection.py index 1dc07271391d..7391d170472d 100644 --- a/gcloud/bigtable/happybase/connection.py +++ b/gcloud/bigtable/happybase/connection.py @@ -234,3 +234,32 @@ def table(self, name, use_prefix=True): if use_prefix: name = self._table_name(name) return Table(name, self) + + def tables(self): + """Return a list of table names available to this connection. + + .. note:: + + This lists every table in the cluster owned by this connection, + **not** every table that a given user may have access to. + + .. note:: + + If ``table_prefix`` is set on this connection, only returns the + table names which match that prefix. + + :rtype: list + :returns: List of string table names. + """ + low_level_table_instances = self._cluster.list_tables() + table_names = [table_instance.table_id + for table_instance in low_level_table_instances] + + # Filter using prefix, and strip prefix from names + if self.table_prefix is not None: + prefix = self._table_name('') + offset = len(prefix) + table_names = [name[offset:] for name in table_names + if name.startswith(prefix)] + + return table_names diff --git a/gcloud/bigtable/happybase/test_connection.py b/gcloud/bigtable/happybase/test_connection.py index 14a8ea4b25aa..ef1ac49298d3 100644 --- a/gcloud/bigtable/happybase/test_connection.py +++ b/gcloud/bigtable/happybase/test_connection.py @@ -278,6 +278,39 @@ def test_table_factory_with_prefix(self): def test_table_factory_with_ignored_prefix(self): self._table_factory_prefix_helper(use_prefix=False) + def test_tables(self): + from gcloud.bigtable.table import Table + + table_name1 = 'table-name1' + table_name2 = 'table-name2' + cluster = _Cluster(list_tables_result=[ + Table(table_name1, None), + Table(table_name2, None), + ]) + connection = self._makeOne(autoconnect=False, cluster=cluster) + result = connection.tables() + self.assertEqual(result, [table_name1, table_name2]) + + def test_tables_with_prefix(self): + from gcloud.bigtable.table import Table + + table_prefix = 'prefix' + table_prefix_separator = '<>' + unprefixed_table_name1 = 'table-name1' + + table_name1 = (table_prefix + table_prefix_separator + + unprefixed_table_name1) + table_name2 = 'table-name2' + cluster = _Cluster(list_tables_result=[ + Table(table_name1, None), + Table(table_name2, None), + ]) + connection = self._makeOne( + autoconnect=False, cluster=cluster, table_prefix=table_prefix, + table_prefix_separator=table_prefix_separator) + result = connection.tables() + self.assertEqual(result, [unprefixed_table_name1]) + class _Client(object): @@ -316,3 +349,6 @@ def copy(self): return result else: return self + + def list_tables(self): + return self.list_tables_result