This file is indexed.

/usr/share/pyshared/schooltool/relationship/README.txt is in python-schooltool 1:2.1.0-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
Relationship
============

``schooltool.relationship`` is a library for managing arbitrary many-to-many
binary relationships.


Quick overview
--------------

This package lets you define arbitrary many-to-many relationship schemas and
use them to relate arbitrary components (that are annotatable or have an
adapter to `IRelationshipLinks`).

Usage example::

    # Establish a relationship
    Membership(member=frog, group=frogpond)

    # Find all related objects for a given role (URIGroup in this case)
    for group in getRelatedObjects(frog, URIGroup):
        print group

    Membership.unlink(member=frog, group=frogpond)

You can also define relationship properties in your component classes, and
rewrite the example above as::

    # Establish a relationship
    frogpond.members.add(frog)      # or frog.groups.add(frogpond)

    # Find all related objects for a given role (URIGroup in this case)
    for group in frogpond.members:
        print group

    # Remove a relationship
    frogpond.members.remove(frog)   # or frog.groups.remove(frogpond)


Details
-------

Relationship types and roles are identified by URIs (the idea was borrowed
from XLink and RDF).  You can use strings containing those URIs directly,
or you can use introspectable URI objects that also have an optional short name
and a description in addition to the URI itself.

    >>> from schooltool.relationship import URIObject

For example, a generic group membership relationship can be defined with the
following URIs:

    >>> URIMembership = URIObject('http://schooltool.org/ns/membership',
    ...                           'Membership', 'The membership relationship.')
    >>> URIGroup = URIObject('http://schooltool.org/ns/membership/group',
    ...                      'Group', 'A role of a containing group.')
    >>> URIMember = URIObject('http://schooltool.org/ns/membership/member',
    ...                       'Member', 'A group member role.')

To demonstrate relationships we need some objects that can be related.  Any
object that has an adapter to `IRelationshipLinks` can be used in relationships.
Since schooltool.relationship provides a default adapter from `IAnnotatable`
to `IRelationshipLinks`, it is enough to declare that our objects are
`IAttributeAnnotatable`.

    >>> from zope.interface import implements
    >>> from zope.annotation.interfaces import IAttributeAnnotatable
    >>> class SomeObject(object):
    ...     implements(IAttributeAnnotatable)
    ...     def __init__(self, name):
    ...         self._name = name
    ...     def __repr__(self):
    ...         return self._name

We need some setup to make Zope 3 annotations work.

    >>> from zope.app.testing import setup
    >>> setup.placelessSetUp()
    >>> setup.setUpAnnotations()

We need to define the adapter from `IAnnotatable` to `IRelationshipLinks`.
In real life you would include the ZCML configuration of the
``schooltool.relationship`` package via Zope 3 package includes.  In a test
you can use `setUpRelationships` from ``schooltool.relationship.tests``.

    >>> from schooltool.relationship.tests import setUpRelationships
    >>> setUpRelationships()

You can create relationships by calling the `relate` function

    >>> from schooltool.relationship import relate
    >>> frogs = SomeObject('frogs')
    >>> frogger = SomeObject('frogger')
    >>> relate(URIMembership, (frogs, URIGroup), (frogger, URIMember))

Since you will always want to use a particular set of roles for a given
relationship type, you can define a relationship schema and use it as a
shortcut::

    >>> from schooltool.relationship import RelationshipSchema
    >>> Membership = RelationshipSchema(URIMembership, group=URIGroup,
    ...                                 member=URIMember)

    >>> lilfroggy = SomeObject('lilfroggy')
    >>> Membership(member=lilfroggy, group=frogs)

If you try to create the same relationship between the same objects more
than once, you will get a `DuplicateRelationship` exception.

    >>> Membership(member=lilfroggy, group=frogs)
    Traceback (most recent call last):
      ...
    DuplicateRelationship

You can query relationships by calling the `getRelatedObjects` function.
It returns a list of objects in undefined order, so we'll define a function
to sort them alphabetically:

    >>> def sorted(list):
    ...     items = [(repr(item), item) for item in list]
    ...     items.sort()
    ...     return [row[-1] for row in items]

For example, you can get a list of all members of the "frogs" group like
this:

    >>> from schooltool.relationship import getRelatedObjects
    >>> sorted(getRelatedObjects(frogs, URIMember))
    [frogger, lilfroggy]

The relationship is bidirectional, so you can ask an object what groups it
belongs to

    >>> getRelatedObjects(frogger, URIGroup)
    [frogs]

You can also explicitly say that you want all `URIGroup`'s that participate
in a `URIMembership` relationship.

    >>> getRelatedObjects(frogger, URIGroup, URIMembership)
    [frogs]
    >>> getRelatedObjects(frogger, URIGroup, 'example:Groupship')
    []

In general, avoid reusing the same role for different relationship types.

You can remove relationships by calling the `unrelate` function::

    >>> from schooltool.relationship import unrelate
    >>> unrelate(URIMembership, (frogs, URIGroup), (frogger, URIMember))

    >>> getRelatedObjects(frogger, URIGroup)
    []
    >>> getRelatedObjects(frogs, URIMember)
    [lilfroggy]

If you try to remove a relationship that does not exist, you will get an
exception

    >>> unrelate(URIMembership, (frogs, URIMember), (frogger, URIGroup))
    Traceback (most recent call last):
      ...
    NoSuchRelationship

If you have a relationship schema, you can call its `unlink` method, as
a shortcut for the full unrelate call.

    >>> Membership.unlink(member=lilfroggy, group=frogs)
    >>> getRelatedObjects(frogs, URIMember)
    []

There is also an `unrelateAll` function that removes all relationships of
an object.  It is useful if you want to break all relationships when deleting
an object.


Relationship properties
-----------------------

You can define a property in a class and use it instead of explicitly
calling global functions and passing roles around::

    >>> from schooltool.relationship import RelationshipProperty

    >>> class Group(SomeObject):
    ...     members = RelationshipProperty(URIMembership, URIGroup, URIMember)

    >>> class Member(SomeObject):
    ...     groups = RelationshipProperty(URIMembership, URIMember, URIGroup)

Usage example::

    >>> fido = Member('fido')
    >>> dogs = Group('dogs')

    >>> list(fido.groups)
    []
    >>> list(dogs.members)
    []

    >>> bool(fido.groups)
    False

    >>> dogs.members.add(fido)

    >>> list(fido.groups)
    [dogs]
    >>> list(dogs.members)
    [fido]

    >>> bool(fido.groups)
    True
    >>> len(fido.groups)
    1

    >>> fido.groups.remove(dogs)

    >>> list(fido.groups)
    []
    >>> list(dogs.members)
    []


Events
------

    >>> import zope.event
    >>> old_subscribers = zope.event.subscribers
    >>> zope.event.subscribers = []

Before you establish a relationship, a `BeforeRelationshipEvent` is sent out.
You can implement constraints by raising an exception in an event subscriber::

    >>> from zope.interface import Interface, directlyProvides
    >>> class IFrog(Interface):
    ...     pass

    >>> from schooltool.relationship.interfaces import IBeforeRelationshipEvent
    >>> def no_toads(event):
    ...     if (IBeforeRelationshipEvent.providedBy(event) and
    ...             event.rel_type == URIMembership and
    ...             event[URIGroup] is frogs and
    ...             not IFrog.providedBy(event[URIMember])):
    ...         raise Exception("Only frogs can be members of the frogs group")
    >>> zope.event.subscribers.append(no_toads)

    >>> toady = SomeObject('toady')
    >>> Membership(member=toady, group=frogs)
    Traceback (most recent call last):
      ...
    Exception: Only frogs can be members of the frogs group

When you establish a relationship, a `RelationshipAddedEvent` is sent out::

    >>> from schooltool.relationship.interfaces import IRelationshipAddedEvent
    >>> def my_subscriber(event):
    ...     if IRelationshipAddedEvent.providedBy(event):
    ...         print 'Relationship %s added between %s (%s) and %s (%s)' % (
    ...                     event.rel_type.name,
    ...                     event.participant1, event.role1.name,
    ...                     event.participant2, event.role2.name)
    ...         if event.extra_info:
    ...             print '(BTW, %s)' % event.extra_info
    >>> zope.event.subscribers.append(my_subscriber)

    >>> kermit = SomeObject('kermit')
    >>> directlyProvides(kermit, IFrog)
    >>> Membership(member=kermit, group=frogs)
    Relationship Membership added between kermit (Member) and frogs (Group)

Before you break a relationship, a `BeforeRemovingRelationshipEvent` is sent
out. You can implement constraints by raising exceptions in the subscriber (e.g.
prevent members from leaving a group before they do something they have to
do).

When you break a relationship, a `RelationshipRemovedEvent` is sent out::

    >>> from schooltool.relationship.interfaces \
    ...         import IBeforeRemovingRelationshipEvent
    >>> from schooltool.relationship.interfaces \
    ...         import IRelationshipRemovedEvent
    >>> def my_subscriber(event):
    ...     if IBeforeRemovingRelationshipEvent.providedBy(event):
    ...         if (event.rel_type == URIMembership
    ...             and event[URIMember] is kermit):
    ...             print "Please don't leave us!"
    ...     if IRelationshipRemovedEvent.providedBy(event):
    ...         print 'Relationship %s between %s (%s) and %s (%s) removed' % (
    ...                     event.rel_type.name,
    ...                     event.participant1, event.role1.name,
    ...                     event.participant2, event.role2.name)
    ...         if event.extra_info:
    ...             print '(BTW, %s)' % event.extra_info
    >>> zope.event.subscribers.append(my_subscriber)

    >>> Membership.unlink(member=kermit, group=frogs)
    Please don't leave us!
    Relationship Membership between kermit (Member) and frogs (Group) removed


Symmetric relationships
-----------------------

Symmetric relationships work too::

    >>> URIFriendship = URIObject('example:Friendship', 'Friendship')
    >>> URIFriend = URIObject('example:Friend', 'Friend')

    >>> Friendship = RelationshipSchema(URIFriendship,
    ...                                 one=URIFriend, other=URIFriend)
    >>> Friendship(one=fido, other=kermit)
    Relationship Friendship added between kermit (Friend) and fido (Friend)

    >>> class FriendlyObject(SomeObject):
    ...     friends = RelationshipProperty(URIFriendship, URIFriend, URIFriend)

    >>> neko = FriendlyObject('neko')
    >>> neko.friends.add(kermit)
    Relationship Friendship added between neko (Friend) and kermit (Friend)
    >>> list(neko.friends)
    [kermit]
    >>> sorted(getRelatedObjects(kermit, URIFriend))
    [fido, neko]

Note that if you use symmetric relationships, you cannot use `__getitem__`
on `IBeforeRelationshipEvent`'s.


Annotated relationships
-----------------------

Sometimes you may want to attach some extra information to a relationship (e.g.
a label).  You can do so by passing an extra argument to `relate` and
`unrelate`:

    >>> relate(URIFriendship, (kermit, URIFriend), (frogger, URIFriend),
    ...        'kermit and frogger know each other for years')
    Relationship Friendship added between kermit (Friend) and frogger (Friend)
    (BTW, kermit and frogger know each other for years)

This extra argument should be either a read-only object, or a subclass of
persistent.Persistent, because references to this object will be stored from
both relationship sides.

You can access this extra information from relationship links directly:

    >>> from schooltool.relationship.interfaces import IRelationshipLinks
    >>> for link in IRelationshipLinks(kermit):
    ...     if link.extra_info:
    ...         print link.extra_info
    kermit and frogger know each other for years

Since this is very inconvenient, I expect you will write your own access
properties that mimic `RelationshipProperty`, and override the `__iter__`
method.  For example:

    >>> from schooltool.relationship.relationship import BoundRelationshipProperty
    >>> class FriendshipProperty(object):
    ...     def __get__(self, instance, owner):
    ...         if instance is None: return self
    ...         return BoundFriendshipProperty(instance)
    >>> class BoundFriendshipProperty(BoundRelationshipProperty):
    ...     def __init__(self, this):
    ...         BoundRelationshipProperty.__init__(self, this, URIFriendship,
    ...                                            URIFriend, URIFriend)
    ...     def __iter__(self):
    ...         for link in IRelationshipLinks(self.this):
    ...             if link.role == self.other_role and link.rel_type == self.rel_type:
    ...                 yield link.target, link.extra_info

You can then use it like this::

    >>> class Friend(SomeObject):
    ...     friends = FriendshipProperty()

    >>> fluffy = Friend('fluffy')
    >>> fluffy.friends.add(kermit,
    ...         'fluffy just met kermit, but fluffy is very friendly')
    Relationship Friendship added between fluffy (Friend) and kermit (Friend)
    (BTW, fluffy just met kermit, but fluffy is very friendly)

    >>> for friend, extra_info in fluffy.friends:
    ...     print '%s: %s' % (friend, extra_info)
    kermit: fluffy just met kermit, but fluffy is very friendly

As you see, the extra info is accessible to all event handlers

    >>> fluffy.friends.remove(kermit)
    Relationship Friendship between fluffy (Friend) and kermit (Friend) removed
    (BTW, fluffy just met kermit, but fluffy is very friendly)


Caveats
-------

- When you delete objects, you should remove all relationships for those
  objects.  If you use Zope 3 objects events, you can register the
  `unrelateOnDeletion` event handler from ``schooltool.relationship.objectevents``.
  `configure.zcml` of ``schooltool.relationship`` does that.

- When you copy objects (e.g. using Zope's `IObjectCopier`), you should take
  care to ensure that you do not duplicate just one half of relationship
  links.  It is tricky.  locationCopy from zope.location.pickling
  performs deep copies of all objects that are located within the object you
  are copying.  It works if all relationships are within this subtree (or
  outside it).  You will get problems if you have a relationship between
  an object that is copied and another object that is not copied.

  You can register the `unrelateOnCopy` event handler from
  ``schooltool.relationship.objectevents`` to solve *part* of the problem
  (`configure.zcml` of ``schooltool.relationship`` does that).  This event handler
  removes all relationships from the copy of the object that you are copying.
  It does not traverse the whole deply-copied subtree, therefore if you
  have subobjects that participate in relationships with objects outside of
  the subtree, you will have problems.

  An alternative solution is to disallow copying of objects that may have
  subobjects related with other objects that are not located within the
  original object.  To do so, declare and `IObjectCopier` adapter for the object
  and make the `copyable` method return False.


.. Cleaning up

    >>> zope.event.subscribers = old_subscribers
    >>> setup.placelessTearDown()