-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathevents.py
More file actions
612 lines (553 loc) · 17.9 KB
/
Copy pathevents.py
File metadata and controls
612 lines (553 loc) · 17.9 KB
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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2014 uralbash <root@uralbash.ru>
#
# Distributed under terms of the MIT license.
"""
SQLAlchemy events extension
"""
# standard library
import weakref
# SQLAlchemy
from sqlalchemy import and_, case, event, select, inspection
from sqlalchemy.orm import object_session
from sqlalchemy.sql import func
from sqlalchemy.orm.base import NO_VALUE
def _insert_subtree(
table,
connection,
node_size,
node_pos_left,
node_pos_right,
parent_pos_left,
parent_pos_right,
subtree,
parent_tree_id,
parent_level,
node_level,
left_sibling,
table_pk
):
# step 1: rebuild inserted subtree
delta_lft = left_sibling['lft'] + 1
if not left_sibling['is_parent']:
delta_lft = left_sibling['rgt'] + 1
delta_rgt = delta_lft + node_size - 1
connection.execute(
table.update(
table_pk.in_(subtree)
).values(
lft=table.c.lft - node_pos_left + delta_lft,
rgt=table.c.rgt - node_pos_right + delta_rgt,
level=table.c.level - node_level + parent_level + 1,
tree_id=parent_tree_id
)
)
# step 2: update key of right side
connection.execute(
table.update(
and_(
table.c.rgt > delta_lft - 1,
table_pk.notin_(subtree),
table.c.tree_id == parent_tree_id
)
).values(
rgt=table.c.rgt + node_size,
lft=case(
[
(
table.c.lft > left_sibling['lft'],
table.c.lft + node_size
)
],
else_=table.c.lft
)
)
)
def _get_tree_table(mapper):
for table in mapper.tables:
if all(key in table.c for key in ['level', 'lft', 'rgt', 'parent_id']):
return table
def mptt_before_insert(mapper, connection, instance):
""" Based on example
https://bitbucket.org/zzzeek/sqlalchemy/src/73095b353124/examples/nested_sets/nested_sets.py?at=master
"""
table = _get_tree_table(mapper)
db_pk = instance.get_pk_column()
table_pk = getattr(table.c, db_pk.name)
if instance.parent_id is None:
instance.left = 1
instance.right = 2
instance.level = instance.get_default_level()
tree_id = connection.scalar(
select(
[
func.max(table.c.tree_id) + 1
]
)
) or 1
instance.tree_id = tree_id
else:
(parent_pos_left,
parent_pos_right,
parent_tree_id,
parent_level) = connection.execute(
select(
[
table.c.lft,
table.c.rgt,
table.c.tree_id,
table.c.level
]
).where(
table_pk == instance.parent_id
)
).fetchone()
# Update key of right side
connection.execute(
table.update(
and_(table.c.rgt >= parent_pos_right,
table.c.tree_id == parent_tree_id)
).values(
lft=case(
[
(
table.c.lft > parent_pos_right,
table.c.lft + 2
)
],
else_=table.c.lft
),
rgt=case(
[
(
table.c.rgt >= parent_pos_right,
table.c.rgt + 2
)
],
else_=table.c.rgt
)
)
)
instance.level = parent_level + 1
instance.tree_id = parent_tree_id
instance.left = parent_pos_right
instance.right = parent_pos_right + 1
def mptt_before_delete(mapper, connection, instance, delete=True):
table = _get_tree_table(mapper)
tree_id = instance.tree_id
pk = getattr(instance, instance.get_pk_name())
db_pk = instance.get_pk_column()
table_pk = getattr(table.c, db_pk.name)
lft, rgt = connection.execute(
select(
[
table.c.lft,
table.c.rgt
]
).where(
table_pk == pk
)
).fetchone()
delta = rgt - lft + 1
if delete:
mapper.base_mapper.confirm_deleted_rows = False
connection.execute(
table.delete(
table_pk == pk
)
)
if instance.parent_id is not None or not delete:
""" Update key of current tree
UPDATE tree
SET left_id = CASE
WHEN left_id > $leftId THEN left_id - $delta
ELSE left_id
END,
right_id = CASE
WHEN right_id >= $rightId THEN right_id - $delta
ELSE right_id
END
"""
connection.execute(
table.update(
and_(
table.c.rgt > rgt,
table.c.tree_id == tree_id
)
).values(
lft=case(
[
(
table.c.lft > lft,
table.c.lft - delta
)
],
else_=table.c.lft
),
rgt=case(
[
(
table.c.rgt >= rgt,
table.c.rgt - delta
)
],
else_=table.c.rgt
)
)
)
def mptt_before_update(mapper, connection, instance):
""" Based on this example:
http://stackoverflow.com/questions/889527/move-node-in-nested-set
"""
node_id = getattr(instance, instance.get_pk_name())
table = _get_tree_table(mapper)
db_pk = instance.get_pk_column()
default_level = instance.get_default_level()
table_pk = getattr(table.c, db_pk.name)
mptt_move_inside = None
left_sibling = None
left_sibling_tree_id = None
if hasattr(instance, 'mptt_move_inside'):
mptt_move_inside = instance.mptt_move_inside
if hasattr(instance, 'mptt_move_before'):
(
right_sibling_left,
right_sibling_right,
right_sibling_parent,
right_sibling_level,
right_sibling_tree_id
) = connection.execute(
select(
[
table.c.lft,
table.c.rgt,
table.c.parent_id,
table.c.level,
table.c.tree_id
]
).where(
table_pk == instance.mptt_move_before
)
).fetchone()
current_lvl_nodes = connection.execute(
select(
[
table.c.lft,
table.c.rgt,
table.c.parent_id,
table.c.tree_id
]
).where(
and_(
table.c.level == right_sibling_level,
table.c.tree_id == right_sibling_tree_id,
table.c.lft < right_sibling_left
)
)
).fetchall()
if current_lvl_nodes:
(
left_sibling_left,
left_sibling_right,
left_sibling_parent,
left_sibling_tree_id
) = current_lvl_nodes[-1]
instance.parent_id = left_sibling_parent
left_sibling = {
'lft': left_sibling_left,
'rgt': left_sibling_right,
'is_parent': False
}
# if move_before to top level
elif not right_sibling_parent:
left_sibling_tree_id = right_sibling_tree_id - 1
# if placed after a particular node
if hasattr(instance, 'mptt_move_after'):
(
left_sibling_left,
left_sibling_right,
left_sibling_parent,
left_sibling_tree_id
) = connection.execute(
select(
[
table.c.lft,
table.c.rgt,
table.c.parent_id,
table.c.tree_id
]
).where(
table_pk == instance.mptt_move_after
)
).fetchone()
instance.parent_id = left_sibling_parent
left_sibling = {
'lft': left_sibling_left,
'rgt': left_sibling_right,
'is_parent': False
}
""" Get subtree from node
SELECT id, name, level FROM my_tree
WHERE left_key >= $left_key AND right_key <= $right_key
ORDER BY left_key
"""
subtree = connection.execute(
select([table_pk])
.where(
and_(
table.c.lft >= instance.left,
table.c.rgt <= instance.right,
table.c.tree_id == instance.tree_id
)
).order_by(
table.c.lft
)
).fetchall()
subtree = [x[0] for x in subtree]
""" step 0: Initialize parameters.
Put there left and right position of moving node
"""
(
node_pos_left,
node_pos_right,
node_tree_id,
node_parent_id,
node_level
) = connection.execute(
select(
[
table.c.lft,
table.c.rgt,
table.c.tree_id,
table.c.parent_id,
table.c.level
]
).where(
table_pk == node_id
)
).fetchone()
# if instance just update w/o move
# XXX why this str() around parent_id comparison?
if not left_sibling \
and str(node_parent_id) == str(instance.parent_id) \
and not mptt_move_inside:
if left_sibling_tree_id is None:
return
# fix tree shorting
if instance.parent_id is not None:
(
parent_id,
parent_pos_right,
parent_pos_left,
parent_tree_id,
parent_level
) = connection.execute(
select(
[
table_pk,
table.c.rgt,
table.c.lft,
table.c.tree_id,
table.c.level
]
).where(
table_pk == instance.parent_id
)
).fetchone()
if node_parent_id is None and node_tree_id == parent_tree_id:
instance.parent_id = None
return
# delete from old tree
mptt_before_delete(mapper, connection, instance, False)
if instance.parent_id is not None:
""" Put there right position of new parent node (there moving node
should be moved)
"""
(
parent_id,
parent_pos_right,
parent_pos_left,
parent_tree_id,
parent_level
) = connection.execute(
select(
[
table_pk,
table.c.rgt,
table.c.lft,
table.c.tree_id,
table.c.level
]
).where(
table_pk == instance.parent_id
)
).fetchone()
# 'size' of moving node (including all it's sub nodes)
node_size = node_pos_right - node_pos_left + 1
# left sibling node
if not left_sibling:
left_sibling = {
'lft': parent_pos_left,
'rgt': parent_pos_right,
'is_parent': True
}
# insert subtree in exist tree
instance.tree_id = parent_tree_id
_insert_subtree(
table,
connection,
node_size,
node_pos_left,
node_pos_right,
parent_pos_left,
parent_pos_right,
subtree,
parent_tree_id,
parent_level,
node_level,
left_sibling,
table_pk
)
else:
# if insert after
if left_sibling_tree_id or left_sibling_tree_id == 0:
tree_id = left_sibling_tree_id + 1
connection.execute(
table.update(
table.c.tree_id > left_sibling_tree_id
).values(
tree_id=table.c.tree_id + 1
)
)
# if just insert
else:
tree_id = connection.scalar(
select(
[
func.max(table.c.tree_id) + 1
]
)
)
connection.execute(
table.update(
table_pk.in_(
subtree
)
).values(
lft=table.c.lft - node_pos_left + 1,
rgt=table.c.rgt - node_pos_left + 1,
level=table.c.level - node_level + default_level,
tree_id=tree_id
)
)
class _WeakDefaultDict(weakref.WeakKeyDictionary):
"""A weak reference dictionary that returns a new `WeakSet` as a default
value for missing keys."""
def __getitem__(self, key):
try:
return super(_WeakDefaultDict, self).__getitem__(key)
except KeyError:
self[key] = value = weakref.WeakSet()
return value
class TreesManager(object):
"""
Manages events dispatching for all subclasses of a given class.
"""
def __init__(self, base_class):
self.base_class = base_class
self.classes = set()
self.instances = _WeakDefaultDict()
def register_events(self, remove=False):
for e, h in (
('before_insert', self.before_insert),
('before_update', self.before_update),
('before_delete', self.before_delete),
):
is_event_exist = event.contains(self.base_class, e, h)
if remove and is_event_exist:
event.remove(self.base_class, e, h)
elif not is_event_exist:
event.listen(self.base_class, e, h, propagate=True)
return self
def register_factory(self, sessionmaker):
"""
Registers this TreesManager instance to respond on
`after_flush_postexec` events on the given session or session factory.
This method returns the original argument, so that it can be used by
wrapping an already existing instance:
.. code-block:: python
:linenos:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, mapper
from sqlalchemy_mptt.mixins import BaseNestedSets
engine = create_engine('...')
trees_manager = TreesManager(BaseNestedSets)
trees_manager.register_mapper(mapper)
Session = tree_manager.register_factory(
sessionmaker(bind=engine)
)
A reference to this method, bound to a default instance of this class
and already registered to a mapper, is importable directly from
`sqlalchemy_mptt`:
.. code-block:: python
:linenos:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_mptt import mptt_sessionmaker
engine = create_engine('...')
Session = mptt_sessionmaker(sessionmaker(bind=engine))
"""
event.listen(sessionmaker, 'after_flush_postexec',
self.after_flush_postexec)
return sessionmaker
def before_insert(self, mapper, connection, instance):
session = object_session(instance)
self.instances[session].add(instance)
mptt_before_insert(mapper, connection, instance)
def before_update(self, mapper, connection, instance):
session = object_session(instance)
self.instances[session].add(instance)
mptt_before_update(mapper, connection, instance)
def before_delete(self, mapper, connection, instance):
session = object_session(instance)
self.instances[session].discard(instance)
mptt_before_delete(mapper, connection, instance)
def after_flush_postexec(self, session, context):
"""
Event listener to recursively expire `left` and `right` attributes the
parents of all modified instances part of this flush.
"""
instances = self.instances[session]
while True:
try:
instance = instances.pop()
except KeyError:
break
if instance not in session:
continue
parent = self.get_parent_value(instance)
while parent != NO_VALUE and parent is not None:
instances.discard(parent)
session.expire(parent, ['left', 'right', 'tree_id', 'level'])
parent = self.get_parent_value(parent)
else:
session.expire(instance, ['left', 'right', 'tree_id', 'level'])
self.expire_session_for_children(session, instance)
@staticmethod
def get_parent_value(instance):
return inspection.inspect(instance).attrs.parent.loaded_value
@staticmethod
def expire_session_for_children(session, instance):
children = instance.children
def expire_recursively(node):
children = node.children
for item in children:
session.expire(item, ['left', 'right', 'tree_id', 'level'])
expire_recursively(item)
if children != NO_VALUE and children is not None:
for item in children:
session.expire(item, ['left', 'right', 'tree_id', 'level'])
expire_recursively(item)