decl_class.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. # ext/mypy/decl_class.py
  2. # Copyright (C) 2021 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. from typing import List
  8. from typing import Optional
  9. from typing import Union
  10. from mypy.nodes import AssignmentStmt
  11. from mypy.nodes import CallExpr
  12. from mypy.nodes import ClassDef
  13. from mypy.nodes import Decorator
  14. from mypy.nodes import LambdaExpr
  15. from mypy.nodes import ListExpr
  16. from mypy.nodes import MemberExpr
  17. from mypy.nodes import NameExpr
  18. from mypy.nodes import PlaceholderNode
  19. from mypy.nodes import RefExpr
  20. from mypy.nodes import StrExpr
  21. from mypy.nodes import SymbolNode
  22. from mypy.nodes import SymbolTableNode
  23. from mypy.nodes import TempNode
  24. from mypy.nodes import TypeInfo
  25. from mypy.nodes import Var
  26. from mypy.plugin import SemanticAnalyzerPluginInterface
  27. from mypy.types import AnyType
  28. from mypy.types import CallableType
  29. from mypy.types import get_proper_type
  30. from mypy.types import Instance
  31. from mypy.types import NoneType
  32. from mypy.types import ProperType
  33. from mypy.types import Type
  34. from mypy.types import TypeOfAny
  35. from mypy.types import UnboundType
  36. from mypy.types import UnionType
  37. from . import apply
  38. from . import infer
  39. from . import names
  40. from . import util
  41. def scan_declarative_assignments_and_apply_types(
  42. cls: ClassDef,
  43. api: SemanticAnalyzerPluginInterface,
  44. is_mixin_scan: bool = False,
  45. ) -> Optional[List[util.SQLAlchemyAttribute]]:
  46. info = util.info_for_cls(cls, api)
  47. if info is None:
  48. # this can occur during cached passes
  49. return None
  50. elif cls.fullname.startswith("builtins"):
  51. return None
  52. mapped_attributes: Optional[
  53. List[util.SQLAlchemyAttribute]
  54. ] = util.get_mapped_attributes(info, api)
  55. # used by assign.add_additional_orm_attributes among others
  56. util.establish_as_sqlalchemy(info)
  57. if mapped_attributes is not None:
  58. # ensure that a class that's mapped is always picked up by
  59. # its mapped() decorator or declarative metaclass before
  60. # it would be detected as an unmapped mixin class
  61. if not is_mixin_scan:
  62. # mypy can call us more than once. it then *may* have reset the
  63. # left hand side of everything, but not the right that we removed,
  64. # removing our ability to re-scan. but we have the types
  65. # here, so lets re-apply them, or if we have an UnboundType,
  66. # we can re-scan
  67. apply.re_apply_declarative_assignments(cls, api, mapped_attributes)
  68. return mapped_attributes
  69. mapped_attributes = []
  70. if not cls.defs.body:
  71. # when we get a mixin class from another file, the body is
  72. # empty (!) but the names are in the symbol table. so use that.
  73. for sym_name, sym in info.names.items():
  74. _scan_symbol_table_entry(
  75. cls, api, sym_name, sym, mapped_attributes
  76. )
  77. else:
  78. for stmt in util.flatten_typechecking(cls.defs.body):
  79. if isinstance(stmt, AssignmentStmt):
  80. _scan_declarative_assignment_stmt(
  81. cls, api, stmt, mapped_attributes
  82. )
  83. elif isinstance(stmt, Decorator):
  84. _scan_declarative_decorator_stmt(
  85. cls, api, stmt, mapped_attributes
  86. )
  87. _scan_for_mapped_bases(cls, api)
  88. if not is_mixin_scan:
  89. apply.add_additional_orm_attributes(cls, api, mapped_attributes)
  90. util.set_mapped_attributes(info, mapped_attributes)
  91. return mapped_attributes
  92. def _scan_symbol_table_entry(
  93. cls: ClassDef,
  94. api: SemanticAnalyzerPluginInterface,
  95. name: str,
  96. value: SymbolTableNode,
  97. attributes: List[util.SQLAlchemyAttribute],
  98. ) -> None:
  99. """Extract mapping information from a SymbolTableNode that's in the
  100. type.names dictionary.
  101. """
  102. value_type = get_proper_type(value.type)
  103. if not isinstance(value_type, Instance):
  104. return
  105. left_hand_explicit_type = None
  106. type_id = names.type_id_for_named_node(value_type.type)
  107. # type_id = names._type_id_for_unbound_type(value.type.type, cls, api)
  108. err = False
  109. # TODO: this is nearly the same logic as that of
  110. # _scan_declarative_decorator_stmt, likely can be merged
  111. if type_id in {
  112. names.MAPPED,
  113. names.RELATIONSHIP,
  114. names.COMPOSITE_PROPERTY,
  115. names.MAPPER_PROPERTY,
  116. names.SYNONYM_PROPERTY,
  117. names.COLUMN_PROPERTY,
  118. }:
  119. if value_type.args:
  120. left_hand_explicit_type = get_proper_type(value_type.args[0])
  121. else:
  122. err = True
  123. elif type_id is names.COLUMN:
  124. if not value_type.args:
  125. err = True
  126. else:
  127. typeengine_arg: Union[ProperType, TypeInfo] = get_proper_type(
  128. value_type.args[0]
  129. )
  130. if isinstance(typeengine_arg, Instance):
  131. typeengine_arg = typeengine_arg.type
  132. if isinstance(typeengine_arg, (UnboundType, TypeInfo)):
  133. sym = api.lookup_qualified(typeengine_arg.name, typeengine_arg)
  134. if sym is not None and isinstance(sym.node, TypeInfo):
  135. if names.has_base_type_id(sym.node, names.TYPEENGINE):
  136. left_hand_explicit_type = UnionType(
  137. [
  138. infer.extract_python_type_from_typeengine(
  139. api, sym.node, []
  140. ),
  141. NoneType(),
  142. ]
  143. )
  144. else:
  145. util.fail(
  146. api,
  147. "Column type should be a TypeEngine "
  148. "subclass not '{}'".format(sym.node.fullname),
  149. value_type,
  150. )
  151. if err:
  152. msg = (
  153. "Can't infer type from attribute {} on class {}. "
  154. "please specify a return type from this function that is "
  155. "one of: Mapped[<python type>], relationship[<target class>], "
  156. "Column[<TypeEngine>], MapperProperty[<python type>]"
  157. )
  158. util.fail(api, msg.format(name, cls.name), cls)
  159. left_hand_explicit_type = AnyType(TypeOfAny.special_form)
  160. if left_hand_explicit_type is not None:
  161. assert value.node is not None
  162. attributes.append(
  163. util.SQLAlchemyAttribute(
  164. name=name,
  165. line=value.node.line,
  166. column=value.node.column,
  167. typ=left_hand_explicit_type,
  168. info=cls.info,
  169. )
  170. )
  171. def _scan_declarative_decorator_stmt(
  172. cls: ClassDef,
  173. api: SemanticAnalyzerPluginInterface,
  174. stmt: Decorator,
  175. attributes: List[util.SQLAlchemyAttribute],
  176. ) -> None:
  177. """Extract mapping information from a @declared_attr in a declarative
  178. class.
  179. E.g.::
  180. @reg.mapped
  181. class MyClass:
  182. # ...
  183. @declared_attr
  184. def updated_at(cls) -> Column[DateTime]:
  185. return Column(DateTime)
  186. Will resolve in mypy as::
  187. @reg.mapped
  188. class MyClass:
  189. # ...
  190. updated_at: Mapped[Optional[datetime.datetime]]
  191. """
  192. for dec in stmt.decorators:
  193. if (
  194. isinstance(dec, (NameExpr, MemberExpr, SymbolNode))
  195. and names.type_id_for_named_node(dec) is names.DECLARED_ATTR
  196. ):
  197. break
  198. else:
  199. return
  200. dec_index = cls.defs.body.index(stmt)
  201. left_hand_explicit_type: Optional[ProperType] = None
  202. if util.name_is_dunder(stmt.name):
  203. # for dunder names like __table_args__, __tablename__,
  204. # __mapper_args__ etc., rewrite these as simple assignment
  205. # statements; otherwise mypy doesn't like if the decorated
  206. # function has an annotation like ``cls: Type[Foo]`` because
  207. # it isn't @classmethod
  208. any_ = AnyType(TypeOfAny.special_form)
  209. left_node = NameExpr(stmt.var.name)
  210. left_node.node = stmt.var
  211. new_stmt = AssignmentStmt([left_node], TempNode(any_))
  212. new_stmt.type = left_node.node.type
  213. cls.defs.body[dec_index] = new_stmt
  214. return
  215. elif isinstance(stmt.func.type, CallableType):
  216. func_type = stmt.func.type.ret_type
  217. if isinstance(func_type, UnboundType):
  218. type_id = names.type_id_for_unbound_type(func_type, cls, api)
  219. else:
  220. # this does not seem to occur unless the type argument is
  221. # incorrect
  222. return
  223. if (
  224. type_id
  225. in {
  226. names.MAPPED,
  227. names.RELATIONSHIP,
  228. names.COMPOSITE_PROPERTY,
  229. names.MAPPER_PROPERTY,
  230. names.SYNONYM_PROPERTY,
  231. names.COLUMN_PROPERTY,
  232. }
  233. and func_type.args
  234. ):
  235. left_hand_explicit_type = get_proper_type(func_type.args[0])
  236. elif type_id is names.COLUMN and func_type.args:
  237. typeengine_arg = func_type.args[0]
  238. if isinstance(typeengine_arg, UnboundType):
  239. sym = api.lookup_qualified(typeengine_arg.name, typeengine_arg)
  240. if sym is not None and isinstance(sym.node, TypeInfo):
  241. if names.has_base_type_id(sym.node, names.TYPEENGINE):
  242. left_hand_explicit_type = UnionType(
  243. [
  244. infer.extract_python_type_from_typeengine(
  245. api, sym.node, []
  246. ),
  247. NoneType(),
  248. ]
  249. )
  250. else:
  251. util.fail(
  252. api,
  253. "Column type should be a TypeEngine "
  254. "subclass not '{}'".format(sym.node.fullname),
  255. func_type,
  256. )
  257. if left_hand_explicit_type is None:
  258. # no type on the decorated function. our option here is to
  259. # dig into the function body and get the return type, but they
  260. # should just have an annotation.
  261. msg = (
  262. "Can't infer type from @declared_attr on function '{}'; "
  263. "please specify a return type from this function that is "
  264. "one of: Mapped[<python type>], relationship[<target class>], "
  265. "Column[<TypeEngine>], MapperProperty[<python type>]"
  266. )
  267. util.fail(api, msg.format(stmt.var.name), stmt)
  268. left_hand_explicit_type = AnyType(TypeOfAny.special_form)
  269. left_node = NameExpr(stmt.var.name)
  270. left_node.node = stmt.var
  271. # totally feeling around in the dark here as I don't totally understand
  272. # the significance of UnboundType. It seems to be something that is
  273. # not going to do what's expected when it is applied as the type of
  274. # an AssignmentStatement. So do a feeling-around-in-the-dark version
  275. # of converting it to the regular Instance/TypeInfo/UnionType structures
  276. # we see everywhere else.
  277. if isinstance(left_hand_explicit_type, UnboundType):
  278. left_hand_explicit_type = get_proper_type(
  279. util.unbound_to_instance(api, left_hand_explicit_type)
  280. )
  281. left_node.node.type = api.named_type(
  282. names.NAMED_TYPE_SQLA_MAPPED, [left_hand_explicit_type]
  283. )
  284. # this will ignore the rvalue entirely
  285. # rvalue = TempNode(AnyType(TypeOfAny.special_form))
  286. # rewrite the node as:
  287. # <attr> : Mapped[<typ>] =
  288. # _sa_Mapped._empty_constructor(lambda: <function body>)
  289. # the function body is maintained so it gets type checked internally
  290. rvalue = util.expr_to_mapped_constructor(
  291. LambdaExpr(stmt.func.arguments, stmt.func.body)
  292. )
  293. new_stmt = AssignmentStmt([left_node], rvalue)
  294. new_stmt.type = left_node.node.type
  295. attributes.append(
  296. util.SQLAlchemyAttribute(
  297. name=left_node.name,
  298. line=stmt.line,
  299. column=stmt.column,
  300. typ=left_hand_explicit_type,
  301. info=cls.info,
  302. )
  303. )
  304. cls.defs.body[dec_index] = new_stmt
  305. def _scan_declarative_assignment_stmt(
  306. cls: ClassDef,
  307. api: SemanticAnalyzerPluginInterface,
  308. stmt: AssignmentStmt,
  309. attributes: List[util.SQLAlchemyAttribute],
  310. ) -> None:
  311. """Extract mapping information from an assignment statement in a
  312. declarative class.
  313. """
  314. lvalue = stmt.lvalues[0]
  315. if not isinstance(lvalue, NameExpr):
  316. return
  317. sym = cls.info.names.get(lvalue.name)
  318. # this establishes that semantic analysis has taken place, which
  319. # means the nodes are populated and we are called from an appropriate
  320. # hook.
  321. assert sym is not None
  322. node = sym.node
  323. if isinstance(node, PlaceholderNode):
  324. return
  325. assert node is lvalue.node
  326. assert isinstance(node, Var)
  327. if node.name == "__abstract__":
  328. if api.parse_bool(stmt.rvalue) is True:
  329. util.set_is_base(cls.info)
  330. return
  331. elif node.name == "__tablename__":
  332. util.set_has_table(cls.info)
  333. elif node.name.startswith("__"):
  334. return
  335. elif node.name == "_mypy_mapped_attrs":
  336. if not isinstance(stmt.rvalue, ListExpr):
  337. util.fail(api, "_mypy_mapped_attrs is expected to be a list", stmt)
  338. else:
  339. for item in stmt.rvalue.items:
  340. if isinstance(item, (NameExpr, StrExpr)):
  341. apply.apply_mypy_mapped_attr(cls, api, item, attributes)
  342. left_hand_mapped_type: Optional[Type] = None
  343. left_hand_explicit_type: Optional[ProperType] = None
  344. if node.is_inferred or node.type is None:
  345. if isinstance(stmt.type, UnboundType):
  346. # look for an explicit Mapped[] type annotation on the left
  347. # side with nothing on the right
  348. # print(stmt.type)
  349. # Mapped?[Optional?[A?]]
  350. left_hand_explicit_type = stmt.type
  351. if stmt.type.name == "Mapped":
  352. mapped_sym = api.lookup_qualified("Mapped", cls)
  353. if (
  354. mapped_sym is not None
  355. and mapped_sym.node is not None
  356. and names.type_id_for_named_node(mapped_sym.node)
  357. is names.MAPPED
  358. ):
  359. left_hand_explicit_type = get_proper_type(
  360. stmt.type.args[0]
  361. )
  362. left_hand_mapped_type = stmt.type
  363. # TODO: do we need to convert from unbound for this case?
  364. # left_hand_explicit_type = util._unbound_to_instance(
  365. # api, left_hand_explicit_type
  366. # )
  367. else:
  368. node_type = get_proper_type(node.type)
  369. if (
  370. isinstance(node_type, Instance)
  371. and names.type_id_for_named_node(node_type.type) is names.MAPPED
  372. ):
  373. # print(node.type)
  374. # sqlalchemy.orm.attributes.Mapped[<python type>]
  375. left_hand_explicit_type = get_proper_type(node_type.args[0])
  376. left_hand_mapped_type = node_type
  377. else:
  378. # print(node.type)
  379. # <python type>
  380. left_hand_explicit_type = node_type
  381. left_hand_mapped_type = None
  382. if isinstance(stmt.rvalue, TempNode) and left_hand_mapped_type is not None:
  383. # annotation without assignment and Mapped is present
  384. # as type annotation
  385. # equivalent to using _infer_type_from_left_hand_type_only.
  386. python_type_for_type = left_hand_explicit_type
  387. elif isinstance(stmt.rvalue, CallExpr) and isinstance(
  388. stmt.rvalue.callee, RefExpr
  389. ):
  390. python_type_for_type = infer.infer_type_from_right_hand_nameexpr(
  391. api, stmt, node, left_hand_explicit_type, stmt.rvalue.callee
  392. )
  393. if python_type_for_type is None:
  394. return
  395. else:
  396. return
  397. assert python_type_for_type is not None
  398. attributes.append(
  399. util.SQLAlchemyAttribute(
  400. name=node.name,
  401. line=stmt.line,
  402. column=stmt.column,
  403. typ=python_type_for_type,
  404. info=cls.info,
  405. )
  406. )
  407. apply.apply_type_to_mapped_statement(
  408. api,
  409. stmt,
  410. lvalue,
  411. left_hand_explicit_type,
  412. python_type_for_type,
  413. )
  414. def _scan_for_mapped_bases(
  415. cls: ClassDef,
  416. api: SemanticAnalyzerPluginInterface,
  417. ) -> None:
  418. """Given a class, iterate through its superclass hierarchy to find
  419. all other classes that are considered as ORM-significant.
  420. Locates non-mapped mixins and scans them for mapped attributes to be
  421. applied to subclasses.
  422. """
  423. info = util.info_for_cls(cls, api)
  424. if info is None:
  425. return
  426. for base_info in info.mro[1:-1]:
  427. if base_info.fullname.startswith("builtins"):
  428. continue
  429. # scan each base for mapped attributes. if they are not already
  430. # scanned (but have all their type info), that means they are unmapped
  431. # mixins
  432. scan_declarative_assignments_and_apply_types(
  433. base_info.defn, api, is_mixin_scan=True
  434. )