Open maxmouchet opened 2 years ago
If I am not mistaken column secret should be declared as: secret: str = Field(sa_column=Column(String)) So specifying type using Type Hinting we should only use types from standard python library.
I recently came across a similar task and came across this question.
I understand that it has been a long time, but it may be useful to someone.
You can use TypeDecorator
from sqlalchemy
(https://docs.sqlalchemy.org/en/20/core/custom_types.html#sqlalchemy.types.TypeDecorator)
It will look something like this
import sqlalchemy as sa
class SecretStrType(sa.types.TypeDecorator):
impl = sa.types.TEXT
def process_bind_param(self, value: SecretStr, dialect):
return value.get_secret_value()
def process_result_value(self, value: str, dialect):
return SecretStr(value)
and full example
from typing import Optional
import sqlalchemy as sa
from pydantic import SecretStr
from sqlmodel import Field, Session, SQLModel, create_engine, select
class SecretStrType(sa.types.TypeDecorator):
impl = sa.types.TEXT
def process_bind_param(self, value: SecretStr, dialect):
return value.get_secret_value()
def process_result_value(self, value: str, dialect):
return SecretStr(value)
class A(SQLModel, table=True):
id: Optional[int] = Field( # type: ignore[call-overload]
title='Идентификатор',
default=None,
primary_key=True,
description='Идентификатор',
)
access_token: SecretStr = Field( # type: ignore[call-overload]
title='Логин',
min_length=5,
max_length=255,
sa_type=SecretStrType(),
nullable=False,
description='Логин',
)
engine = create_engine(url='postgresql://postgres:postgres@localhost:5432/postgres')
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
a = A.model_validate({"id": 1, "access_token": "secret"})
session.add(a)
session.commit()
with Session(engine) as session:
res = session.exec(select(A))
for i in res:
print(f'{i = }')
First Check
Commit to Help
Example Code
Description
pydantic.SecretStr
fieldCan't generate DDL for NullType()
exceptionOperating System
macOS
Operating System Details
No response
SQLModel Version
0.0.4
Python Version
3.9.6
Additional Context
We can specify the column type manually, but it fails with another error: