kvesteri / sqlalchemy-utils

Various utility functions and datatypes for SQLAlchemy.
Other
1.23k stars 317 forks source link

LTreeType and LTree with the new version of sqlalchemy #697

Open caufman opened 1 year ago

caufman commented 1 year ago

Library version 0.40.0, sqlalchemy 2.0.4 Created this model:

from sqlalchemy_utils import Ltree

class Node(Base):
    __tablename__ = 'nodes'

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[Ltree] = mapped_column(nullable=False)

As a result of running the code I have these errors:

sqlalchemy.exc.ArgumentError: Could not locate SQLAlchemy Core type for Python type <class 'sqlalchemy_utils.primitives.ltree.Ltree'> inside the 'name' attribute Mapped annotation

sqlalchemy.exc.ArgumentError: The type provided inside the 'name' attribute Mapped annotation is the SQLAlchemy type <class 'sqlalchemy_utils.types.ltree.LtreeType'>. Expected a Python type instead

How to use LTreeType and LTree types correctly with the new version of sqlalchemy? It looks like the documentation hasn't been updated yet.

BBArikL commented 12 months ago

Library version 0.41.1, sqlalchemy 2.0.18

I did not try LTree but it is quite strange that it would not work since it is a primitive type and not a sqlalchemy type. Password and PhoneNumber seems to work.

For the persons that are looking for a current syntax with sqlalchemy 2.0+: (If it can also help for the documentation)

from phonenumbers import PhoneNumber
from sqlalchemy_utils import EmailType, PhoneNumberType, PasswordType, Password

class User(Base):
    __tablename__ = 'user'

    id: Mapped[int] = mapped_column(primary_key=True)
    password: Mapped[Password] = mapped_column(PasswordType(schemes=['pbkdf2_sha512']))
    email: Mapped[str] = mapped_column(EmailType)
    phone: Mapped[PhoneNumber] = mapped_column(PhoneNumberType)

However, EmailType only makes the email be a lower-case value which is a little bit disappointing. I might open a issue for this but it would be great to use email-validator as an extra, just like phonenumber.

aleksilahis commented 10 months ago

Any update on this? I got the same issue with SQLAlchem v2.0.19 and SQLAlchemy-Utils v0.41.1. If I specify the column as @BBArikL instructed: path: Mapped[Ltree] = mapped_column(LtreeType, nullable=True) I get the following error: AttributeError: 'LtreeType' object has no attribute '_variant_mapping'.

aleksilahis commented 10 months ago

Any update on this? I got the same issue with SQLAlchem v2.0.19 and SQLAlchemy-Utils v0.41.1. If I specify the column as @BBArikL instructed: path: Mapped[Ltree] = mapped_column(LtreeType, nullable=True) I get the following error: AttributeError: 'LtreeType' object has no attribute '_variant_mapping'.

This was my bad. My local setup was still pointing to old version of SQLAlchemy. So I can confirm that this indeed works like this:

path: Mapped[Ltree] = mapped_column(LtreeType)