Skip to content

Commit

Permalink
feat: add Database.list_tables method
Browse files Browse the repository at this point in the history
  • Loading branch information
tswast committed Jan 29, 2021
1 parent bc38664 commit 134f1c8
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
21 changes: 20 additions & 1 deletion google/cloud/spanner_v1/database.py
Expand Up @@ -48,7 +48,8 @@
from google.cloud.spanner_admin_database_v1 import CreateDatabaseRequest
from google.cloud.spanner_admin_database_v1 import UpdateDatabaseDdlRequest
from google.cloud.spanner_v1 import ExecuteSqlRequest
from google.cloud.spanner_v1 import (
from google.cloud.spanner_v1.table import Table
from google.cloud.spanner_v1.proto.transaction_pb2 import (
TransactionSelector,
TransactionOptions,
)
Expand All @@ -67,6 +68,11 @@

_DATABASE_METADATA_FILTER = "name:{0}/operations/"

_LIST_TABLES_QUERY = """SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE SPANNER_STATE = 'COMMITTED'
"""

DEFAULT_RETRY_BACKOFF = Retry(initial=0.02, maximum=32, multiplier=1.3)


Expand Down Expand Up @@ -596,6 +602,19 @@ def list_database_operations(self, filter_="", page_size=None):
filter_=database_filter, page_size=page_size
)

def list_tables(self):
"""List tables within the database.
:type: Iterable
:returns:
Iterable of :class:`~google.cloud.spanner_v1.table.Table`
resources within the current database.
"""
with self.snapshot() as snapshot:
results = snapshot.execute_sql(_LIST_TABLES_QUERY)
for row in results:
yield Table(row[0], self)


class BatchCheckout(object):
"""Context manager for using a batch from a database.
Expand Down
36 changes: 36 additions & 0 deletions google/cloud/spanner_v1/table.py
@@ -0,0 +1,36 @@
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""User friendly container for Cloud Spanner Table."""

_GET_SCHEMA_TEMPLATE = "SELECT * FROM {} LIMIT 0"


class Table(object):
"""Representation of a Cloud Spanner Table.
"""

def __init__(self, table_id, database):
self.table_id = table_id
self._database = database

def get_schema(self):
"""
List of google.cloud.spanner_v1.types.Field
"""
with self._database.snapshot() as snapshot:
query = _GET_SCHEMA_TEMPLATE.format(self.table_id)
results = snapshot.execute_sql(query)
# _ = list(results)
return list(results.fields)

0 comments on commit 134f1c8

Please sign in to comment.