orm.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  1. from collections import OrderedDict
  2. from functools import partial
  3. from inspect import isclass
  4. from operator import attrgetter
  5. import six
  6. import sqlalchemy as sa
  7. from sqlalchemy.engine.interfaces import Dialect
  8. from sqlalchemy.ext.hybrid import hybrid_property
  9. from sqlalchemy.orm import mapperlib
  10. from sqlalchemy.orm.attributes import InstrumentedAttribute
  11. from sqlalchemy.orm.exc import UnmappedInstanceError
  12. from sqlalchemy.orm.properties import ColumnProperty, RelationshipProperty
  13. try:
  14. from sqlalchemy.orm.context import _ColumnEntity, _MapperEntity
  15. except ImportError: # SQLAlchemy <1.4
  16. from sqlalchemy.orm.query import _ColumnEntity, _MapperEntity
  17. from sqlalchemy.orm.session import object_session
  18. from sqlalchemy.orm.util import AliasedInsp
  19. from ..utils import is_sequence
  20. def get_class_by_table(base, table, data=None):
  21. """
  22. Return declarative class associated with given table. If no class is found
  23. this function returns `None`. If multiple classes were found (polymorphic
  24. cases) additional `data` parameter can be given to hint which class
  25. to return.
  26. ::
  27. class User(Base):
  28. __tablename__ = 'entity'
  29. id = sa.Column(sa.Integer, primary_key=True)
  30. name = sa.Column(sa.String)
  31. get_class_by_table(Base, User.__table__) # User class
  32. This function also supports models using single table inheritance.
  33. Additional data paratemer should be provided in these case.
  34. ::
  35. class Entity(Base):
  36. __tablename__ = 'entity'
  37. id = sa.Column(sa.Integer, primary_key=True)
  38. name = sa.Column(sa.String)
  39. type = sa.Column(sa.String)
  40. __mapper_args__ = {
  41. 'polymorphic_on': type,
  42. 'polymorphic_identity': 'entity'
  43. }
  44. class User(Entity):
  45. __mapper_args__ = {
  46. 'polymorphic_identity': 'user'
  47. }
  48. # Entity class
  49. get_class_by_table(Base, Entity.__table__, {'type': 'entity'})
  50. # User class
  51. get_class_by_table(Base, Entity.__table__, {'type': 'user'})
  52. :param base: Declarative model base
  53. :param table: SQLAlchemy Table object
  54. :param data: Data row to determine the class in polymorphic scenarios
  55. :return: Declarative class or None.
  56. """
  57. found_classes = set(
  58. c for c in _get_class_registry(base).values()
  59. if hasattr(c, '__table__') and c.__table__ is table
  60. )
  61. if len(found_classes) > 1:
  62. if not data:
  63. raise ValueError(
  64. "Multiple declarative classes found for table '{0}'. "
  65. "Please provide data parameter for this function to be able "
  66. "to determine polymorphic scenarios.".format(
  67. table.name
  68. )
  69. )
  70. else:
  71. for cls in found_classes:
  72. mapper = sa.inspect(cls)
  73. polymorphic_on = mapper.polymorphic_on.name
  74. if polymorphic_on in data:
  75. if data[polymorphic_on] == mapper.polymorphic_identity:
  76. return cls
  77. raise ValueError(
  78. "Multiple declarative classes found for table '{0}'. Given "
  79. "data row does not match any polymorphic identity of the "
  80. "found classes.".format(
  81. table.name
  82. )
  83. )
  84. elif found_classes:
  85. return found_classes.pop()
  86. return None
  87. def get_type(expr):
  88. """
  89. Return the associated type with given Column, InstrumentedAttribute,
  90. ColumnProperty, RelationshipProperty or other similar SQLAlchemy construct.
  91. For constructs wrapping columns this is the column type. For relationships
  92. this function returns the relationship mapper class.
  93. :param expr:
  94. SQLAlchemy Column, InstrumentedAttribute, ColumnProperty or other
  95. similar SA construct.
  96. ::
  97. class User(Base):
  98. __tablename__ = 'user'
  99. id = sa.Column(sa.Integer, primary_key=True)
  100. name = sa.Column(sa.String)
  101. class Article(Base):
  102. __tablename__ = 'article'
  103. id = sa.Column(sa.Integer, primary_key=True)
  104. author_id = sa.Column(sa.Integer, sa.ForeignKey(User.id))
  105. author = sa.orm.relationship(User)
  106. get_type(User.__table__.c.name) # sa.String()
  107. get_type(User.name) # sa.String()
  108. get_type(User.name.property) # sa.String()
  109. get_type(Article.author) # User
  110. .. versionadded: 0.30.9
  111. """
  112. if hasattr(expr, 'type'):
  113. return expr.type
  114. elif isinstance(expr, InstrumentedAttribute):
  115. expr = expr.property
  116. if isinstance(expr, ColumnProperty):
  117. return expr.columns[0].type
  118. elif isinstance(expr, RelationshipProperty):
  119. return expr.mapper.class_
  120. raise TypeError("Couldn't inspect type.")
  121. def cast_if(expression, type_):
  122. """
  123. Produce a CAST expression but only if given expression is not of given type
  124. already.
  125. Assume we have a model with two fields id (Integer) and name (String).
  126. ::
  127. import sqlalchemy as sa
  128. from sqlalchemy_utils import cast_if
  129. cast_if(User.id, sa.Integer) # "user".id
  130. cast_if(User.name, sa.String) # "user".name
  131. cast_if(User.id, sa.String) # CAST("user".id AS TEXT)
  132. This function supports scalar values as well.
  133. ::
  134. cast_if(1, sa.Integer) # 1
  135. cast_if('text', sa.String) # 'text'
  136. cast_if(1, sa.String) # CAST(1 AS TEXT)
  137. :param expression:
  138. A SQL expression, such as a ColumnElement expression or a Python string
  139. which will be coerced into a bound literal value.
  140. :param type_:
  141. A TypeEngine class or instance indicating the type to which the CAST
  142. should apply.
  143. .. versionadded: 0.30.14
  144. """
  145. try:
  146. expr_type = get_type(expression)
  147. except TypeError:
  148. expr_type = expression
  149. check_type = type_().python_type
  150. else:
  151. check_type = type_
  152. return (
  153. sa.cast(expression, type_)
  154. if not isinstance(expr_type, check_type)
  155. else expression
  156. )
  157. def get_column_key(model, column):
  158. """
  159. Return the key for given column in given model.
  160. :param model: SQLAlchemy declarative model object
  161. ::
  162. class User(Base):
  163. __tablename__ = 'user'
  164. id = sa.Column(sa.Integer, primary_key=True)
  165. name = sa.Column('_name', sa.String)
  166. get_column_key(User, User.__table__.c._name) # 'name'
  167. .. versionadded: 0.26.5
  168. .. versionchanged: 0.27.11
  169. Throws UnmappedColumnError instead of ValueError when no property was
  170. found for given column. This is consistent with how SQLAlchemy works.
  171. """
  172. mapper = sa.inspect(model)
  173. try:
  174. return mapper.get_property_by_column(column).key
  175. except sa.orm.exc.UnmappedColumnError:
  176. for key, c in mapper.columns.items():
  177. if c.name == column.name and c.table is column.table:
  178. return key
  179. raise sa.orm.exc.UnmappedColumnError(
  180. 'No column %s is configured on mapper %s...' %
  181. (column, mapper)
  182. )
  183. def get_mapper(mixed):
  184. """
  185. Return related SQLAlchemy Mapper for given SQLAlchemy object.
  186. :param mixed: SQLAlchemy Table / Alias / Mapper / declarative model object
  187. ::
  188. from sqlalchemy_utils import get_mapper
  189. get_mapper(User)
  190. get_mapper(User())
  191. get_mapper(User.__table__)
  192. get_mapper(User.__mapper__)
  193. get_mapper(sa.orm.aliased(User))
  194. get_mapper(sa.orm.aliased(User.__table__))
  195. Raises:
  196. ValueError: if multiple mappers were found for given argument
  197. .. versionadded: 0.26.1
  198. """
  199. if isinstance(mixed, _MapperEntity):
  200. mixed = mixed.expr
  201. elif isinstance(mixed, sa.Column):
  202. mixed = mixed.table
  203. elif isinstance(mixed, _ColumnEntity):
  204. mixed = mixed.expr
  205. if isinstance(mixed, sa.orm.Mapper):
  206. return mixed
  207. if isinstance(mixed, sa.orm.util.AliasedClass):
  208. return sa.inspect(mixed).mapper
  209. if isinstance(mixed, sa.sql.selectable.Alias):
  210. mixed = mixed.element
  211. if isinstance(mixed, AliasedInsp):
  212. return mixed.mapper
  213. if isinstance(mixed, sa.orm.attributes.InstrumentedAttribute):
  214. mixed = mixed.class_
  215. if isinstance(mixed, sa.Table):
  216. if hasattr(mapperlib, '_all_registries'):
  217. all_mappers = set()
  218. for mapper_registry in mapperlib._all_registries():
  219. all_mappers.update(mapper_registry.mappers)
  220. else: # SQLAlchemy <1.4
  221. all_mappers = mapperlib._mapper_registry
  222. mappers = [
  223. mapper for mapper in all_mappers
  224. if mixed in mapper.tables
  225. ]
  226. if len(mappers) > 1:
  227. raise ValueError(
  228. "Multiple mappers found for table '%s'." % mixed.name
  229. )
  230. elif not mappers:
  231. raise ValueError(
  232. "Could not get mapper for table '%s'." % mixed.name
  233. )
  234. else:
  235. return mappers[0]
  236. if not isclass(mixed):
  237. mixed = type(mixed)
  238. return sa.inspect(mixed)
  239. def get_bind(obj):
  240. """
  241. Return the bind for given SQLAlchemy Engine / Connection / declarative
  242. model object.
  243. :param obj: SQLAlchemy Engine / Connection / declarative model object
  244. ::
  245. from sqlalchemy_utils import get_bind
  246. get_bind(session) # Connection object
  247. get_bind(user)
  248. """
  249. if hasattr(obj, 'bind'):
  250. conn = obj.bind
  251. else:
  252. try:
  253. conn = object_session(obj).bind
  254. except UnmappedInstanceError:
  255. conn = obj
  256. if not hasattr(conn, 'execute'):
  257. raise TypeError(
  258. 'This method accepts only Session, Engine, Connection and '
  259. 'declarative model objects.'
  260. )
  261. return conn
  262. def get_primary_keys(mixed):
  263. """
  264. Return an OrderedDict of all primary keys for given Table object,
  265. declarative class or declarative class instance.
  266. :param mixed:
  267. SA Table object, SA declarative class or SA declarative class instance
  268. ::
  269. get_primary_keys(User)
  270. get_primary_keys(User())
  271. get_primary_keys(User.__table__)
  272. get_primary_keys(User.__mapper__)
  273. get_primary_keys(sa.orm.aliased(User))
  274. get_primary_keys(sa.orm.aliased(User.__table__))
  275. .. versionchanged: 0.25.3
  276. Made the function return an ordered dictionary instead of generator.
  277. This change was made to support primary key aliases.
  278. Renamed this function to 'get_primary_keys', formerly 'primary_keys'
  279. .. seealso:: :func:`get_columns`
  280. """
  281. return OrderedDict(
  282. (
  283. (key, column) for key, column in get_columns(mixed).items()
  284. if column.primary_key
  285. )
  286. )
  287. def get_tables(mixed):
  288. """
  289. Return a set of tables associated with given SQLAlchemy object.
  290. Let's say we have three classes which use joined table inheritance
  291. TextItem, Article and BlogPost. Article and BlogPost inherit TextItem.
  292. ::
  293. get_tables(Article) # set([Table('article', ...), Table('text_item')])
  294. get_tables(Article())
  295. get_tables(Article.__mapper__)
  296. If the TextItem entity is using with_polymorphic='*' then this function
  297. returns all child tables (article and blog_post) as well.
  298. ::
  299. get_tables(TextItem) # set([Table('text_item', ...)], ...])
  300. .. versionadded: 0.26.0
  301. :param mixed:
  302. SQLAlchemy Mapper, Declarative class, Column, InstrumentedAttribute or
  303. a SA Alias object wrapping any of these objects.
  304. """
  305. if isinstance(mixed, sa.Table):
  306. return [mixed]
  307. elif isinstance(mixed, sa.Column):
  308. return [mixed.table]
  309. elif isinstance(mixed, sa.orm.attributes.InstrumentedAttribute):
  310. return mixed.parent.tables
  311. elif isinstance(mixed, _ColumnEntity):
  312. mixed = mixed.expr
  313. mapper = get_mapper(mixed)
  314. polymorphic_mappers = get_polymorphic_mappers(mapper)
  315. if polymorphic_mappers:
  316. tables = sum((m.tables for m in polymorphic_mappers), [])
  317. else:
  318. tables = mapper.tables
  319. return tables
  320. def get_columns(mixed):
  321. """
  322. Return a collection of all Column objects for given SQLAlchemy
  323. object.
  324. The type of the collection depends on the type of the object to return the
  325. columns from.
  326. ::
  327. get_columns(User)
  328. get_columns(User())
  329. get_columns(User.__table__)
  330. get_columns(User.__mapper__)
  331. get_columns(sa.orm.aliased(User))
  332. get_columns(sa.orm.alised(User.__table__))
  333. :param mixed:
  334. SA Table object, SA Mapper, SA declarative class, SA declarative class
  335. instance or an alias of any of these objects
  336. """
  337. if isinstance(mixed, sa.sql.selectable.Selectable):
  338. try:
  339. return mixed.selected_columns
  340. except AttributeError: # SQLAlchemy <1.4
  341. return mixed.c
  342. if isinstance(mixed, sa.orm.util.AliasedClass):
  343. return sa.inspect(mixed).mapper.columns
  344. if isinstance(mixed, sa.orm.Mapper):
  345. return mixed.columns
  346. if isinstance(mixed, InstrumentedAttribute):
  347. return mixed.property.columns
  348. if isinstance(mixed, ColumnProperty):
  349. return mixed.columns
  350. if isinstance(mixed, sa.Column):
  351. return [mixed]
  352. if not isclass(mixed):
  353. mixed = mixed.__class__
  354. return sa.inspect(mixed).columns
  355. def table_name(obj):
  356. """
  357. Return table name of given target, declarative class or the
  358. table name where the declarative attribute is bound to.
  359. """
  360. class_ = getattr(obj, 'class_', obj)
  361. try:
  362. return class_.__tablename__
  363. except AttributeError:
  364. pass
  365. try:
  366. return class_.__table__.name
  367. except AttributeError:
  368. pass
  369. def getattrs(obj, attrs):
  370. return map(partial(getattr, obj), attrs)
  371. def quote(mixed, ident):
  372. """
  373. Conditionally quote an identifier.
  374. ::
  375. from sqlalchemy_utils import quote
  376. engine = create_engine('sqlite:///:memory:')
  377. quote(engine, 'order')
  378. # '"order"'
  379. quote(engine, 'some_other_identifier')
  380. # 'some_other_identifier'
  381. :param mixed: SQLAlchemy Session / Connection / Engine / Dialect object.
  382. :param ident: identifier to conditionally quote
  383. """
  384. if isinstance(mixed, Dialect):
  385. dialect = mixed
  386. else:
  387. dialect = get_bind(mixed).dialect
  388. return dialect.preparer(dialect).quote(ident)
  389. def _get_query_compile_state(query):
  390. if hasattr(query, '_compile_state'):
  391. return query._compile_state()
  392. else: # SQLAlchemy <1.4
  393. return query
  394. def get_polymorphic_mappers(mixed):
  395. if isinstance(mixed, AliasedInsp):
  396. return mixed.with_polymorphic_mappers
  397. else:
  398. return mixed.polymorphic_map.values()
  399. def get_descriptor(entity, attr):
  400. mapper = sa.inspect(entity)
  401. for key, descriptor in get_all_descriptors(mapper).items():
  402. if attr == key:
  403. prop = (
  404. descriptor.property
  405. if hasattr(descriptor, 'property')
  406. else None
  407. )
  408. if isinstance(prop, ColumnProperty):
  409. if isinstance(entity, sa.orm.util.AliasedClass):
  410. for c in mapper.selectable.c:
  411. if c.key == attr:
  412. return c
  413. else:
  414. # If the property belongs to a class that uses
  415. # polymorphic inheritance we have to take into account
  416. # situations where the attribute exists in child class
  417. # but not in parent class.
  418. return getattr(prop.parent.class_, attr)
  419. else:
  420. # Handle synonyms, relationship properties and hybrid
  421. # properties
  422. if isinstance(entity, sa.orm.util.AliasedClass):
  423. return getattr(entity, attr)
  424. try:
  425. return getattr(mapper.class_, attr)
  426. except AttributeError:
  427. pass
  428. def get_all_descriptors(expr):
  429. if isinstance(expr, sa.sql.selectable.Selectable):
  430. return expr.c
  431. insp = sa.inspect(expr)
  432. try:
  433. polymorphic_mappers = get_polymorphic_mappers(insp)
  434. except sa.exc.NoInspectionAvailable:
  435. return get_mapper(expr).all_orm_descriptors
  436. else:
  437. attrs = dict(get_mapper(expr).all_orm_descriptors)
  438. for submapper in polymorphic_mappers:
  439. for key, descriptor in submapper.all_orm_descriptors.items():
  440. if key not in attrs:
  441. attrs[key] = descriptor
  442. return attrs
  443. def get_hybrid_properties(model):
  444. """
  445. Returns a dictionary of hybrid property keys and hybrid properties for
  446. given SQLAlchemy declarative model / mapper.
  447. Consider the following model
  448. ::
  449. from sqlalchemy.ext.hybrid import hybrid_property
  450. class Category(Base):
  451. __tablename__ = 'category'
  452. id = sa.Column(sa.Integer, primary_key=True)
  453. name = sa.Column(sa.Unicode(255))
  454. @hybrid_property
  455. def lowercase_name(self):
  456. return self.name.lower()
  457. @lowercase_name.expression
  458. def lowercase_name(cls):
  459. return sa.func.lower(cls.name)
  460. You can now easily get a list of all hybrid property names
  461. ::
  462. from sqlalchemy_utils import get_hybrid_properties
  463. get_hybrid_properties(Category).keys() # ['lowercase_name']
  464. This function also supports aliased classes
  465. ::
  466. get_hybrid_properties(
  467. sa.orm.aliased(Category)
  468. ).keys() # ['lowercase_name']
  469. .. versionchanged: 0.26.7
  470. This function now returns a dictionary instead of generator
  471. .. versionchanged: 0.30.15
  472. Added support for aliased classes
  473. :param model: SQLAlchemy declarative model or mapper
  474. """
  475. return dict(
  476. (key, prop)
  477. for key, prop in get_mapper(model).all_orm_descriptors.items()
  478. if isinstance(prop, hybrid_property)
  479. )
  480. def get_declarative_base(model):
  481. """
  482. Returns the declarative base for given model class.
  483. :param model: SQLAlchemy declarative model
  484. """
  485. for parent in model.__bases__:
  486. try:
  487. parent.metadata
  488. return get_declarative_base(parent)
  489. except AttributeError:
  490. pass
  491. return model
  492. def getdotattr(obj_or_class, dot_path, condition=None):
  493. """
  494. Allow dot-notated strings to be passed to `getattr`.
  495. ::
  496. getdotattr(SubSection, 'section.document')
  497. getdotattr(subsection, 'section.document')
  498. :param obj_or_class: Any object or class
  499. :param dot_path: Attribute path with dot mark as separator
  500. """
  501. last = obj_or_class
  502. for path in str(dot_path).split('.'):
  503. getter = attrgetter(path)
  504. if is_sequence(last):
  505. tmp = []
  506. for element in last:
  507. value = getter(element)
  508. if is_sequence(value):
  509. tmp.extend(value)
  510. else:
  511. tmp.append(value)
  512. last = tmp
  513. elif isinstance(last, InstrumentedAttribute):
  514. last = getter(last.property.mapper.class_)
  515. elif last is None:
  516. return None
  517. else:
  518. last = getter(last)
  519. if condition is not None:
  520. if is_sequence(last):
  521. last = [v for v in last if condition(v)]
  522. else:
  523. if not condition(last):
  524. return None
  525. return last
  526. def is_deleted(obj):
  527. return obj in sa.orm.object_session(obj).deleted
  528. def has_changes(obj, attrs=None, exclude=None):
  529. """
  530. Simple shortcut function for checking if given attributes of given
  531. declarative model object have changed during the session. Without
  532. parameters this checks if given object has any modificiations. Additionally
  533. exclude parameter can be given to check if given object has any changes
  534. in any attributes other than the ones given in exclude.
  535. ::
  536. from sqlalchemy_utils import has_changes
  537. user = User()
  538. has_changes(user, 'name') # False
  539. user.name = u'someone'
  540. has_changes(user, 'name') # True
  541. has_changes(user) # True
  542. You can check multiple attributes as well.
  543. ::
  544. has_changes(user, ['age']) # True
  545. has_changes(user, ['name', 'age']) # True
  546. This function also supports excluding certain attributes.
  547. ::
  548. has_changes(user, exclude=['name']) # False
  549. has_changes(user, exclude=['age']) # True
  550. .. versionchanged: 0.26.6
  551. Added support for multiple attributes and exclude parameter.
  552. :param obj: SQLAlchemy declarative model object
  553. :param attrs: Names of the attributes
  554. :param exclude: Names of the attributes to exclude
  555. """
  556. if attrs:
  557. if isinstance(attrs, six.string_types):
  558. return (
  559. sa.inspect(obj)
  560. .attrs
  561. .get(attrs)
  562. .history
  563. .has_changes()
  564. )
  565. else:
  566. return any(has_changes(obj, attr) for attr in attrs)
  567. else:
  568. if exclude is None:
  569. exclude = []
  570. return any(
  571. attr.history.has_changes()
  572. for key, attr in sa.inspect(obj).attrs.items()
  573. if key not in exclude
  574. )
  575. def is_loaded(obj, prop):
  576. """
  577. Return whether or not given property of given object has been loaded.
  578. ::
  579. class Article(Base):
  580. __tablename__ = 'article'
  581. id = sa.Column(sa.Integer, primary_key=True)
  582. name = sa.Column(sa.String)
  583. content = sa.orm.deferred(sa.Column(sa.String))
  584. article = session.query(Article).get(5)
  585. # name gets loaded since its not a deferred property
  586. assert is_loaded(article, 'name')
  587. # content has not yet been loaded since its a deferred property
  588. assert not is_loaded(article, 'content')
  589. .. versionadded: 0.27.8
  590. :param obj: SQLAlchemy declarative model object
  591. :param prop: Name of the property or InstrumentedAttribute
  592. """
  593. return not isinstance(
  594. getattr(sa.inspect(obj).attrs, prop).loaded_value,
  595. sa.util.langhelpers._symbol
  596. )
  597. def identity(obj_or_class):
  598. """
  599. Return the identity of given sqlalchemy declarative model class or instance
  600. as a tuple. This differs from obj._sa_instance_state.identity in a way that
  601. it always returns the identity even if object is still in transient state (
  602. new object that is not yet persisted into database). Also for classes it
  603. returns the identity attributes.
  604. ::
  605. from sqlalchemy import inspect
  606. from sqlalchemy_utils import identity
  607. user = User(name=u'John Matrix')
  608. session.add(user)
  609. identity(user) # None
  610. inspect(user).identity # None
  611. session.flush() # User now has id but is still in transient state
  612. identity(user) # (1,)
  613. inspect(user).identity # None
  614. session.commit()
  615. identity(user) # (1,)
  616. inspect(user).identity # (1, )
  617. You can also use identity for classes::
  618. identity(User) # (User.id, )
  619. .. versionadded: 0.21.0
  620. :param obj: SQLAlchemy declarative model object
  621. """
  622. return tuple(
  623. getattr(obj_or_class, column_key)
  624. for column_key in get_primary_keys(obj_or_class).keys()
  625. )
  626. def naturally_equivalent(obj, obj2):
  627. """
  628. Returns whether or not two given SQLAlchemy declarative instances are
  629. naturally equivalent (all their non primary key properties are equivalent).
  630. ::
  631. from sqlalchemy_utils import naturally_equivalent
  632. user = User(name=u'someone')
  633. user2 = User(name=u'someone')
  634. user == user2 # False
  635. naturally_equivalent(user, user2) # True
  636. :param obj: SQLAlchemy declarative model object
  637. :param obj2: SQLAlchemy declarative model object to compare with `obj`
  638. """
  639. for column_key, column in sa.inspect(obj.__class__).columns.items():
  640. if column.primary_key:
  641. continue
  642. if not (getattr(obj, column_key) == getattr(obj2, column_key)):
  643. return False
  644. return True
  645. def _get_class_registry(class_):
  646. try:
  647. return class_.registry._class_registry
  648. except AttributeError: # SQLAlchemy <1.4
  649. return class_._decl_class_registry