@@ -41,12 +41,16 @@ def process_mapped_attributes(dct):
4141 mapped_attrs = {}
4242 for name , annotation in dct .get ("__annotations__" , {}).items ():
4343 primary_key = False
44+ nullable = None
4445 if annotation .__class__ is t ._AnnotatedAlias :
4546 primary_key = PrimaryKeyColumn in getattr (annotation , "__metadata__" , ())
4647 annotation = annotation .__args__ [0 ]
48+ if annotation .__class__ is t .Optional :
49+ annotation = annotation .__args__ [0 ]
50+ nullable = True
4751 if name not in dct :
4852 # create column object for annotations with no default values
49- dct [name ] = mapped_attrs [name ] = Column (name , annotation , primary_key = primary_key )
53+ dct [name ] = mapped_attrs [name ] = Column (name , annotation , primary_key = primary_key , nullable = nullable )
5054 elif isinstance (dct [name ], Column ):
5155 mapped_attrs [name ] = dct [name ]
5256 if dct [name ].type is None :
@@ -112,6 +116,10 @@ def create_mapper(cls, mapped_attrs=None):
112116 if mapped_attrs :
113117 cls .__mapper__ .map (mapped_attrs )
114118
119+ for col in cls .__mapper__ .columns :
120+ if col .nullable is None :
121+ col .nullable = cls .Meta .columns_default_nullable
122+
115123 cls .c = cls .__mapper__ .columns # handy shortcut
116124
117125 auto_primary_key = cls .Meta .auto_primary_key
@@ -120,7 +128,9 @@ def create_mapper(cls, mapped_attrs=None):
120128 # we force the usage of SELECT * as we auto add a primary key without any other mapped columns
121129 # without doing this, only the primary key would be selected
122130 cls .__mapper__ .force_select_wildcard = True
123- cls .__mapper__ .map (auto_primary_key , Column (auto_primary_key , type = cls .Meta .auto_primary_key_type , primary_key = True ))
131+ pk_column = Column (auto_primary_key , type = cls .Meta .auto_primary_key_type , primary_key = True , nullable = False )
132+ cls .__mapper__ .map (auto_primary_key , pk_column )
133+ setattr (cls , auto_primary_key , pk_column )
124134
125135 @staticmethod
126136 def process_meta_inheritance (cls ):
@@ -340,6 +350,7 @@ class Meta:
340350 )
341351 auto_primary_key_type : SQLType = Integer
342352 allow_unknown_columns : bool = True # hydrate() will set attributes for unknown columns
353+ columns_default_nullable : bool = True
343354
344355 @classmethod
345356 def bind (cls , engine : Engine ):
@@ -349,6 +360,9 @@ def bind(cls, engine: Engine):
349360 (cls , abc .ABC ),
350361 {"__engine__" : engine , "__model_registry__" : ModelRegistry ()},
351362 )
363+
364+ def __sql__ (self ):
365+ return self .table .name
352366
353367
354368class Model (BaseModel , abc .ABC ):
0 commit comments