1

我目前正在为我的本地开发开发扳手模拟器,最终将使用实际实例。我正在尝试运行一个错误的 SQL 查询,期望捕获并为用户抛出一条错误消息。

当我使用云运行以下查询时,我看到HTTPError

gcloud spanner databases execute-sql --project=local-gcp-project testdb --instance=Emulator --sql='SELECT SingerId, AlbumId, AlbumTitle FROM Albums'

(gcloud.spanner.databases.execute-sql) HTTPError 400: {"error":"Table not found: Albums [at 1:43]\nSELECT SingerId, AlbumId, AlbumTitle FROM Albums\n^","code":3,"message":"Table not found: Albums [at 1:43]\nSELECT SingerId, AlbumId, AlbumTitle FROM Albums\n^"}

当我使用 python 客户端库运行相同的查询时,我没有看到任何错误,而且我看到inside try总是被打印出来。

spanner_client = spanner.Client()
instance = spanner_client.instance("Emulator")
database = instance.database("testdb")

def execute_transaction(transaction):
   query = "SELECT SingerId, AlbumId, AlbumTitle FROM Albums"
   transaction.execute_sql(sql=query)
try:
  database.run_in_transaction(execute_transaction)
  print("inside try")
except GoogleAPICallError as e:
  print("inside e")

知道我可能会错过什么吗?

4

1 回答 1

1

execute_sql返回 a StreamedResultSet,它被懒惰地评估。在您遍历结果之前,您不会看到错误。更改您的示例以将结果集读入列表:

from google.cloud import spanner_v1 as spanner
from google.api_core.exceptions import GoogleAPICallError

spanner_client = spanner.Client()
instance = spanner_client.instance("Emulator")
database = instance.database("testdb")

def execute_transaction(transaction):
    query = "SELECT SingerId, AlbumId, AlbumTitle FROM Albums"
    return list(transaction.execute_sql(sql=query))

try:
    database.run_in_transaction(execute_transaction)
    print("inside try")  # never gets here
except GoogleAPICallError as ex:
    print(ex)  # 400 Table not found: Albums...
于 2021-02-24T19:02:22.417 回答