|
1 | | -from typing import Annotated, Optional |
| 1 | +from typing import Annotated, Literal, Optional, Union |
2 | 2 |
|
3 | 3 | import pytest |
| 4 | +from sqlalchemy import text |
4 | 5 | from sqlalchemy.exc import IntegrityError |
5 | 6 | from sqlalchemy.orm import RelationshipProperty |
6 | 7 | from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select |
@@ -216,3 +217,147 @@ class Hero(SQLModel, table=True): |
216 | 217 | assert len(foreign_keys) == 1 |
217 | 218 | assert foreign_keys[0].ondelete == "CASCADE" |
218 | 219 | assert team_id_column.nullable is False |
| 220 | + |
| 221 | + |
| 222 | +def test_literal_valid_values(clear_sqlmodel, caplog): |
| 223 | + """Test https://github.com/fastapi/sqlmodel/issues/57""" |
| 224 | + |
| 225 | + class Model(SQLModel, table=True): |
| 226 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 227 | + all_str: Literal["a", "b", "c"] |
| 228 | + mixed: Literal["yes", "no", 1, 0] |
| 229 | + all_int: Literal[1, 2, 3] |
| 230 | + int_bool: Literal[0, 1, True, False] |
| 231 | + all_bool: Literal[True, False] |
| 232 | + |
| 233 | + obj = Model( |
| 234 | + all_str="a", |
| 235 | + mixed="yes", |
| 236 | + all_int=1, |
| 237 | + int_bool=True, |
| 238 | + all_bool=False, |
| 239 | + ) |
| 240 | + |
| 241 | + engine = create_engine("sqlite://", echo=True) |
| 242 | + |
| 243 | + SQLModel.metadata.create_all(engine) |
| 244 | + |
| 245 | + # Check DDL |
| 246 | + assert "all_str VARCHAR NOT NULL" in caplog.text |
| 247 | + assert "mixed VARCHAR NOT NULL" in caplog.text |
| 248 | + assert "all_int INTEGER NOT NULL" in caplog.text |
| 249 | + assert "int_bool INTEGER NOT NULL" in caplog.text |
| 250 | + assert "all_bool BOOLEAN NOT NULL" in caplog.text |
| 251 | + |
| 252 | + # Check query |
| 253 | + with Session(engine) as session: |
| 254 | + session.add(obj) |
| 255 | + session.commit() |
| 256 | + session.refresh(obj) |
| 257 | + assert isinstance(obj.all_str, str) |
| 258 | + assert obj.all_str == "a" |
| 259 | + assert isinstance(obj.mixed, str) |
| 260 | + assert obj.mixed == "yes" |
| 261 | + assert isinstance(obj.all_int, int) |
| 262 | + assert obj.all_int == 1 |
| 263 | + assert isinstance(obj.int_bool, int) |
| 264 | + assert obj.int_bool == 1 |
| 265 | + assert isinstance(obj.all_bool, bool) |
| 266 | + assert obj.all_bool is False |
| 267 | + |
| 268 | + |
| 269 | +def test_literal_constraints_invalid_values(clear_sqlmodel): |
| 270 | + """DB should reject values that are not part of the Literal choices.""" |
| 271 | + |
| 272 | + class Model(SQLModel, table=True): |
| 273 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 274 | + all_str: Literal["a", "b", "c"] |
| 275 | + mixed: Literal["yes", "no", 1, 0] |
| 276 | + all_int: Literal[1, 2, 3] |
| 277 | + int_bool: Literal[0, 1, True, False] |
| 278 | + all_bool: Literal[True, False] |
| 279 | + |
| 280 | + engine = create_engine("sqlite://") |
| 281 | + SQLModel.metadata.create_all(engine) |
| 282 | + |
| 283 | + # Helper to attempt a raw insert that bypasses Pydantic validation so we |
| 284 | + # can verify that the database-level CHECK constraints are enforced. |
| 285 | + def insert_raw(values: dict[str, object]) -> None: |
| 286 | + stmt = text( |
| 287 | + "INSERT INTO model (all_str, mixed, all_int, int_bool, all_bool) " |
| 288 | + "VALUES (:all_str, :mixed, :all_int, :int_bool, :all_bool)" |
| 289 | + ).bindparams(**values) |
| 290 | + with pytest.raises(IntegrityError): |
| 291 | + with Session(engine) as session: |
| 292 | + session.exec(stmt) |
| 293 | + session.commit() |
| 294 | + |
| 295 | + # Invalid string literal for all_str |
| 296 | + insert_raw( |
| 297 | + { |
| 298 | + "all_str": "z", # invalid, not in {"a","b","c"} |
| 299 | + "mixed": "yes", |
| 300 | + "all_int": 1, |
| 301 | + "int_bool": 1, |
| 302 | + "all_bool": 0, |
| 303 | + } |
| 304 | + ) |
| 305 | + |
| 306 | + # Invalid int literal for all_int |
| 307 | + insert_raw( |
| 308 | + { |
| 309 | + "all_str": "a", |
| 310 | + "mixed": "yes", |
| 311 | + "all_int": 5, # invalid, not in {1,2,3} |
| 312 | + "int_bool": 1, |
| 313 | + "all_bool": 0, |
| 314 | + } |
| 315 | + ) |
| 316 | + |
| 317 | + # Invalid bool literal for all_bool |
| 318 | + insert_raw( |
| 319 | + { |
| 320 | + "all_str": "a", |
| 321 | + "mixed": "yes", |
| 322 | + "all_int": 1, |
| 323 | + "int_bool": 1, |
| 324 | + "all_bool": 2, # invalid boolean value |
| 325 | + } |
| 326 | + ) |
| 327 | + |
| 328 | + |
| 329 | +def test_literal_optional_and_union_constraints(clear_sqlmodel): |
| 330 | + """Literals inside Optional/Union should also be enforced at the DB level.""" |
| 331 | + |
| 332 | + class Model(SQLModel, table=True): |
| 333 | + id: Optional[int] = Field(default=None, primary_key=True) |
| 334 | + opt_str: Optional[Literal["x", "y"]] = None |
| 335 | + union_int: Union[Literal[10, 20], None] = None |
| 336 | + |
| 337 | + engine = create_engine("sqlite://") |
| 338 | + SQLModel.metadata.create_all(engine) |
| 339 | + |
| 340 | + # Valid values should be accepted |
| 341 | + obj = Model(opt_str="x", union_int=10) |
| 342 | + with Session(engine) as session: |
| 343 | + session.add(obj) |
| 344 | + session.commit() |
| 345 | + session.refresh(obj) |
| 346 | + assert obj.opt_str == "x" |
| 347 | + assert obj.union_int == 10 |
| 348 | + |
| 349 | + # Invalid values should be rejected by the database |
| 350 | + def insert_raw(values: dict[str, object]) -> None: |
| 351 | + stmt = text( |
| 352 | + "INSERT INTO model (opt_str, union_int) VALUES (:opt_str, :union_int)" |
| 353 | + ).bindparams(**values) |
| 354 | + with pytest.raises(IntegrityError): |
| 355 | + with Session(engine) as session: |
| 356 | + session.exec(stmt) |
| 357 | + session.commit() |
| 358 | + |
| 359 | + # opt_str not in {"x", "y"} |
| 360 | + insert_raw({"opt_str": "z", "union_int": 10}) |
| 361 | + |
| 362 | + # union_int not in {10, 20} |
| 363 | + insert_raw({"opt_str": "x", "union_int": 30}) |
0 commit comments