Skip to content

Commit 9830ee0

Browse files
van51tiangolo
andauthored
🐛 Fix setting nullable property of Fields that don't accept None (#79)
Co-authored-by: Sebastián Ramírez <[email protected]>
1 parent 2407ecd commit 9830ee0

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

sqlmodel/main.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626
from pydantic import BaseConfig, BaseModel
2727
from pydantic.errors import ConfigError, DictError
28+
from pydantic.fields import SHAPE_SINGLETON
2829
from pydantic.fields import FieldInfo as PydanticFieldInfo
2930
from pydantic.fields import ModelField, Undefined, UndefinedType
3031
from pydantic.main import ModelMetaclass, validate_model
@@ -424,14 +425,14 @@ def get_column_from_field(field: ModelField) -> Column: # type: ignore
424425
return sa_column
425426
sa_type = get_sqlachemy_type(field)
426427
primary_key = getattr(field.field_info, "primary_key", False)
427-
nullable = not field.required
428428
index = getattr(field.field_info, "index", Undefined)
429429
if index is Undefined:
430430
index = False
431431
if hasattr(field.field_info, "nullable"):
432432
field_nullable = getattr(field.field_info, "nullable")
433433
if field_nullable != Undefined:
434434
nullable = field_nullable
435+
nullable = not primary_key and _is_field_nullable(field)
435436
args = []
436437
foreign_key = getattr(field.field_info, "foreign_key", None)
437438
if foreign_key:
@@ -646,3 +647,13 @@ def _calculate_keys(
646647
@declared_attr # type: ignore
647648
def __tablename__(cls) -> str:
648649
return cls.__name__.lower()
650+
651+
652+
def _is_field_nullable(field: ModelField) -> bool:
653+
if not field.required:
654+
# Taken from [Pydantic](https://github.com/samuelcolvin/pydantic/blob/v1.8.2/pydantic/fields.py#L946-L947)
655+
is_optional = field.allow_none and (
656+
field.shape != SHAPE_SINGLETON or not field.sub_fields
657+
)
658+
return is_optional and field.default is None and field.default_factory is None
659+
return False

tests/test_tutorial/test_create_db_and_table/test_tutorial001.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ def test_create_db_and_table(cov_tmp_path: Path):
99
assert "BEGIN" in result.stdout
1010
assert 'PRAGMA main.table_info("hero")' in result.stdout
1111
assert "CREATE TABLE hero (" in result.stdout
12-
assert "id INTEGER," in result.stdout
12+
assert "id INTEGER NOT NULL," in result.stdout
1313
assert "name VARCHAR NOT NULL," in result.stdout
1414
assert "secret_name VARCHAR NOT NULL," in result.stdout
1515
assert "age INTEGER," in result.stdout

0 commit comments

Comments
 (0)