Skip to content

Commit 83870d1

Browse files
committed
🎨 Fix nullable property of Fields
1 parent 02da85c commit 83870d1

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
@@ -26,6 +26,7 @@
2626

2727
from pydantic import BaseModel
2828
from pydantic.errors import ConfigError, DictError
29+
from pydantic.fields import SHAPE_SINGLETON
2930
from pydantic.fields import FieldInfo as PydanticFieldInfo
3031
from pydantic.fields import ModelField, Undefined, UndefinedType
3132
from pydantic.main import BaseConfig, ModelMetaclass, validate_model
@@ -414,7 +415,7 @@ def get_column_from_field(field: ModelField) -> Column:
414415
return sa_column
415416
sa_type = get_sqlachemy_type(field)
416417
primary_key = getattr(field.field_info, "primary_key", False)
417-
nullable = not field.required
418+
nullable = not primary_key and _is_field_nullable(field)
418419
index = getattr(field.field_info, "index", Undefined)
419420
if index is Undefined:
420421
index = True
@@ -634,3 +635,13 @@ def _calculate_keys( # type: ignore
634635
@declared_attr # type: ignore
635636
def __tablename__(cls) -> str:
636637
return cls.__name__.lower()
638+
639+
640+
def _is_field_nullable(field: ModelField) -> bool:
641+
if not field.required:
642+
# Taken from [Pydantic](https://github.com/samuelcolvin/pydantic/blob/v1.8.2/pydantic/fields.py#L946-L947)
643+
is_optional = field.allow_none and (
644+
field.shape != SHAPE_SINGLETON or not field.sub_fields
645+
)
646+
return is_optional and field.default is None and field.default_factory is None
647+
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)