Source

sqlalchemy / lib / sqlalchemy / orm / state.py

Full commit
  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
# orm/state.py
# Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php

"""Defines instrumentation of instances.

This module is usually not directly visible to user applications, but
defines a large part of the ORM's interactivity.

"""

import weakref
from .. import util
from . import exc as orm_exc, attributes,util as orm_util
from .attributes import (
    PASSIVE_NO_RESULT, 
    SQL_OK, NEVER_SET, ATTR_WAS_SET, NO_VALUE,\
    PASSIVE_NO_INITIALIZE
    )
mapperlib = util.importlater("sqlalchemy.orm", "mapperlib")
sessionlib = util.importlater("sqlalchemy.orm", "session")


class InstanceState(object):
    """tracks state information at the instance level."""

    session_id = None
    key = None
    runid = None
    load_options = util.EMPTY_SET
    load_path = ()
    insert_order = None
    _strong_obj = None
    modified = False
    expired = False
    deleted = False
    _load_pending = False

    def __init__(self, obj, manager):
        self.class_ = obj.__class__
        self.manager = manager
        self.obj = weakref.ref(obj, self._cleanup)
        self.callables = {}
        self.committed_state = {}

    @util.memoized_property
    def attr(self):
        return util.ImmutableProperties(
            dict(
                (key, InspectAttr(self, key))
                for key in self.manager
            )
        )

    @property
    def transient(self):
        return self.key is None and \
            not self._attached

    @property
    def pending(self):
        return self.key is None and \
            self._attached

    @property
    def persistent(self):
        return self.key is not None and \
            self._attached

    @property
    def detached(self):
        return self.key is not None and \
            not self._attached

    @property
    def _attached(self):
        return self.session_id is not None and \
            self.session_id in sessionlib._sessions

    @property
    def session(self):
        return sessionlib._state_session(self)

    @property
    def object(self):
        return self.obj()

    @property
    def identity(self):
        if self.key is None:
            return None
        else:
            return self.key[1]

    @property
    def identity_key(self):
        # TODO: just change .key to .identity_key across
        # the board ?  probably
        return self.key

    @util.memoized_property
    def parents(self):
        return {}

    @util.memoized_property
    def _pending_mutations(self):
        return {}

    @util.memoized_property
    def mapper(self):
        return self.manager.mapper

    @property
    def has_identity(self):
        return bool(self.key)

    def _detach(self):
        self.session_id = None

    def _dispose(self):
        self._detach()
        del self.obj

    def _cleanup(self, ref):
        instance_dict = self._instance_dict()
        if instance_dict:
            instance_dict.discard(self)

        self.callables = {}
        self.session_id = None
        del self.obj

    def obj(self):
        return None

    @property
    def dict(self):
        o = self.obj()
        if o is not None:
            return attributes.instance_dict(o)
        else:
            return {}

    def initialize_instance(*mixed, **kwargs):
        self, instance, args = mixed[0], mixed[1], mixed[2:]
        manager = self.manager

        manager.dispatch.init(self, args, kwargs)

        try:
            return manager.original_init(*mixed[1:], **kwargs)
        except:
            manager.dispatch.init_failure(self, args, kwargs)
            raise

    def get_history(self, key, passive):
        return self.manager[key].impl.get_history(self, self.dict, passive)

    def get_impl(self, key):
        return self.manager[key].impl

    def _get_pending_mutation(self, key):
        if key not in self._pending_mutations:
            self._pending_mutations[key] = PendingCollection()
        return self._pending_mutations[key]

    def __getstate__(self):
        d = {'instance':self.obj()}
        d.update(
            (k, self.__dict__[k]) for k in (
                'committed_state', '_pending_mutations', 'modified', 'expired', 
                'callables', 'key', 'parents', 'load_options',
                'class_',
            ) if k in self.__dict__ 
        )
        if self.load_path:
            d['load_path'] = self.load_path.serialize()

        self.manager.dispatch.pickle(self, d)

        return d

    def __setstate__(self, state):
        from sqlalchemy.orm import instrumentation
        inst = state['instance']
        if inst is not None:
            self.obj = weakref.ref(inst, self._cleanup)
            self.class_ = inst.__class__
        else:
            # None being possible here generally new as of 0.7.4
            # due to storage of state in "parents".  "class_"
            # also new.
            self.obj = None
            self.class_ = state['class_']
        self.manager = manager = instrumentation.manager_of_class(self.class_)
        if manager is None:
            raise orm_exc.UnmappedInstanceError(
                        inst,
                        "Cannot deserialize object of type %r - no mapper() has"
                        " been configured for this class within the current Python process!" %
                        self.class_)
        elif manager.is_mapped and not manager.mapper.configured:
            mapperlib.configure_mappers()

        self.committed_state = state.get('committed_state', {})
        self._pending_mutations = state.get('_pending_mutations', {})
        self.parents = state.get('parents', {})
        self.modified = state.get('modified', False)
        self.expired = state.get('expired', False)
        self.callables = state.get('callables', {})

        if self.modified:
            self._strong_obj = inst

        self.__dict__.update([
            (k, state[k]) for k in (
                'key', 'load_options', 
            ) if k in state 
        ])

        if 'load_path' in state:
            self.load_path = orm_util.PathRegistry.\
                                deserialize(state['load_path'])

        # setup _sa_instance_state ahead of time so that 
        # unpickle events can access the object normally.
        # see [ticket:2362]
        manager.setup_instance(inst, self)
        manager.dispatch.unpickle(self, state)

    def initialize(self, key):
        """Set this attribute to an empty value or collection, 
           based on the AttributeImpl in use."""

        self.manager.get_impl(key).initialize(self, self.dict)

    def reset(self, dict_, key):
        """Remove the given attribute and any 
           callables associated with it."""

        dict_.pop(key, None)
        self.callables.pop(key, None)

    def expire_attribute_pre_commit(self, dict_, key):
        """a fast expire that can be called by column loaders during a load.

        The additional bookkeeping is finished up in commit_all().

        This method is actually called a lot with joined-table
        loading, when the second table isn't present in the result.

        """
        dict_.pop(key, None)
        self.callables[key] = self

    def set_callable(self, dict_, key, callable_):
        """Remove the given attribute and set the given callable
           as a loader."""

        dict_.pop(key, None)
        self.callables[key] = callable_

    def expire(self, dict_, modified_set):
        self.expired = True
        if self.modified:
            modified_set.discard(self)

        self.modified = False

        self.committed_state.clear()

        self.__dict__.pop('_pending_mutations', None)

        # clear out 'parents' collection.  not
        # entirely clear how we can best determine
        # which to remove, or not.
        self.__dict__.pop('parents', None)

        for key in self.manager:
            impl = self.manager[key].impl
            if impl.accepts_scalar_loader and \
                (impl.expire_missing or key in dict_):
                self.callables[key] = self
            dict_.pop(key, None)

        self.manager.dispatch.expire(self, None)

    def expire_attributes(self, dict_, attribute_names):
        pending = self.__dict__.get('_pending_mutations', None)

        for key in attribute_names:
            impl = self.manager[key].impl
            if impl.accepts_scalar_loader:
                self.callables[key] = self
            dict_.pop(key, None)

            self.committed_state.pop(key, None)
            if pending:
                pending.pop(key, None)

        self.manager.dispatch.expire(self, attribute_names)

    def __call__(self, passive):
        """__call__ allows the InstanceState to act as a deferred
        callable for loading expired attributes, which is also
        serializable (picklable).

        """

        if not passive & SQL_OK:
            return PASSIVE_NO_RESULT

        toload = self.expired_attributes.\
                        intersection(self.unmodified)

        self.manager.deferred_scalar_loader(self, toload)

        # if the loader failed, or this 
        # instance state didn't have an identity,
        # the attributes still might be in the callables
        # dict.  ensure they are removed.
        for k in toload.intersection(self.callables):
            del self.callables[k]

        return ATTR_WAS_SET

    @property
    def unmodified(self):
        """Return the set of keys which have no uncommitted changes"""

        return set(self.manager).difference(self.committed_state)

    def unmodified_intersection(self, keys):
        """Return self.unmodified.intersection(keys)."""

        return set(keys).intersection(self.manager).\
                    difference(self.committed_state)


    @property
    def unloaded(self):
        """Return the set of keys which do not have a loaded value.

        This includes expired attributes and any other attribute that
        was never populated or modified.

        """
        return set(self.manager).\
                    difference(self.committed_state).\
                    difference(self.dict)

    @property
    def expired_attributes(self):
        """Return the set of keys which are 'expired' to be loaded by
           the manager's deferred scalar loader, assuming no pending 
           changes.

           see also the ``unmodified`` collection which is intersected
           against this set when a refresh operation occurs.

        """
        return set([k for k, v in self.callables.items() if v is self])

    def _instance_dict(self):
        return None

    def _is_really_none(self):
        return self.obj()

    def _modified_event(self, dict_, attr, previous, collection=False):
        if attr.key not in self.committed_state:
            if collection:
                if previous is NEVER_SET:
                    if attr.key in dict_:
                        previous = dict_[attr.key]

                if previous not in (None, NO_VALUE, NEVER_SET):
                    previous = attr.copy(previous)

            self.committed_state[attr.key] = previous

        # the "or not self.modified" is defensive at 
        # this point.  The assertion below is expected
        # to be True:
        # assert self._strong_obj is None or self.modified

        if self._strong_obj is None or not self.modified:
            instance_dict = self._instance_dict()
            if instance_dict:
                instance_dict._modified.add(self)

            self._strong_obj = self.obj()
            if self._strong_obj is None:
                raise orm_exc.ObjectDereferencedError(
                        "Can't emit change event for attribute '%s' - "
                        "parent object of type %s has been garbage "
                        "collected." 
                        % (
                            self.manager[attr.key], 
                            orm_util.state_class_str(self)
                        ))
            self.modified = True

    def commit(self, dict_, keys):
        """Commit attributes.

        This is used by a partial-attribute load operation to mark committed
        those attributes which were refreshed from the database.

        Attributes marked as "expired" can potentially remain "expired" after
        this step if a value was not populated in state.dict.

        """
        class_manager = self.manager
        for key in keys:
            self.committed_state.pop(key, None)

        self.expired = False

        for key in set(self.callables).\
                            intersection(keys).\
                            intersection(dict_):
            del self.callables[key]

    def commit_all(self, dict_, instance_dict=None):
        """commit all attributes unconditionally.

        This is used after a flush() or a full load/refresh
        to remove all pending state from the instance.

         - all attributes are marked as "committed"
         - the "strong dirty reference" is removed
         - the "modified" flag is set to False
         - any "expired" markers/callables for attributes loaded are removed.

        Attributes marked as "expired" can potentially remain "expired" after this step
        if a value was not populated in state.dict.

        """

        self.committed_state.clear()
        self.__dict__.pop('_pending_mutations', None)

        callables = self.callables
        for key in list(callables):
            if key in dict_ and callables[key] is self:
                del callables[key]

        if instance_dict and self.modified:
            instance_dict._modified.discard(self)

        self.modified = self.expired = False
        self._strong_obj = None

class InspectAttr(object):
    """Provide inspection interface to an object's state."""

    def __init__(self, state, key):
        self.state = state
        self.key = key

    @property
    def loaded_value(self):
        return self.state.dict.get(self.key, NO_VALUE)

    @property
    def value(self):
        return self.state.manager[self.key].__get__(
                        self.state.obj(), self.state.class_)

    @property
    def history(self):
        return self.state.get_history(self.key, 
                    PASSIVE_NO_INITIALIZE)


class PendingCollection(object):
    """A writable placeholder for an unloaded collection.

    Stores items appended to and removed from a collection that has not yet
    been loaded. When the collection is loaded, the changes stored in
    PendingCollection are applied to it to produce the final result.

    """
    def __init__(self):
        self.deleted_items = util.IdentitySet()
        self.added_items = util.OrderedIdentitySet()

    def append(self, value):
        if value in self.deleted_items:
            self.deleted_items.remove(value)
        else:
            self.added_items.add(value)

    def remove(self, value):
        if value in self.added_items:
            self.added_items.remove(value)
        else:
            self.deleted_items.add(value)