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

Postgres arrays returned as string by sqlalchemy #27

Open
gnuletik opened this issue Oct 26, 2023 · 0 comments
Open

Postgres arrays returned as string by sqlalchemy #27

gnuletik opened this issue Oct 26, 2023 · 0 comments

Comments

@gnuletik
Copy link

Context

Given the following SQL schema

CREATE TYPE public.state AS ENUM (
    'CREATED',
    'RUNNING'
);

CREATE TABLE public.member (
    id uuid DEFAULT public.uuid_generate_v4() NOT NULL,
    states public.state[] DEFAULT ARRAY['CREATED'::public.state] NOT NULL
);

Queries:

-- name: GetMember :one
SELECT * FROM member WHERE id = $1;

sqlc-gen-python generates the following model:

class State(str, enum.Enum):
    CREATED = "CREATED"
    RUNNING = "RUNNING"


@dataclasses.dataclass()
class Member:
    id: uuid.UUID
    states: List[State]

And the following query:

GET_MEMBER = """-- name: get_member \\:one
SELECT id, states FROM member WHERE id = :p1
"""

class Querier:
    def __init__(self, conn: sqlalchemy.engine.Connection):
        self._conn = conn

    def get_member(self, *, member_id: uuid.UUID) -> Optional[models.Member]:
        row = self._conn.execute(sqlalchemy.text(GET_MEMBER), {"p1": member_id}).first()
        if row is None:
            return None
        return models.Member(
            id=row[0],
            states=row[1],
        )

Issue

When using the get_member() method, the states property doesn't have the expected type.
It should be a List[State] but the type is a string of the following format: {CREATED,RUNNING}.

member = queries.get_member(some_uuid)

# the following line is not expected.
type(member.states) # <class 'str'>

Workaround

Our current workaround is to manually parse the string but this would be better handled by SQLAlchemy / SQLC.

It seems that SQLAlchemy supports array types when using the ORM interface:
https://docs.sqlalchemy.org/en/20/dialects/postgresql.html#sqlalchemy.dialects.postgresql.ARRAY
But I'm not sure how to use this with the execute method.

For reference, the List type is generated by sqlc-gen-python:

type pyType struct {
InnerType string
IsArray bool
IsNull bool
}
func (t pyType) Annotation() *pyast.Node {
ann := poet.Name(t.InnerType)
if t.IsArray {
ann = subscriptNode("List", ann)
}
if t.IsNull {
ann = subscriptNode("Optional", ann)
}
return ann
}

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