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 Helper functions to search through a collection of entities
30 """
31 import logging
32
33 logger = logging.getLogger('camelot.view.search')
34
35 import camelot.types
36
38 """create a query decorator to search through a collection of entities
39 @param admin: the admin interface of the entity
40 @param text: the text to search for
41 @return: a function that can be applied to a query to make the query filter
42 only the objects related to the requested text
43 """
44 from elixir import entities
45 if len(text.strip()):
46 from sqlalchemy import Unicode, or_
47 args = []
48 search_tables = [admin.entity.table]
49 for entity in entities:
50 if issubclass(admin.entity, entity):
51 search_tables.append(entity.table)
52 for table in search_tables:
53 for c in table._columns:
54 if issubclass(c.type.__class__, camelot.types.Code):
55 codes = text.split('.')
56 args.append(c.like(['%'] + codes + ['%']))
57 args.append(c.like(['%'] + codes))
58 args.append(c.like(codes + ['%']))
59 elif issubclass(c.type.__class__, camelot.types.Image):
60 continue
61 elif issubclass(c.type.__class__, (Unicode, )) or \
62 (hasattr(c.type, 'impl') and \
63 issubclass(c.type.impl.__class__, (Unicode, ))):
64 logger.debug('look in column : %s'%c.name)
65 args.append(c.like('%'+text+'%'))
66 if len(args):
67 if len(args)>1:
68 return lambda q: q.filter(or_(*args))
69 else:
70 return lambda q: q.filter(args[0])
71 logger.debug('query args : %s'%str(args))
72 return lambda q: q
73