sqlalchemy_msabramo_tox / lib / sqlalchemy / orm / events.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
# orm/events.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

"""ORM event interfaces.

"""
from .. import event, exc, util
orm = util.importlater("sqlalchemy", "orm")
import inspect

class InstrumentationEvents(event.Events):
    """Events related to class instrumentation events.

    The listeners here support being established against
    any new style class, that is any object that is a subclass
    of 'type'.  Events will then be fired off for events
    against that class as well as all subclasses.
    'type' itself is also accepted as a target
    in which case the events fire for all classes.

    """

    @classmethod
    def _accept_with(cls, target):
        if isinstance(target, type):
            return orm.instrumentation.instrumentation_registry
        else:
            return None

    @classmethod
    def _listen(cls, target, identifier, fn, propagate=False):
        event.Events._listen(target, identifier, fn, propagate=propagate)

    @classmethod
    def _remove(cls, identifier, target, fn):
        raise NotImplementedError("Removal of instrumentation events not yet implemented")

    def class_instrument(self, cls):
        """Called after the given class is instrumented.

        To get at the :class:`.ClassManager`, use
        :func:`.manager_of_class`.

        """

    def class_uninstrument(self, cls):
        """Called before the given class is uninstrumented.

        To get at the :class:`.ClassManager`, use
        :func:`.manager_of_class`.

        """


    def attribute_instrument(self, cls, key, inst):
        """Called when an attribute is instrumented."""

class InstanceEvents(event.Events):
    """Define events specific to object lifecycle.

    e.g.::

        from sqlalchemy import event

        def my_load_listener(target, context):
            print "on load!"

        event.listen(SomeMappedClass, 'load', my_load_listener)

    Available targets include mapped classes, instances of
    :class:`.Mapper` (i.e. returned by :func:`.mapper`,
    :func:`.class_mapper` and similar), as well as the
    :class:`.Mapper` class and :func:`.mapper` function itself
    for global event reception::

        from sqlalchemy.orm import mapper

        def some_listener(target, context):
            log.debug("Instance %s being loaded" % target)

        # attach to all mappers
        event.listen(mapper, 'load', some_listener)

    Instance events are closely related to mapper events, but
    are more specific to the instance and its instrumentation,
    rather than its system of persistence.

    When using :class:`.InstanceEvents`, several modifiers are
    available to the :func:`.event.listen` function.

    :param propagate=False: When True, the event listener should 
       be applied to all inheriting mappers as well as the 
       mapper which is the target of this listener.
    :param raw=False: When True, the "target" argument passed
       to applicable event listener functions will be the 
       instance's :class:`.InstanceState` management
       object, rather than the mapped instance itself.

    """
    @classmethod
    def _accept_with(cls, target):
        if isinstance(target, orm.instrumentation.ClassManager):
            return target
        elif isinstance(target, orm.Mapper):
            return target.class_manager
        elif target is orm.mapper:
            return orm.instrumentation.ClassManager
        elif isinstance(target, type):
            if issubclass(target, orm.Mapper):
                return orm.instrumentation.ClassManager
            else:
                manager = orm.instrumentation.manager_of_class(target)
                if manager:
                    return manager
        return None

    @classmethod
    def _listen(cls, target, identifier, fn, raw=False, propagate=False):
        if not raw:
            orig_fn = fn
            def wrap(state, *arg, **kw):
                return orig_fn(state.obj(), *arg, **kw)
            fn = wrap

        event.Events._listen(target, identifier, fn, propagate=propagate)
        if propagate:
            for mgr in target.subclass_managers(True):
                event.Events._listen(mgr, identifier, fn, True)

    @classmethod
    def _remove(cls, identifier, target, fn):
        raise NotImplementedError("Removal of instance events not yet implemented")

    def first_init(self, manager, cls):
        """Called when the first instance of a particular mapping is called.

        """

    def init(self, target, args, kwargs):
        """Receive an instance when it's constructor is called.

        This method is only called during a userland construction of 
        an object.  It is not called when an object is loaded from the
        database.

        """

    def init_failure(self, target, args, kwargs):
        """Receive an instance when it's constructor has been called, 
        and raised an exception.

        This method is only called during a userland construction of 
        an object.  It is not called when an object is loaded from the
        database.

        """

    def load(self, target, context):
        """Receive an object instance after it has been created via
        ``__new__``, and after initial attribute population has
        occurred.

        This typically occurs when the instance is created based on
        incoming result rows, and is only called once for that
        instance's lifetime.

        Note that during a result-row load, this method is called upon
        the first row received for this instance.  Note that some 
        attributes and collections may or may not be loaded or even 
        initialized, depending on what's present in the result rows.

        :param target: the mapped instance.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.
        :param context: the :class:`.QueryContext` corresponding to the
         current :class:`.Query` in progress.  This argument may be
         ``None`` if the load does not correspond to a :class:`.Query`,
         such as during :meth:`.Session.merge`.

        """

    def refresh(self, target, context, attrs):
        """Receive an object instance after one or more attributes have 
        been refreshed from a query.

        :param target: the mapped instance.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.
        :param context: the :class:`.QueryContext` corresponding to the
         current :class:`.Query` in progress.
        :param attrs: iterable collection of attribute names which 
         were populated, or None if all column-mapped, non-deferred
         attributes were populated.

        """

    def expire(self, target, attrs):
        """Receive an object instance after its attributes or some subset
        have been expired.

        'keys' is a list of attribute names.  If None, the entire
        state was expired.

        :param target: the mapped instance.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.
        :param attrs: iterable collection of attribute
         names which were expired, or None if all attributes were 
         expired.

        """

    def resurrect(self, target):
        """Receive an object instance as it is 'resurrected' from 
        garbage collection, which occurs when a "dirty" state falls
        out of scope.

        :param target: the mapped instance.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.

        """

    def pickle(self, target, state_dict):
        """Receive an object instance when its associated state is
        being pickled.

        :param target: the mapped instance.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.
        :param state_dict: the dictionary returned by 
         :class:`.InstanceState.__getstate__`, containing the state
         to be pickled.
         
        """

    def unpickle(self, target, state_dict):
        """Receive an object instance after it's associated state has
        been unpickled.

        :param target: the mapped instance.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.
        :param state_dict: the dictionary sent to
         :class:`.InstanceState.__setstate__`, containing the state
         dictionary which was pickled.
        
        """

class MapperEvents(event.Events):
    """Define events specific to mappings.

    e.g.::

        from sqlalchemy import event

        def my_before_insert_listener(mapper, connection, target):
            # execute a stored procedure upon INSERT,
            # apply the value to the row to be inserted
            target.calculated_value = connection.scalar(
                                        "select my_special_function(%d)" 
                                        % target.special_number)

        # associate the listener function with SomeMappedClass,
        # to execute during the "before_insert" hook
        event.listen(SomeMappedClass, 'before_insert', my_before_insert_listener)

    Available targets include mapped classes, instances of
    :class:`.Mapper` (i.e. returned by :func:`.mapper`,
    :func:`.class_mapper` and similar), as well as the
    :class:`.Mapper` class and :func:`.mapper` function itself
    for global event reception::

        from sqlalchemy.orm import mapper

        def some_listener(mapper, connection, target):
            log.debug("Instance %s being inserted" % target)

        # attach to all mappers
        event.listen(mapper, 'before_insert', some_listener)

    Mapper events provide hooks into critical sections of the
    mapper, including those related to object instrumentation,
    object loading, and object persistence. In particular, the
    persistence methods :meth:`~.MapperEvents.before_insert`,
    and :meth:`~.MapperEvents.before_update` are popular
    places to augment the state being persisted - however, these
    methods operate with several significant restrictions. The
    user is encouraged to evaluate the
    :meth:`.SessionEvents.before_flush` and
    :meth:`.SessionEvents.after_flush` methods as more
    flexible and user-friendly hooks in which to apply
    additional database state during a flush.

    When using :class:`.MapperEvents`, several modifiers are
    available to the :func:`.event.listen` function.

    :param propagate=False: When True, the event listener should 
       be applied to all inheriting mappers as well as the 
       mapper which is the target of this listener.
    :param raw=False: When True, the "target" argument passed
       to applicable event listener functions will be the 
       instance's :class:`.InstanceState` management
       object, rather than the mapped instance itself.
    :param retval=False: when True, the user-defined event function
       must have a return value, the purpose of which is either to
       control subsequent event propagation, or to otherwise alter 
       the operation in progress by the mapper.   Possible return
       values are:

       * ``sqlalchemy.orm.interfaces.EXT_CONTINUE`` - continue event
         processing normally.
       * ``sqlalchemy.orm.interfaces.EXT_STOP`` - cancel all subsequent
         event handlers in the chain.
       * other values - the return value specified by specific listeners,
         such as :meth:`~.MapperEvents.translate_row` or 
         :meth:`~.MapperEvents.create_instance`.

    """

    @classmethod
    def _accept_with(cls, target):
        if target is orm.mapper:
            return orm.Mapper
        elif isinstance(target, type):
            if issubclass(target, orm.Mapper):
                return target
            else:
                return orm.class_mapper(target, compile=False)
        else:
            return target

    @classmethod
    def _listen(cls, target, identifier, fn, 
                            raw=False, retval=False, propagate=False):

        if not raw or not retval:
            if not raw:
                meth = getattr(cls, identifier)
                try:
                    target_index = inspect.getargspec(meth)[0].index('target') - 1
                except ValueError:
                    target_index = None

            wrapped_fn = fn
            def wrap(*arg, **kw):
                if not raw and target_index is not None:
                    arg = list(arg)
                    arg[target_index] = arg[target_index].obj()
                if not retval:
                    wrapped_fn(*arg, **kw)
                    return orm.interfaces.EXT_CONTINUE
                else:
                    return wrapped_fn(*arg, **kw)
            fn = wrap

        if propagate:
            for mapper in target.self_and_descendants:
                event.Events._listen(mapper, identifier, fn, propagate=True)
        else:
            event.Events._listen(target, identifier, fn)

    def instrument_class(self, mapper, class_):
        """Receive a class when the mapper is first constructed, 
        before instrumentation is applied to the mapped class.

        This event is the earliest phase of mapper construction.
        Most attributes of the mapper are not yet initialized.

        This listener can generally only be applied to the :class:`.Mapper`
        class overall.

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param class\_: the mapped class.

        """

    def mapper_configured(self, mapper, class_):
        """Called when the mapper for the class is fully configured.

        This event is the latest phase of mapper construction.
        The mapper should be in its final state.

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param class\_: the mapped class.

        """
        # TODO: need coverage for this event

    def after_configured(self):
        """Called after a series of mappers have been configured.

        This corresponds to the :func:`.orm.configure_mappers` call, which
        note is usually called automatically as mappings are first
        used.
        
        Theoretically this event is called once per
        application, but is actually called any time new mappers
        have been affected by a :func:`.orm.configure_mappers` call.   If new mappings
        are constructed after existing ones have already been used, 
        this event can be called again.

        """

    def translate_row(self, mapper, context, row):
        """Perform pre-processing on the given result row and return a
        new row instance.

        This listener is typically registered with ``retval=True``.
        It is called when the mapper first receives a row, before
        the object identity or the instance itself has been derived
        from that row.   The given row may or may not be a 
        :class:`.RowProxy` object - it will always be a dictionary-like
        object which contains mapped columns as keys.  The 
        returned object should also be a dictionary-like object
        which recognizes mapped columns as keys.

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param context: the :class:`.QueryContext`, which includes
         a handle to the current :class:`.Query` in progress as well
         as additional state information.
        :param row: the result row being handled.  This may be 
         an actual :class:`.RowProxy` or may be a dictionary containing
         :class:`.Column` objects as keys.
        :return: When configured with ``retval=True``, the function
         should return a dictionary-like row object, or ``EXT_CONTINUE``,
         indicating the original row should be used.


        """

    def create_instance(self, mapper, context, row, class_):
        """Receive a row when a new object instance is about to be
        created from that row.

        The method can choose to create the instance itself, or it can return
        EXT_CONTINUE to indicate normal object creation should take place.
        This listener is typically registered with ``retval=True``.

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param context: the :class:`.QueryContext`, which includes
         a handle to the current :class:`.Query` in progress as well
         as additional state information.
        :param row: the result row being handled.  This may be 
         an actual :class:`.RowProxy` or may be a dictionary containing
         :class:`.Column` objects as keys.
        :param class\_: the mapped class.
        :return: When configured with ``retval=True``, the return value
         should be a newly created instance of the mapped class, 
         or ``EXT_CONTINUE`` indicating that default object construction
         should take place.

        """

    def append_result(self, mapper, context, row, target, 
                        result, **flags):
        """Receive an object instance before that instance is appended
        to a result list.

        This is a rarely used hook which can be used to alter
        the construction of a result list returned by :class:`.Query`.

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param context: the :class:`.QueryContext`, which includes
         a handle to the current :class:`.Query` in progress as well
         as additional state information.
        :param row: the result row being handled.  This may be 
         an actual :class:`.RowProxy` or may be a dictionary containing
         :class:`.Column` objects as keys.
        :param target: the mapped instance being populated.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.
        :param result: a list-like object where results are being
         appended.
        :param \**flags: Additional state information about the 
         current handling of the row.
        :return: If this method is registered with ``retval=True``,
         a return value of ``EXT_STOP`` will prevent the instance
         from being appended to the given result list, whereas a 
         return value of ``EXT_CONTINUE`` will result in the default
         behavior of appending the value to the result list.

        """


    def populate_instance(self, mapper, context, row, 
                            target, **flags):
        """Receive an instance before that instance has
        its attributes populated.

        This usually corresponds to a newly loaded instance but may
        also correspond to an already-loaded instance which has
        unloaded attributes to be populated.  The method may be called
        many times for a single instance, as multiple result rows are
        used to populate eagerly loaded collections.

        Most usages of this hook are obsolete.  For a
        generic "object has been newly created from a row" hook, use
        :meth:`.InstanceEvents.load`.

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param context: the :class:`.QueryContext`, which includes
         a handle to the current :class:`.Query` in progress as well
         as additional state information.
        :param row: the result row being handled.  This may be 
         an actual :class:`.RowProxy` or may be a dictionary containing
         :class:`.Column` objects as keys.
        :param target: the mapped instance.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.
        :return: When configured with ``retval=True``, a return
         value of ``EXT_STOP`` will bypass instance population by
         the mapper. A value of ``EXT_CONTINUE`` indicates that
         default instance population should take place.

        """

    def before_insert(self, mapper, connection, target):
        """Receive an object instance before an INSERT statement
        is emitted corresponding to that instance.

        This event is used to modify local, non-object related 
        attributes on the instance before an INSERT occurs, as well
        as to emit additional SQL statements on the given 
        connection.

        The event is often called for a batch of objects of the
        same class before their INSERT statements are emitted at
        once in a later step. In the extremely rare case that
        this is not desirable, the :func:`.mapper` can be
        configured with ``batch=False``, which will cause
        batches of instances to be broken up into individual
        (and more poorly performing) event->persist->event
        steps.

        .. warning::
            Mapper-level flush events are designed to operate **on attributes
            local to the immediate object being handled  
            and via SQL operations with the given** :class:`.Connection` **only.**
            Handlers here should **not** make alterations to the state of 
            the :class:`.Session` overall, and in general should not
            affect any :func:`.relationship` -mapped attributes, as 
            session cascade rules will not function properly, nor is it
            always known if the related class has already been handled.  
            Operations that **are not supported in mapper events** include:
        
            * :meth:`.Session.add`
            * :meth:`.Session.delete`
            * Mapped collection append, add, remove, delete, discard, etc.
            * Mapped relationship attribute set/del events, i.e. ``someobject.related = someotherobject``
        
            Operations which manipulate the state of the object
            relative to other objects are better handled:
        
            * In the ``__init__()`` method of the mapped object itself, or another method
              designed to establish some particular state.
            * In a ``@validates`` handler, see :ref:`simple_validators`
            * Within the  :meth:`.SessionEvents.before_flush` event.

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param connection: the :class:`.Connection` being used to 
         emit INSERT statements for this instance.  This
         provides a handle into the current transaction on the 
         target database specific to this instance.
        :param target: the mapped instance being persisted.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.
        :return: No return value is supported by this event.

        """

    def after_insert(self, mapper, connection, target):
        """Receive an object instance after an INSERT statement
        is emitted corresponding to that instance.

        This event is used to modify in-Python-only
        state on the instance after an INSERT occurs, as well
        as to emit additional SQL statements on the given 
        connection.

        The event is often called for a batch of objects of the
        same class after their INSERT statements have been
        emitted at once in a previous step. In the extremely
        rare case that this is not desirable, the
        :func:`.mapper` can be configured with ``batch=False``,
        which will cause batches of instances to be broken up
        into individual (and more poorly performing)
        event->persist->event steps.

        .. warning::
            Mapper-level flush events are designed to operate **on attributes
            local to the immediate object being handled  
            and via SQL operations with the given** :class:`.Connection` **only.**
            Handlers here should **not** make alterations to the state of 
            the :class:`.Session` overall, and in general should not
            affect any :func:`.relationship` -mapped attributes, as 
            session cascade rules will not function properly, nor is it
            always known if the related class has already been handled.  
            Operations that **are not supported in mapper events** include:
        
            * :meth:`.Session.add`
            * :meth:`.Session.delete`
            * Mapped collection append, add, remove, delete, discard, etc.
            * Mapped relationship attribute set/del events, i.e. ``someobject.related = someotherobject``
        
            Operations which manipulate the state of the object
            relative to other objects are better handled:
        
            * In the ``__init__()`` method of the mapped object itself, or another method
              designed to establish some particular state.
            * In a ``@validates`` handler, see :ref:`simple_validators`
            * Within the  :meth:`.SessionEvents.before_flush` event.

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param connection: the :class:`.Connection` being used to 
         emit INSERT statements for this instance.  This
         provides a handle into the current transaction on the 
         target database specific to this instance.
        :param target: the mapped instance being persisted.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.
        :return: No return value is supported by this event.

        """

    def before_update(self, mapper, connection, target):
        """Receive an object instance before an UPDATE statement
        is emitted corresponding to that instance.

        This event is used to modify local, non-object related 
        attributes on the instance before an UPDATE occurs, as well
        as to emit additional SQL statements on the given 
        connection.

        This method is called for all instances that are
        marked as "dirty", *even those which have no net changes
        to their column-based attributes*. An object is marked
        as dirty when any of its column-based attributes have a
        "set attribute" operation called or when any of its
        collections are modified. If, at update time, no
        column-based attributes have any net changes, no UPDATE
        statement will be issued. This means that an instance
        being sent to :meth:`~.MapperEvents.before_update` is
        *not* a guarantee that an UPDATE statement will be
        issued, although you can affect the outcome here by
        modifying attributes so that a net change in value does
        exist.

        To detect if the column-based attributes on the object have net
        changes, and will therefore generate an UPDATE statement, use
        ``object_session(instance).is_modified(instance,
        include_collections=False)``.

        The event is often called for a batch of objects of the
        same class before their UPDATE statements are emitted at
        once in a later step. In the extremely rare case that
        this is not desirable, the :func:`.mapper` can be
        configured with ``batch=False``, which will cause
        batches of instances to be broken up into individual
        (and more poorly performing) event->persist->event
        steps.

        .. warning::
            Mapper-level flush events are designed to operate **on attributes
            local to the immediate object being handled  
            and via SQL operations with the given** :class:`.Connection` **only.**
            Handlers here should **not** make alterations to the state of 
            the :class:`.Session` overall, and in general should not
            affect any :func:`.relationship` -mapped attributes, as 
            session cascade rules will not function properly, nor is it
            always known if the related class has already been handled.  
            Operations that **are not supported in mapper events** include:
        
            * :meth:`.Session.add`
            * :meth:`.Session.delete`
            * Mapped collection append, add, remove, delete, discard, etc.
            * Mapped relationship attribute set/del events, i.e. ``someobject.related = someotherobject``
        
            Operations which manipulate the state of the object
            relative to other objects are better handled:
        
            * In the ``__init__()`` method of the mapped object itself, or another method
              designed to establish some particular state.
            * In a ``@validates`` handler, see :ref:`simple_validators`
            * Within the  :meth:`.SessionEvents.before_flush` event.

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param connection: the :class:`.Connection` being used to 
         emit UPDATE statements for this instance.  This
         provides a handle into the current transaction on the 
         target database specific to this instance.
        :param target: the mapped instance being persisted.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.
        :return: No return value is supported by this event.
        """

    def after_update(self, mapper, connection, target):
        """Receive an object instance after an UPDATE statement
        is emitted corresponding to that instance.

        This event is used to modify in-Python-only
        state on the instance after an UPDATE occurs, as well
        as to emit additional SQL statements on the given 
        connection.

        This method is called for all instances that are
        marked as "dirty", *even those which have no net changes
        to their column-based attributes*, and for which 
        no UPDATE statement has proceeded. An object is marked
        as dirty when any of its column-based attributes have a
        "set attribute" operation called or when any of its
        collections are modified. If, at update time, no
        column-based attributes have any net changes, no UPDATE
        statement will be issued. This means that an instance
        being sent to :meth:`~.MapperEvents.after_update` is
        *not* a guarantee that an UPDATE statement has been
        issued.

        To detect if the column-based attributes on the object have net
        changes, and therefore resulted in an UPDATE statement, use
        ``object_session(instance).is_modified(instance,
        include_collections=False)``.

        The event is often called for a batch of objects of the
        same class after their UPDATE statements have been emitted at
        once in a previous step. In the extremely rare case that
        this is not desirable, the :func:`.mapper` can be
        configured with ``batch=False``, which will cause
        batches of instances to be broken up into individual
        (and more poorly performing) event->persist->event
        steps.

        .. warning::
            Mapper-level flush events are designed to operate **on attributes
            local to the immediate object being handled  
            and via SQL operations with the given** :class:`.Connection` **only.**
            Handlers here should **not** make alterations to the state of 
            the :class:`.Session` overall, and in general should not
            affect any :func:`.relationship` -mapped attributes, as 
            session cascade rules will not function properly, nor is it
            always known if the related class has already been handled.  
            Operations that **are not supported in mapper events** include:
        
            * :meth:`.Session.add`
            * :meth:`.Session.delete`
            * Mapped collection append, add, remove, delete, discard, etc.
            * Mapped relationship attribute set/del events, i.e. ``someobject.related = someotherobject``
        
            Operations which manipulate the state of the object
            relative to other objects are better handled:
        
            * In the ``__init__()`` method of the mapped object itself, or another method
              designed to establish some particular state.
            * In a ``@validates`` handler, see :ref:`simple_validators`
            * Within the  :meth:`.SessionEvents.before_flush` event.

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param connection: the :class:`.Connection` being used to 
         emit UPDATE statements for this instance.  This
         provides a handle into the current transaction on the 
         target database specific to this instance.
        :param target: the mapped instance being persisted.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.
        :return: No return value is supported by this event.

        """

    def before_delete(self, mapper, connection, target):
        """Receive an object instance before a DELETE statement
        is emitted corresponding to that instance.

        This event is used to emit additional SQL statements on 
        the given connection as well as to perform application
        specific bookkeeping related to a deletion event.

        The event is often called for a batch of objects of the
        same class before their DELETE statements are emitted at
        once in a later step. 

        .. warning::
            Mapper-level flush events are designed to operate **on attributes
            local to the immediate object being handled  
            and via SQL operations with the given** :class:`.Connection` **only.**
            Handlers here should **not** make alterations to the state of 
            the :class:`.Session` overall, and in general should not
            affect any :func:`.relationship` -mapped attributes, as 
            session cascade rules will not function properly, nor is it
            always known if the related class has already been handled.  
            Operations that **are not supported in mapper events** include:
        
            * :meth:`.Session.add`
            * :meth:`.Session.delete`
            * Mapped collection append, add, remove, delete, discard, etc.
            * Mapped relationship attribute set/del events, i.e. ``someobject.related = someotherobject``
        
            Operations which manipulate the state of the object
            relative to other objects are better handled:
        
            * In the ``__init__()`` method of the mapped object itself, or another method
              designed to establish some particular state.
            * In a ``@validates`` handler, see :ref:`simple_validators`
            * Within the  :meth:`.SessionEvents.before_flush` event.

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param connection: the :class:`.Connection` being used to 
         emit DELETE statements for this instance.  This
         provides a handle into the current transaction on the 
         target database specific to this instance.
        :param target: the mapped instance being deleted.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.
        :return: No return value is supported by this event.

        """

    def after_delete(self, mapper, connection, target):
        """Receive an object instance after a DELETE statement
        has been emitted corresponding to that instance.

        This event is used to emit additional SQL statements on 
        the given connection as well as to perform application
        specific bookkeeping related to a deletion event.

        The event is often called for a batch of objects of the
        same class after their DELETE statements have been emitted at
        once in a previous step. 

        .. warning::
            Mapper-level flush events are designed to operate **on attributes
            local to the immediate object being handled  
            and via SQL operations with the given** :class:`.Connection` **only.**
            Handlers here should **not** make alterations to the state of 
            the :class:`.Session` overall, and in general should not
            affect any :func:`.relationship` -mapped attributes, as 
            session cascade rules will not function properly, nor is it
            always known if the related class has already been handled.  
            Operations that **are not supported in mapper events** include:
        
            * :meth:`.Session.add`
            * :meth:`.Session.delete`
            * Mapped collection append, add, remove, delete, discard, etc.
            * Mapped relationship attribute set/del events, i.e. ``someobject.related = someotherobject``
        
            Operations which manipulate the state of the object
            relative to other objects are better handled:
        
            * In the ``__init__()`` method of the mapped object itself, or another method
              designed to establish some particular state.
            * In a ``@validates`` handler, see :ref:`simple_validators`
            * Within the  :meth:`.SessionEvents.before_flush` event.

        :param mapper: the :class:`.Mapper` which is the target
         of this event.
        :param connection: the :class:`.Connection` being used to 
         emit DELETE statements for this instance.  This
         provides a handle into the current transaction on the 
         target database specific to this instance.
        :param target: the mapped instance being deleted.  If 
         the event is configured with ``raw=True``, this will 
         instead be the :class:`.InstanceState` state-management
         object associated with the instance.
        :return: No return value is supported by this event.

        """

    @classmethod
    def _remove(cls, identifier, target, fn):
        raise NotImplementedError("Removal of mapper events not yet implemented")

class SessionEvents(event.Events):
    """Define events specific to :class:`.Session` lifecycle.

    e.g.::

        from sqlalchemy import event
        from sqlalchemy.orm import sessionmaker

        def my_before_commit(session):
            print "before commit!"

        Session = sessionmaker()

        event.listen(Session, "before_commit", my_before_commit)

    The :func:`~.event.listen` function will accept
    :class:`.Session` objects as well as the return result
    of :func:`.sessionmaker` and :func:`.scoped_session`.

    Additionally, it accepts the :class:`.Session` class which
    will apply listeners to all :class:`.Session` instances
    globally.

    """

    @classmethod
    def _accept_with(cls, target):
        if isinstance(target, orm.ScopedSession):
            if not isinstance(target.session_factory, type) or \
                not issubclass(target.session_factory, orm.Session):
                raise exc.ArgumentError(
                            "Session event listen on a ScopedSession "
                            "requires that its creation callable "
                            "is a Session subclass.")
            return target.session_factory
        elif isinstance(target, type):
            if issubclass(target, orm.ScopedSession):
                return orm.Session
            elif issubclass(target, orm.Session):
                return target
        elif isinstance(target, orm.Session):
            return target
        else:
            return None

    @classmethod
    def _remove(cls, identifier, target, fn):
        raise NotImplementedError("Removal of session events not yet implemented")

    def before_commit(self, session):
        """Execute before commit is called.

        Note that this may not be per-flush if a longer running
        transaction is ongoing.

        :param session: The target :class:`.Session`.
        
        """

    def after_commit(self, session):
        """Execute after a commit has occurred.

        Note that this may not be per-flush if a longer running
        transaction is ongoing.
        
        :param session: The target :class:`.Session`.
        
        """

    def after_rollback(self, session):
        """Execute after a real DBAPI rollback has occurred.
        
        Note that this event only fires when the *actual* rollback against
        the database occurs - it does *not* fire each time the 
        :meth:`.Session.rollback` method is called, if the underlying 
        DBAPI transaction has already been rolled back.  In many
        cases, the :class:`.Session` will not be in 
        an "active" state during this event, as the current
        transaction is not valid.   To acquire a :class:`.Session`
        which is active after the outermost rollback has proceeded,
        use the :meth:`.SessionEvents.after_soft_rollback` event, checking the
        :attr:`.Session.is_active` flag.

        :param session: The target :class:`.Session`.

        """

    def after_soft_rollback(self, session, previous_transaction):
        """Execute after any rollback has occurred, including "soft" 
        rollbacks that don't actually emit at the DBAPI level.
        
        This corresponds to both nested and outer rollbacks, i.e.
        the innermost rollback that calls the DBAPI's 
        rollback() method, as well as the enclosing rollback 
        calls that only pop themselves from the transaction stack.
        
        The given :class:`.Session` can be used to invoke SQL and 
        :meth:`.Session.query` operations after an outermost rollback 
        by first checking the :attr:`.Session.is_active` flag::

            @event.listens_for(Session, "after_soft_rollback")
            def do_something(session, previous_transaction):
                if session.is_active:
                    session.execute("select * from some_table")
        
        :param session: The target :class:`.Session`.
        :param previous_transaction: The :class:`.SessionTransaction` transactional
         marker object which was just closed.   The current :class:`.SessionTransaction`
         for the given :class:`.Session` is available via the
         :attr:`.Session.transaction` attribute.

        .. versionadded:: 0.7.3

        """

    def before_flush( self, session, flush_context, instances):
        """Execute before flush process has started.

        :param session: The target :class:`.Session`.
        :param flush_context: Internal :class:`.UOWTransaction` object
         which handles the details of the flush.
        :param instances: Usually ``None``, this is the collection of
         objects which can be passed to the :meth:`.Session.flush` method
         (note this usage is deprecated).

        """

    def after_flush(self, session, flush_context):
        """Execute after flush has completed, but before commit has been
        called.

        Note that the session's state is still in pre-flush, i.e. 'new',
        'dirty', and 'deleted' lists still show pre-flush state as well
        as the history settings on instance attributes.
        
        :param session: The target :class:`.Session`.
        :param flush_context: Internal :class:`.UOWTransaction` object
         which handles the details of the flush.

        """

    def after_flush_postexec(self, session, flush_context):
        """Execute after flush has completed, and after the post-exec
        state occurs.

        This will be when the 'new', 'dirty', and 'deleted' lists are in
        their final state.  An actual commit() may or may not have
        occurred, depending on whether or not the flush started its own
        transaction or participated in a larger transaction. 
        
        :param session: The target :class:`.Session`.
        :param flush_context: Internal :class:`.UOWTransaction` object
         which handles the details of the flush.
        """

    def after_begin( self, session, transaction, connection):
        """Execute after a transaction is begun on a connection

        :param session: The target :class:`.Session`.
        :param transaction: The :class:`.SessionTransaction`.
        :param connection: The :class:`~.engine.base.Connection` object 
         which will be used for SQL statements.
        
        """

    def before_attach(self, session, instance):
        """Execute before an instance is attached to a session.

        This is called before an add, delete or merge causes
        the object to be part of the session.
        
        .. versionadded:: 0.8.  Note that :meth:`.after_attach` now 
           fires off after the item is part of the session.  
           :meth:`.before_attach` is provided for those cases where
           the item should not yet be part of the session state.
           
        """

    def after_attach(self, session, instance):
        """Execute after an instance is attached to a session.

        This is called after an add, delete or merge. 
        
        .. note::
           
           As of 0.8, this event fires off *after* the item
           has been fully associated with the session, which is
           different than previous releases.  For event
           handlers that require the object not yet 
           be part of session state (such as handlers which
           may autoflush while the target object is not
           yet complete) consider the
           new :meth:`.before_attach` event.
           
        """

    def after_bulk_update( self, session, query, query_context, result):
        """Execute after a bulk update operation to the session.

        This is called as a result of the :meth:`.Query.update` method.

        :param query: the :class:`.Query` object that this update operation was
         called upon. 
        :param query_context: The :class:`.QueryContext` object, corresponding
         to the invocation of an ORM query.
        :param result: the :class:`.ResultProxy` returned as a result of the
         bulk UPDATE operation.

        """

    def after_bulk_delete( self, session, query, query_context, result):
        """Execute after a bulk delete operation to the session.

        This is called as a result of the :meth:`.Query.delete` method.

        :param query: the :class:`.Query` object that this update operation was
         called upon. 
        :param query_context: The :class:`.QueryContext` object, corresponding
         to the invocation of an ORM query.
        :param result: the :class:`.ResultProxy` returned as a result of the
         bulk DELETE operation.

        """


class AttributeEvents(event.Events):
    """Define events for object attributes.

    These are typically defined on the class-bound descriptor for the
    target class.

    e.g.::

        from sqlalchemy import event

        def my_append_listener(target, value, initiator):
            print "received append event for target: %s" % target

        event.listen(MyClass.collection, 'append', my_append_listener)

    Listeners have the option to return a possibly modified version
    of the value, when the ``retval=True`` flag is passed
    to :func:`~.event.listen`::

        def validate_phone(target, value, oldvalue, initiator):
            "Strip non-numeric characters from a phone number"

            return re.sub(r'(?![0-9])', '', value)

        # setup listener on UserContact.phone attribute, instructing
        # it to use the return value
        listen(UserContact.phone, 'set', validate_phone, retval=True)

    A validation function like the above can also raise an exception
    such as :class:`.ValueError` to halt the operation.

    Several modifiers are available to the :func:`~.event.listen` function.

    :param active_history=False: When True, indicates that the
      "set" event would like to receive the "old" value being
      replaced unconditionally, even if this requires firing off
      database loads. Note that ``active_history`` can also be
      set directly via :func:`.column_property` and
      :func:`.relationship`.

    :param propagate=False: When True, the listener function will
      be established not just for the class attribute given, but
      for attributes of the same name on all current subclasses 
      of that class, as well as all future subclasses of that 
      class, using an additional listener that listens for 
      instrumentation events.
    :param raw=False: When True, the "target" argument to the
      event will be the :class:`.InstanceState` management
      object, rather than the mapped instance itself.
    :param retval=False: when True, the user-defined event 
      listening must return the "value" argument from the 
      function.  This gives the listening function the opportunity
      to change the value that is ultimately used for a "set"
      or "append" event.

    """

    @classmethod
    def _accept_with(cls, target):
        # TODO: coverage
        if isinstance(target, orm.interfaces.MapperProperty):
            return getattr(target.parent.class_, target.key)
        else:
            return target

    @classmethod
    def _listen(cls, target, identifier, fn, active_history=False, 
                                        raw=False, retval=False,
                                        propagate=False):
        if active_history:
            target.dispatch._active_history = True

        # TODO: for removal, need to package the identity
        # of the wrapper with the original function.

        if not raw or not retval:
            orig_fn = fn
            def wrap(target, value, *arg):
                if not raw:
                    target = target.obj()
                if not retval:
                    orig_fn(target, value, *arg)
                    return value
                else:
                    return orig_fn(target, value, *arg)
            fn = wrap

        event.Events._listen(target, identifier, fn, propagate)

        if propagate:
            manager = orm.instrumentation.manager_of_class(target.class_)

            for mgr in manager.subclass_managers(True):
                event.Events._listen(mgr[target.key], identifier, fn, True)

    @classmethod
    def _remove(cls, identifier, target, fn):
        raise NotImplementedError("Removal of attribute events not yet implemented")

    def append(self, target, value, initiator):
        """Receive a collection append event.

        :param target: the object instance receiving the event.
          If the listener is registered with ``raw=True``, this will
          be the :class:`.InstanceState` object.
        :param value: the value being appended.  If this listener
          is registered with ``retval=True``, the listener
          function must return this value, or a new value which 
          replaces it.
        :param initiator: the attribute implementation object 
          which initiated this event.
        :return: if the event was registered with ``retval=True``,
         the given value, or a new effective value, should be returned.

        """

    def remove(self, target, value, initiator):
        """Receive a collection remove event.

        :param target: the object instance receiving the event.
          If the listener is registered with ``raw=True``, this will
          be the :class:`.InstanceState` object.
        :param value: the value being removed.
        :param initiator: the attribute implementation object 
          which initiated this event.
        :return: No return value is defined for this event.
        """

    def set(self, target, value, oldvalue, initiator):
        """Receive a scalar set event.

        :param target: the object instance receiving the event.
          If the listener is registered with ``raw=True``, this will
          be the :class:`.InstanceState` object.
        :param value: the value being set.  If this listener
          is registered with ``retval=True``, the listener
          function must return this value, or a new value which 
          replaces it.
        :param oldvalue: the previous value being replaced.  This
          may also be the symbol ``NEVER_SET`` or ``NO_VALUE``.
          If the listener is registered with ``active_history=True``,
          the previous value of the attribute will be loaded from
          the database if the existing value is currently unloaded 
          or expired.
        :param initiator: the attribute implementation object 
          which initiated this event.
        :return: if the event was registered with ``retval=True``,
         the given value, or a new effective value, should be returned.

        """
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.