MaterializeInc / demos

Demos of Materialize, the operational data warehouse.

Home Page:https://materialize.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Connection examples: SQLalchemy boilerplate

chuck-alt-delete opened this issue · comments

Here is some basic boilerplate for connecting to Materialize via SQLalchemy.

from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
from dotenv import dotenv_values
from pathlib import Path
from sqlalchemy import URL


path_to_env = Path(__file__).parent.absolute() / ".env"
# Load values from .env file into config dictionary.
# See example.env for what variables you need to define.
config = dotenv_values(path_to_env)

config["options"] = ''
if config["MZ_CLUSTER"]:
    config["options"] += f'--cluster={config["MZ_CLUSTER"]}'
else:
    config["options"] += '--cluster=quickstart'

if config["MZ_TRANSACTION_ISOLATION"]:
    config["options"] += f' -c transaction_isolation={config["MZ_TRANSACTION_ISOLATION"]}'

if config["MZ_SCHEMA"]:
    config["options"] += f' -c search_path={config["MZ_SCHEMA"]}'


url = URL.create(
    "postgresql+psycopg2",
    database=config["MZ_DB"],
    username=config["MZ_USER"],
    password=config["MZ_PASSWORD"],
    host=config["MZ_HOST"],
    port=6875,
    query={
        "sslmode": "require",
        "application_name": "sqlalchemy app",
        "options": config["options"]
    }
)

# Create an engine and metadata
engine = create_engine(
    url=url,
    # avoid wrapping queries in transactions
    isolation_level="AUTOCOMMIT")

# Create a new session
Session = sessionmaker(bind=engine)
session = Session()

conn = session.connection()
result = conn.execute(text('select * from t'))

# Fetch all rows from the result (if you want to print the rows)
rows = result.fetchall()
for row in rows:
    print(row)

# Close the session
session.close()

I made a more organized repo that we can link to: