1 | """ORM Wrappers""" |
---|
2 | import inspect |
---|
3 | from webhelpers.util import Partial |
---|
4 | |
---|
5 | orms = {} |
---|
6 | try: |
---|
7 | import sqlobject |
---|
8 | except: |
---|
9 | pass |
---|
10 | else: |
---|
11 | orms['sqlobject'] = True |
---|
12 | try: |
---|
13 | import sqlalchemy |
---|
14 | except: |
---|
15 | pass |
---|
16 | else: |
---|
17 | orms['sqlalchemy'] = True |
---|
18 | |
---|
19 | def get_wrapper(obj, *args, **kw): |
---|
20 | if isinstance(obj, (list, tuple)): |
---|
21 | return obj |
---|
22 | if orms.get('sqlobject'): |
---|
23 | if inspect.isclass(obj) and issubclass(obj, sqlobject.SQLObject): |
---|
24 | return SQLObjectLazy(obj.select, *args, **kw) |
---|
25 | if orms.get('sqlalchemy'): |
---|
26 | if hasattr(obj, '_is_primary_mapper'): |
---|
27 | return SQLAlchemyLazyMapper(obj, *args, **kw) |
---|
28 | if isinstance(obj, sqlalchemy.Table): |
---|
29 | return SQLAlchemyLazyTable(obj, *args, **kw) |
---|
30 | return "You shouldn't have this" |
---|
31 | |
---|
32 | |
---|
33 | class SQLObjectLazy(Partial): |
---|
34 | def __getitem__(self, key): |
---|
35 | if not isinstance(key, slice): |
---|
36 | raise Exception, "SQLObjectLazy doesn't support getitem without slicing" |
---|
37 | return list(self()[key.start:key.stop]) |
---|
38 | |
---|
39 | def __len__(self): |
---|
40 | return self().count() |
---|
41 | |
---|
42 | class SQLAlchemyLazyTable(Partial): |
---|
43 | def __getitem__(self, key): |
---|
44 | if not isinstance(key, slice): |
---|
45 | raise Exception, "SQLAlchemyLazy doesn't support getitem without slicing" |
---|
46 | limit = key.stop - key.start |
---|
47 | offset = key.start |
---|
48 | fn = self.fn |
---|
49 | self.fn = fn.select |
---|
50 | results = self(limit=limit, offset=offset).execute() |
---|
51 | self.fn = fn |
---|
52 | return results |
---|
53 | |
---|
54 | def __len__(self): |
---|
55 | s = self.fn.select(*self.args, **self.kw) |
---|
56 | return self.fn([func.count(1)], from_obj=[s]) |
---|
57 | |
---|
58 | class SQLAlchemyLazyMapper(Partial): |
---|
59 | def __getitem__(self, key): |
---|
60 | if not isinstance(key, slice): |
---|
61 | raise Exception, "SQLAlchemyLazy doesn't support getitem without slicing" |
---|
62 | limit = key.stop - key.start |
---|
63 | offset = key.start |
---|
64 | fn = self.fn |
---|
65 | self.fn = fn.select |
---|
66 | results = self(limit=limit, offset=offset) |
---|
67 | self.fn = fn |
---|
68 | return results |
---|
69 | |
---|
70 | def __len__(self): |
---|
71 | return self.fn.count(*self.args, **self.kw) |
---|