/
session.py
4440 lines (3515 loc) · 159 KB
/
session.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# orm/session.py
# Copyright (C) 2005-2024 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""Provides the Session class and related utilities."""
import itertools
import sys
import weakref
from . import attributes
from . import context
from . import exc
from . import identity
from . import loading
from . import persistence
from . import query
from . import state as statelib
from .base import _class_to_mapper
from .base import _none_set
from .base import _state_mapper
from .base import instance_str
from .base import object_mapper
from .base import object_state
from .base import state_str
from .unitofwork import UOWTransaction
from .. import engine
from .. import exc as sa_exc
from .. import sql
from .. import util
from ..engine.util import TransactionalContext
from ..inspection import inspect
from ..sql import coercions
from ..sql import dml
from ..sql import roles
from ..sql import visitors
from ..sql.base import CompileState
from ..sql.selectable import LABEL_STYLE_TABLENAME_PLUS_COL
__all__ = [
"Session",
"SessionTransaction",
"sessionmaker",
"ORMExecuteState",
"close_all_sessions",
"make_transient",
"make_transient_to_detached",
"object_session",
]
_sessions = weakref.WeakValueDictionary()
"""Weak-referencing dictionary of :class:`.Session` objects.
"""
statelib._sessions = _sessions
def _state_session(state):
"""Given an :class:`.InstanceState`, return the :class:`.Session`
associated, if any.
"""
return state.session
class _SessionClassMethods(object):
"""Class-level methods for :class:`.Session`, :class:`.sessionmaker`."""
@classmethod
@util.deprecated(
"1.3",
"The :meth:`.Session.close_all` method is deprecated and will be "
"removed in a future release. Please refer to "
":func:`.session.close_all_sessions`.",
)
def close_all(cls):
"""Close *all* sessions in memory."""
close_all_sessions()
@classmethod
@util.preload_module("sqlalchemy.orm.util")
def identity_key(cls, *args, **kwargs):
"""Return an identity key.
This is an alias of :func:`.util.identity_key`.
"""
return util.preloaded.orm_util.identity_key(*args, **kwargs)
@classmethod
def object_session(cls, instance):
"""Return the :class:`.Session` to which an object belongs.
This is an alias of :func:`.object_session`.
"""
return object_session(instance)
ACTIVE = util.symbol("ACTIVE")
PREPARED = util.symbol("PREPARED")
COMMITTED = util.symbol("COMMITTED")
DEACTIVE = util.symbol("DEACTIVE")
CLOSED = util.symbol("CLOSED")
class ORMExecuteState(util.MemoizedSlots):
"""Represents a call to the :meth:`_orm.Session.execute` method, as passed
to the :meth:`.SessionEvents.do_orm_execute` event hook.
.. versionadded:: 1.4
.. seealso::
:ref:`session_execute_events` - top level documentation on how
to use :meth:`_orm.SessionEvents.do_orm_execute`
"""
__slots__ = (
"session",
"statement",
"parameters",
"execution_options",
"local_execution_options",
"bind_arguments",
"_compile_state_cls",
"_starting_event_idx",
"_events_todo",
"_update_execution_options",
)
def __init__(
self,
session,
statement,
parameters,
execution_options,
bind_arguments,
compile_state_cls,
events_todo,
):
self.session = session
self.statement = statement
self.parameters = parameters
self.local_execution_options = execution_options
self.execution_options = statement._execution_options.union(
execution_options
)
self.bind_arguments = bind_arguments
self._compile_state_cls = compile_state_cls
self._events_todo = list(events_todo)
def _remaining_events(self):
return self._events_todo[self._starting_event_idx + 1 :]
def invoke_statement(
self,
statement=None,
params=None,
execution_options=None,
bind_arguments=None,
):
"""Execute the statement represented by this
:class:`.ORMExecuteState`, without re-invoking events that have
already proceeded.
This method essentially performs a re-entrant execution of the current
statement for which the :meth:`.SessionEvents.do_orm_execute` event is
being currently invoked. The use case for this is for event handlers
that want to override how the ultimate
:class:`_engine.Result` object is returned, such as for schemes that
retrieve results from an offline cache or which concatenate results
from multiple executions.
When the :class:`_engine.Result` object is returned by the actual
handler function within :meth:`_orm.SessionEvents.do_orm_execute` and
is propagated to the calling
:meth:`_orm.Session.execute` method, the remainder of the
:meth:`_orm.Session.execute` method is preempted and the
:class:`_engine.Result` object is returned to the caller of
:meth:`_orm.Session.execute` immediately.
:param statement: optional statement to be invoked, in place of the
statement currently represented by :attr:`.ORMExecuteState.statement`.
:param params: optional dictionary of parameters which will be merged
into the existing :attr:`.ORMExecuteState.parameters` of this
:class:`.ORMExecuteState`.
:param execution_options: optional dictionary of execution options
will be merged into the existing
:attr:`.ORMExecuteState.execution_options` of this
:class:`.ORMExecuteState`.
:param bind_arguments: optional dictionary of bind_arguments
which will be merged amongst the current
:attr:`.ORMExecuteState.bind_arguments`
of this :class:`.ORMExecuteState`.
:return: a :class:`_engine.Result` object with ORM-level results.
.. seealso::
:ref:`do_orm_execute_re_executing` - background and examples on the
appropriate usage of :meth:`_orm.ORMExecuteState.invoke_statement`.
"""
if statement is None:
statement = self.statement
_bind_arguments = dict(self.bind_arguments)
if bind_arguments:
_bind_arguments.update(bind_arguments)
_bind_arguments["_sa_skip_events"] = True
if params:
_params = dict(self.parameters)
_params.update(params)
else:
_params = self.parameters
_execution_options = self.local_execution_options
if execution_options:
_execution_options = _execution_options.union(execution_options)
return self.session.execute(
statement,
_params,
_execution_options,
_bind_arguments,
_parent_execute_state=self,
)
@property
def bind_mapper(self):
"""Return the :class:`_orm.Mapper` that is the primary "bind" mapper.
For an :class:`_orm.ORMExecuteState` object invoking an ORM
statement, that is, the :attr:`_orm.ORMExecuteState.is_orm_statement`
attribute is ``True``, this attribute will return the
:class:`_orm.Mapper` that is considered to be the "primary" mapper
of the statement. The term "bind mapper" refers to the fact that
a :class:`_orm.Session` object may be "bound" to multiple
:class:`_engine.Engine` objects keyed to mapped classes, and the
"bind mapper" determines which of those :class:`_engine.Engine` objects
would be selected.
For a statement that is invoked against a single mapped class,
:attr:`_orm.ORMExecuteState.bind_mapper` is intended to be a reliable
way of getting this mapper.
.. versionadded:: 1.4.0b2
.. seealso::
:attr:`_orm.ORMExecuteState.all_mappers`
"""
return self.bind_arguments.get("mapper", None)
@property
def all_mappers(self):
"""Return a sequence of all :class:`_orm.Mapper` objects that are
involved at the top level of this statement.
By "top level" we mean those :class:`_orm.Mapper` objects that would
be represented in the result set rows for a :func:`_sql.select`
query, or for a :func:`_dml.update` or :func:`_dml.delete` query,
the mapper that is the main subject of the UPDATE or DELETE.
.. versionadded:: 1.4.0b2
.. seealso::
:attr:`_orm.ORMExecuteState.bind_mapper`
"""
if not self.is_orm_statement:
return []
elif self.is_select:
result = []
seen = set()
for d in self.statement.column_descriptions:
ent = d["entity"]
if ent:
insp = inspect(ent, raiseerr=False)
if insp and insp.mapper and insp.mapper not in seen:
seen.add(insp.mapper)
result.append(insp.mapper)
return result
elif self.is_update or self.is_delete:
return [self.bind_mapper]
else:
return []
@property
def is_orm_statement(self):
"""return True if the operation is an ORM statement.
This indicates that the select(), update(), or delete() being
invoked contains ORM entities as subjects. For a statement
that does not have ORM entities and instead refers only to
:class:`.Table` metadata, it is invoked as a Core SQL statement
and no ORM-level automation takes place.
"""
return self._compile_state_cls is not None
@property
def is_select(self):
"""return True if this is a SELECT operation."""
return self.statement.is_select
@property
def is_insert(self):
"""return True if this is an INSERT operation."""
return self.statement.is_dml and self.statement.is_insert
@property
def is_update(self):
"""return True if this is an UPDATE operation."""
return self.statement.is_dml and self.statement.is_update
@property
def is_delete(self):
"""return True if this is a DELETE operation."""
return self.statement.is_dml and self.statement.is_delete
@property
def _is_crud(self):
return isinstance(self.statement, (dml.Update, dml.Delete))
def update_execution_options(self, **opts):
# TODO: no coverage
self.local_execution_options = self.local_execution_options.union(opts)
def _orm_compile_options(self):
if not self.is_select:
return None
try:
opts = self.statement._compile_options
except AttributeError:
return None
if opts.isinstance(context.ORMCompileState.default_compile_options):
return opts
else:
return None
@property
def lazy_loaded_from(self):
"""An :class:`.InstanceState` that is using this statement execution
for a lazy load operation.
The primary rationale for this attribute is to support the horizontal
sharding extension, where it is available within specific query
execution time hooks created by this extension. To that end, the
attribute is only intended to be meaningful at **query execution
time**, and importantly not any time prior to that, including query
compilation time.
"""
return self.load_options._lazy_loaded_from
@property
def loader_strategy_path(self):
"""Return the :class:`.PathRegistry` for the current load path.
This object represents the "path" in a query along relationships
when a particular object or collection is being loaded.
"""
opts = self._orm_compile_options()
if opts is not None:
return opts._current_path
else:
return None
@property
def is_column_load(self):
"""Return True if the operation is refreshing column-oriented
attributes on an existing ORM object.
This occurs during operations such as :meth:`_orm.Session.refresh`,
as well as when an attribute deferred by :func:`_orm.defer` is
being loaded, or an attribute that was expired either directly
by :meth:`_orm.Session.expire` or via a commit operation is being
loaded.
Handlers will very likely not want to add any options to queries
when such an operation is occurring as the query should be a straight
primary key fetch which should not have any additional WHERE criteria,
and loader options travelling with the instance
will have already been added to the query.
.. versionadded:: 1.4.0b2
.. seealso::
:attr:`_orm.ORMExecuteState.is_relationship_load`
"""
opts = self._orm_compile_options()
return opts is not None and opts._for_refresh_state
@property
def is_relationship_load(self):
"""Return True if this load is loading objects on behalf of a
relationship.
This means, the loader in effect is either a LazyLoader,
SelectInLoader, SubqueryLoader, or similar, and the entire
SELECT statement being emitted is on behalf of a relationship
load.
Handlers will very likely not want to add any options to queries
when such an operation is occurring, as loader options are already
capable of being propagated to relationship loaders and should
be already present.
.. seealso::
:attr:`_orm.ORMExecuteState.is_column_load`
"""
opts = self._orm_compile_options()
if opts is None:
return False
path = self.loader_strategy_path
return path is not None and not path.is_root
@property
def load_options(self):
"""Return the load_options that will be used for this execution."""
if not self.is_select:
raise sa_exc.InvalidRequestError(
"This ORM execution is not against a SELECT statement "
"so there are no load options."
)
return self.execution_options.get(
"_sa_orm_load_options", context.QueryContext.default_load_options
)
@property
def update_delete_options(self):
"""Return the update_delete_options that will be used for this
execution."""
if not self._is_crud:
raise sa_exc.InvalidRequestError(
"This ORM execution is not against an UPDATE or DELETE "
"statement so there are no update options."
)
return self.execution_options.get(
"_sa_orm_update_options",
persistence.BulkUDCompileState.default_update_options,
)
@property
def user_defined_options(self):
"""The sequence of :class:`.UserDefinedOptions` that have been
associated with the statement being invoked.
"""
return [
opt
for opt in self.statement._with_options
if not opt._is_compile_state and not opt._is_legacy_option
]
class SessionTransaction(TransactionalContext):
"""A :class:`.Session`-level transaction.
:class:`.SessionTransaction` is produced from the
:meth:`_orm.Session.begin`
and :meth:`_orm.Session.begin_nested` methods. It's largely an internal
object that in modern use provides a context manager for session
transactions.
Documentation on interacting with :class:`_orm.SessionTransaction` is
at: :ref:`unitofwork_transaction`.
.. versionchanged:: 1.4 The scoping and API methods to work with the
:class:`_orm.SessionTransaction` object directly have been simplified.
.. seealso::
:ref:`unitofwork_transaction`
:meth:`.Session.begin`
:meth:`.Session.begin_nested`
:meth:`.Session.rollback`
:meth:`.Session.commit`
:meth:`.Session.in_transaction`
:meth:`.Session.in_nested_transaction`
:meth:`.Session.get_transaction`
:meth:`.Session.get_nested_transaction`
"""
_rollback_exception = None
def __init__(
self,
session,
parent=None,
nested=False,
autobegin=False,
):
TransactionalContext._trans_ctx_check(session)
self.session = session
self._connections = {}
self._parent = parent
self.nested = nested
if nested:
self._previous_nested_transaction = session._nested_transaction
self._state = ACTIVE
if not parent and nested:
raise sa_exc.InvalidRequestError(
"Can't start a SAVEPOINT transaction when no existing "
"transaction is in progress"
)
self._take_snapshot(autobegin=autobegin)
# make sure transaction is assigned before we call the
# dispatch
self.session._transaction = self
self.session.dispatch.after_transaction_create(self.session, self)
@property
def parent(self):
"""The parent :class:`.SessionTransaction` of this
:class:`.SessionTransaction`.
If this attribute is ``None``, indicates this
:class:`.SessionTransaction` is at the top of the stack, and
corresponds to a real "COMMIT"/"ROLLBACK"
block. If non-``None``, then this is either a "subtransaction"
or a "nested" / SAVEPOINT transaction. If the
:attr:`.SessionTransaction.nested` attribute is ``True``, then
this is a SAVEPOINT, and if ``False``, indicates this a subtransaction.
.. versionadded:: 1.0.16 - use ._parent for previous versions
"""
return self._parent
nested = False
"""Indicates if this is a nested, or SAVEPOINT, transaction.
When :attr:`.SessionTransaction.nested` is True, it is expected
that :attr:`.SessionTransaction.parent` will be True as well.
"""
@property
def is_active(self):
return self.session is not None and self._state is ACTIVE
def _assert_active(
self,
prepared_ok=False,
rollback_ok=False,
deactive_ok=False,
closed_msg="This transaction is closed",
):
if self._state is COMMITTED:
raise sa_exc.InvalidRequestError(
"This session is in 'committed' state; no further "
"SQL can be emitted within this transaction."
)
elif self._state is PREPARED:
if not prepared_ok:
raise sa_exc.InvalidRequestError(
"This session is in 'prepared' state; no further "
"SQL can be emitted within this transaction."
)
elif self._state is DEACTIVE:
if not deactive_ok and not rollback_ok:
if self._rollback_exception:
raise sa_exc.PendingRollbackError(
"This Session's transaction has been rolled back "
"due to a previous exception during flush."
" To begin a new transaction with this Session, "
"first issue Session.rollback()."
" Original exception was: %s"
% self._rollback_exception,
code="7s2a",
)
elif not deactive_ok:
raise sa_exc.InvalidRequestError(
"This session is in 'inactive' state, due to the "
"SQL transaction being rolled back; no further "
"SQL can be emitted within this transaction."
)
elif self._state is CLOSED:
raise sa_exc.ResourceClosedError(closed_msg)
@property
def _is_transaction_boundary(self):
return self.nested or not self._parent
def connection(self, bindkey, execution_options=None, **kwargs):
self._assert_active()
bind = self.session.get_bind(bindkey, **kwargs)
return self._connection_for_bind(bind, execution_options)
def _begin(self, nested=False):
self._assert_active()
return SessionTransaction(self.session, self, nested=nested)
def _iterate_self_and_parents(self, upto=None):
current = self
result = ()
while current:
result += (current,)
if current._parent is upto:
break
elif current._parent is None:
raise sa_exc.InvalidRequestError(
"Transaction %s is not on the active transaction list"
% (upto)
)
else:
current = current._parent
return result
def _take_snapshot(self, autobegin=False):
if not self._is_transaction_boundary:
self._new = self._parent._new
self._deleted = self._parent._deleted
self._dirty = self._parent._dirty
self._key_switches = self._parent._key_switches
return
if not autobegin and not self.session._flushing:
self.session.flush()
self._new = weakref.WeakKeyDictionary()
self._deleted = weakref.WeakKeyDictionary()
self._dirty = weakref.WeakKeyDictionary()
self._key_switches = weakref.WeakKeyDictionary()
def _restore_snapshot(self, dirty_only=False):
"""Restore the restoration state taken before a transaction began.
Corresponds to a rollback.
"""
assert self._is_transaction_boundary
to_expunge = set(self._new).union(self.session._new)
self.session._expunge_states(to_expunge, to_transient=True)
for s, (oldkey, newkey) in self._key_switches.items():
# we probably can do this conditionally based on
# if we expunged or not, but safe_discard does that anyway
self.session.identity_map.safe_discard(s)
# restore the old key
s.key = oldkey
# now restore the object, but only if we didn't expunge
if s not in to_expunge:
self.session.identity_map.replace(s)
for s in set(self._deleted).union(self.session._deleted):
self.session._update_impl(s, revert_deletion=True)
assert not self.session._deleted
for s in self.session.identity_map.all_states():
if not dirty_only or s.modified or s in self._dirty:
s._expire(s.dict, self.session.identity_map._modified)
def _remove_snapshot(self):
"""Remove the restoration state taken before a transaction began.
Corresponds to a commit.
"""
assert self._is_transaction_boundary
if not self.nested and self.session.expire_on_commit:
for s in self.session.identity_map.all_states():
s._expire(s.dict, self.session.identity_map._modified)
statelib.InstanceState._detach_states(
list(self._deleted), self.session
)
self._deleted.clear()
elif self.nested:
self._parent._new.update(self._new)
self._parent._dirty.update(self._dirty)
self._parent._deleted.update(self._deleted)
self._parent._key_switches.update(self._key_switches)
def _connection_for_bind(self, bind, execution_options):
self._assert_active()
if bind in self._connections:
if execution_options:
util.warn(
"Connection is already established for the "
"given bind; execution_options ignored"
)
return self._connections[bind][0]
local_connect = False
should_commit = True
if self._parent:
conn = self._parent._connection_for_bind(bind, execution_options)
if not self.nested:
return conn
else:
if isinstance(bind, engine.Connection):
conn = bind
if conn.engine in self._connections:
raise sa_exc.InvalidRequestError(
"Session already has a Connection associated for the "
"given Connection's Engine"
)
else:
conn = bind.connect()
local_connect = True
try:
if execution_options:
conn = conn.execution_options(**execution_options)
if self.session.twophase and self._parent is None:
transaction = conn.begin_twophase()
elif self.nested:
transaction = conn.begin_nested()
elif conn.in_transaction():
# if given a future connection already in a transaction, don't
# commit that transaction unless it is a savepoint
if conn.in_nested_transaction():
transaction = conn.get_nested_transaction()
else:
transaction = conn.get_transaction()
should_commit = False
else:
transaction = conn.begin()
except:
# connection will not not be associated with this Session;
# close it immediately so that it isn't closed under GC
if local_connect:
conn.close()
raise
else:
bind_is_connection = isinstance(bind, engine.Connection)
self._connections[conn] = self._connections[conn.engine] = (
conn,
transaction,
should_commit,
not bind_is_connection,
)
self.session.dispatch.after_begin(self.session, self, conn)
return conn
def prepare(self):
if self._parent is not None or not self.session.twophase:
raise sa_exc.InvalidRequestError(
"'twophase' mode not enabled, or not root transaction; "
"can't prepare."
)
self._prepare_impl()
def _prepare_impl(self):
self._assert_active()
if self._parent is None or self.nested:
self.session.dispatch.before_commit(self.session)
stx = self.session._transaction
if stx is not self:
for subtransaction in stx._iterate_self_and_parents(upto=self):
subtransaction.commit()
if not self.session._flushing:
for _flush_guard in range(100):
if self.session._is_clean():
break
self.session.flush()
else:
raise exc.FlushError(
"Over 100 subsequent flushes have occurred within "
"session.commit() - is an after_flush() hook "
"creating new objects?"
)
if self._parent is None and self.session.twophase:
try:
for t in set(self._connections.values()):
t[1].prepare()
except:
with util.safe_reraise():
self.rollback()
self._state = PREPARED
def commit(self, _to_root=False):
self._assert_active(prepared_ok=True)
if self._state is not PREPARED:
self._prepare_impl()
if self._parent is None or self.nested:
for conn, trans, should_commit, autoclose in set(
self._connections.values()
):
if should_commit:
trans.commit()
self._state = COMMITTED
self.session.dispatch.after_commit(self.session)
self._remove_snapshot()
self.close()
if _to_root and self._parent:
return self._parent.commit(_to_root=True)
return self._parent
def rollback(self, _capture_exception=False, _to_root=False):
self._assert_active(prepared_ok=True, rollback_ok=True)
stx = self.session._transaction
if stx is not self:
for subtransaction in stx._iterate_self_and_parents(upto=self):
subtransaction.close()
boundary = self
rollback_err = None
if self._state in (ACTIVE, PREPARED):
for transaction in self._iterate_self_and_parents():
if transaction._parent is None or transaction.nested:
try:
for t in set(transaction._connections.values()):
t[1].rollback()
transaction._state = DEACTIVE
self.session.dispatch.after_rollback(self.session)
except:
rollback_err = sys.exc_info()
finally:
transaction._state = DEACTIVE
transaction._restore_snapshot(
dirty_only=transaction.nested
)
boundary = transaction
break
else:
transaction._state = DEACTIVE
sess = self.session
if not rollback_err and not sess._is_clean():
# if items were added, deleted, or mutated
# here, we need to re-restore the snapshot
util.warn(
"Session's state has been changed on "
"a non-active transaction - this state "
"will be discarded."
)
boundary._restore_snapshot(dirty_only=boundary.nested)
self.close()
if self._parent and _capture_exception:
self._parent._rollback_exception = sys.exc_info()[1]
if rollback_err:
util.raise_(rollback_err[1], with_traceback=rollback_err[2])
sess.dispatch.after_soft_rollback(sess, self)
if _to_root and self._parent:
return self._parent.rollback(_to_root=True)
return self._parent
def close(self, invalidate=False):
if self.nested:
self.session._nested_transaction = (
self._previous_nested_transaction
)
self.session._transaction = self._parent
if self._parent is None:
for connection, transaction, should_commit, autoclose in set(
self._connections.values()
):
if invalidate:
connection.invalidate()
if should_commit and transaction.is_active:
transaction.close()
if autoclose:
connection.close()
self._state = CLOSED
self.session.dispatch.after_transaction_end(self.session, self)
self.session = None
self._connections = None
def _get_subject(self):
return self.session
def _transaction_is_active(self):
return self._state is ACTIVE
def _transaction_is_closed(self):
return self._state is CLOSED
def _rollback_can_be_called(self):
return self._state not in (COMMITTED, CLOSED)
class Session(_SessionClassMethods):
"""Manages persistence operations for ORM-mapped objects.
The Session's usage paradigm is described at :doc:`/orm/session`.
"""
_is_asyncio = False
@util.deprecated_params(
autocommit=(
"2.0",
"The :paramref:`.Session.autocommit` parameter is deprecated "
"and will be removed in SQLAlchemy version 2.0. The "
':class:`_orm.Session` now features "autobegin" behavior '
"such that the :meth:`.Session.begin` method may be called "
"if a transaction has not yet been started yet. See the section "
":ref:`session_explicit_begin` for background.",
),
)
def __init__(
self,
bind=None,
autoflush=True,
future=False,
expire_on_commit=True,
autocommit=False,
twophase=False,
binds=None,
enable_baked_queries=True,
info=None,
query_cls=None,
):
r"""Construct a new Session.
See also the :class:`.sessionmaker` function which is used to
generate a :class:`.Session`-producing callable with a given
set of arguments.
:param autocommit:
Defaults to ``False``. When ``True``, the
:class:`.Session` does not automatically begin transactions for
individual statement executions, will acquire connections from the
engine on an as-needed basis, releasing to the connection pool
after each statement. Flushes will begin and commit (or possibly
rollback) their own transaction if no transaction is present.
When using this mode, the
:meth:`.Session.begin` method may be used to explicitly start
transactions, but the usual "autobegin" behavior is not present.
:param autoflush: When ``True``, all query operations will issue a