- Install trino client as
pip install trino
. - Set the env vars
TRINO_HOST
,TRINO_PORT
,TRINO_USER
,TRINO_CATALOG
andTRINO_SCHEMA
. - Run as
python3 <file.py>
.
Last active
May 23, 2021 17:26
-
-
Save hashhar/4ea027d6e60149bfd666d37c1c1120d2 to your computer and use it in GitHub Desktop.
Sample Python3 example to run SQL queries concurrently
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import concurrent.futures | |
import os | |
import trino | |
def execute_query(cur, query): | |
cur.execute(query) | |
return cur.fetchall() | |
# Create connection, only one of these is needed | |
conn = trino.dbapi.connect( | |
host=os.getenv("TRINO_HOST", default="localhost"), | |
port=os.getenv("TRINO_PORT", default="8080"), | |
user=os.getenv("TRINO_USER"), | |
catalog=os.getenv("TRINO_CATALOG"), | |
schema=os.getenv("TRINO_SCHEMA"), | |
) | |
queries = ["SELECT * FROM system.runtime.nodes"] * 10 | |
with concurrent.futures.ThreadPoolExecutor() as executor: | |
futures = [] | |
for query in queries: | |
futures.append(executor.submit(execute_query, cur=conn.cursor(), query=query)) | |
for future in concurrent.futures.as_completed(futures): | |
print(future.result()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import trino | |
def write_results_as_csv(cur, query, csv_file): | |
cur.arraysize = 10000 | |
cur.execute(query) | |
with open(csv_file, 'w', newline='') as csvfile: | |
writer = csv.writer(csvfile) | |
rows = cur.fetchmany() | |
# get column names | |
headers = [desc[0] for desc in cur.description] | |
write.writerow(headers) | |
# write rows | |
while len(rows) > 0: | |
writer.writerows(rows) | |
rows = cur.fetchmany() | |
# Create connection, only one of these is needed | |
conn = trino.dbapi.connect( | |
host=os.getenv("TRINO_HOST", default="localhost"), | |
port=os.getenv("TRINO_PORT", default="8080"), | |
user=os.getenv("TRINO_USER"), | |
catalog=os.getenv("TRINO_CATALOG"), | |
schema=os.getenv("TRINO_SCHEMA"), | |
) | |
query = "SELECT * FROM system.runtime.nodes" | |
write_results_as_csv(conn.cursor(), query, 'results.csv') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment