Search code examples
google-cloud-spanner

Cloud Spanner - Read rows, but no returned columns?


Is there a possibility to return column names with the data that is returned?

For example https://cloud.google.com/spanner/docs/reads#single_read_methods:

def query_data(instance_id, database_id):
    """Queries sample data from the database using SQL."""
    spanner_client = spanner.Client()
    instance = spanner_client.instance(instance_id)
    database = instance.database(database_id)

    with database.snapshot() as snapshot:
        results = snapshot.execute_sql(
            'SELECT SingerId, AlbumId, AlbumTitle FROM Albums')

        for row in results:
            print(u'SingerId: {}, AlbumId: {}, AlbumTitle: {}'.format(*row))

The row variable does not carry any information regarding the columns?


Solution

  • Figured what the problem is.

    When you first execute the query and then immediately read the fields without getting any rows, then the fields attribute fails without giving a warning.

    You need to read one row so the internal parameter

    _meta_data

    gets populated with data.