cuddly-jelly-27016
04/16/2025, 9:28 AMinvalid dsn: invalid connection option "username"
Issue created by HansBambel
### Describe the bug
I am having an issue using the SQLAlchemyTask for getting data from redshift. Initially, I thought the issue is in getting the secrets, but I was able to run the same query using a PythonTask.
from datetime import datetime
from functools import wraps
import flytekit as fl
import polars as pl
from flytekit import kwtypes, workflow, task
from flytekit.types.schema import FlyteSchema
from flytekitplugins.sqlalchemy import SQLAlchemyConfig, SQLAlchemyTask
from src.workflows.default_flyte_types import default_image, project_task
default_image = fl.ImageSpec(
registry="localhost:30000", name="personalization-ml", platform="linux/arm64", requirements="uv.lock"
)
@wraps(task)
def project_task(*args, **kwargs):
def decorator(func):
# Combine your pre-filled param with any extra ones passed in
return task(*args, container_image=default_image, retries=3, **kwargs)(func)
return decorator
secrets = {
"username": fl.Secret(key="username", group="redshift"),
"password": fl.Secret(key="password", group="redshift"),
"host": fl.Secret(key="host", group="redshift"),
"database": fl.Secret(key="database", group="redshift"),
}
WusDataSchema = FlyteSchema[kwtypes(play_time=datetime, content_id=str, score=float, result=str, plugin_name=str)]
sql_query = """select play_time, content_id, score, result, plugin_name from personalization.wus_with_plugin_names limit 1000"""
learners_sql = SQLAlchemyTask(
"wus",
query_template=sql_query,
task_config=SQLAlchemyConfig(
uri="redshift+psycopg2//{username}{password}@{host}:5439/{database}",
secret_connect_args=secrets,
),
secret_requests=[*secrets.values()],
output_schema_type=WusDataSchema,
container_image=default_image,
)
@project_task(secret_requests=[*secrets.values()])
def get_learners_polars() -> pl.DataFrame:
"""Get the learners data from Redshift."""
secrets = fl.current_context().secrets
username = secrets.get("redshift", "username")
password = secrets.get("redshift", "password")
host = secrets.get("redshift", "host")
database = secrets.get("redshift", "database")
learners_df = pl.read_database_uri(
query=sql_query,
uri=f"redshift+psycopg2//{username}{password}@{host}:5439/{database}",
)
return learners_df
@project_task()
def get_mean_score_sql(data: WusDataSchema) -> float:
"""Get the mean score from the WUS data."""
df = data.open().all()
return df["score"].mean().item()
@project_task()
def get_mean_score(data: pl.DataFrame) -> float:
"""Get the mean score from the WUS data."""
return data["score"].mean()
@workflow()
def get_data_from_redshift() -> float:
learners_data = learners_sql()
get_mean_score_sql(learners_data)
learners_data_polars = get_learners_polars()
mean_score_polars = get_mean_score(learners_data_polars)
return mean_score_polars
The error that I get from the SQLAlchemyTask is the following:
ProgrammingError: (psycopg2.ProgrammingError) invalid dsn: invalid connection option "username"
I have installed the required packages and I am using my docker image that contains these:
• flytekitplugins-sqlalchemy
• sqlalchemy-redshift
• psycopg2-binary
Is the problem maybe how the uri=f"redshift+psycopg2://{username}:{password}@{host}:5439/{database}" looks like? In the docs under "Using secrets in task templates" the example just shows
SQLAlchemyConfig(
uri="<DATABASE_URI>",
secret_connect_args=secrets,
),
which I don't think is sufficient as the driver is missing.
Interestingly, when I use the secrets directly I get another error (which could also be a separate issue):
File "/root/.venv/lib/python3.11/site-packages/pandas/io/sql.py", line 2670, in execute
raise TypeError("Query must be a string unless using sqlalchemy.")
TypeError: Query must be a string unless using sqlalchemy.
The query that is used is in string-format, so I don't see the issue here. Seeing that the error is coming from a pandas call, am I correct in assuming that SQLAlchemyTask is just a wrapper for pandas?
### Expected behavior
The SQLAlchemyTask to be able to connect to the database and return data from it.
### Additional context to reproduce
I also noticed that the SQLAlchemyTask
### Screenshots
[Image](https://private-user-images.githubusercontent.com/9060786/434247962-985d3718-e7a4-4592-abde-c78987a6976c.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NDQ3OTYwMjksIm5iZiI6MTc0NDc5NTcyOSwicGF0aCI6Ii85MDYwNzg2LzQzNDI0Nzk2Mi05ODVkMzcxOC1lN2E0LTQ1OTItYWJkZS1jNzg5ODdhNjk3NmMucG5nP1gtQW16LUFsZ29yaXRobT1BV1M0LUhNQUMtU0hBMjU2JlgtQW16LUNyZWRlbnRpYWw9QUtJQVZDT0RZTFNBNTNQUUs0WkElMkYyMDI1MDQxNiUyRnVzLWVhc3QtMSUyRnMzJTJGYXdzNF9yZXF1ZXN0JlgtQW16LURhdGU9MjAyNTA0MTZUMDkyODQ5WiZYLUFtei1FeHBpcmVzPTMwMCZYLUFtei1TaWduYXR1cmU9ZmUyNGEwZjA3OTk2MzNkOTliZDgxYTM5MmNjYWEzM2ZkNWFlMDFkZmQ2NWUwYTUwNTdiZTUwZWFhYTFhMDk5MyZYLUFtei1TaWduZWRIZWFkZXJzPWhvc3QifQ.L7WFL1sfO-blplW2Y2ysSUGC0C55vqG5sedEyefnbsQ)
### Are you sure this issue hasn't been raised already?
• Yes
### Have you read the Code of Conduct?
• Yes
flyteorg/flyte