You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

487 lines
16KB

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