Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connection examples: SQLalchemy boilerplate #102

Open
chuck-alt-delete opened this issue Feb 29, 2024 · 1 comment
Open

Connection examples: SQLalchemy boilerplate #102

chuck-alt-delete opened this issue Feb 29, 2024 · 1 comment

Comments

@chuck-alt-delete
Copy link
Contributor

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()
@chuck-alt-delete
Copy link
Contributor Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant