Sub topic 16
Running SQL on a warehouse from code
This chapter assumes you can write basic SQL, have run queries in the SQL editor, and know what a SQL warehouse is. You also need a workspace URL, a warehouse ID, and a personal access token or another credential that is allowed to use the warehouse.
The Statement Execution API
The editor is not the only way to use a warehouse. The Statement Execution API accepts a SQL statement over HTTPS, runs it on the warehouse you name, and returns the result as JSON. Use it from scripts, services, and tools that have no JDBC or ODBC driver available.
The warehouse must be running. If it is stopped, it starts automatically, so the first call after auto stop can be slow.
Submit a statement
curl -X POST "$DATABRICKS_HOST/api/2.0/sql/statements" \
-H "Authorization: Bearer $DATABRICKS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"warehouse_id": "'"$WAREHOUSE_ID"'",
"statement": "SELECT COUNT(*) FROM samples.nyctaxi.trips",
"wait_timeout": "30s"
}'wait_timeout sets how long the call blocks before returning. It accepts 0s or a value from 5s to 50s. If the statement finishes in time, the response contains the rows in result.data_array. If it does not, the response contains a statement_id and a state of PENDING or RUNNING. By default the statement then keeps running, because on_wait_timeout defaults to CONTINUE. Set it to CANCEL to stop the statement instead.
Poll until the statement finishes
The states are PENDING, RUNNING, SUCCEEDED, FAILED, CANCELED, and CLOSED. Only the last four are final. This Python script submits a statement and polls it.
import os
import time
import requests
host = os.environ["DATABRICKS_HOST"]
headers = {"Authorization": f"Bearer {os.environ['DATABRICKS_TOKEN']}"}
body = {
"warehouse_id": os.environ["WAREHOUSE_ID"],
"statement": "SELECT pickup_zip, trip_distance, fare_amount "
"FROM samples.nyctaxi.trips "
"WHERE trip_distance > :min_distance "
"ORDER BY fare_amount DESC LIMIT 5",
"parameters": [
{"name": "min_distance", "value": "10", "type": "DOUBLE"}
],
"wait_timeout": "10s",
}
resp = requests.post(f"{host}/api/2.0/sql/statements", headers=headers, json=body)
resp.raise_for_status()
result = resp.json()
while result["status"]["state"] in ("PENDING", "RUNNING"):
time.sleep(2)
resp = requests.get(
f"{host}/api/2.0/sql/statements/{result['statement_id']}", headers=headers
)
resp.raise_for_status()
result = resp.json()
if result["status"]["state"] == "SUCCEEDED":
for row in result["result"]["data_array"]:
print(row)
else:
print(result["status"].get("error"))The parameters list uses the same :name markers you met in the editor. Values are sent separately from the statement text, so you never build SQL by string concatenation.
Limits and gotchas
- Every value in
data_arrayis a string. Use the column types inmanifest.schemato convert them. - With the default
INLINEdisposition, results are limited to 25 MiB. For larger results, set"disposition": "EXTERNAL_LINKS"and download the chunks from the returned presigned URLs. - Result data is available for a limited time after the statement finishes. Fetch it promptly.
- Cancel a statement you no longer need with
POST /api/2.0/sql/statements/{id}/cancel.
Exercise
Your POST call returns state RUNNING with a statementid, although you set waittimeout to 10s. What happened, and what do you do next?
Show answer
The statement did not finish within 10 seconds. Because onwaittimeout defaults to CONTINUE, it is still running on the warehouse. Call GET /api/2.0/sql/statements/{statementid} repeatedly until the state is SUCCEEDED, FAILED, CANCELED, or CLOSED, then read result.dataarray if it succeeded.