author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Fri, 26 Feb 2010 13:24:47 +0100 | |
branch | stable |
changeset 4721 | 8f63691ccb7f |
parent 4716 | 55b6a3262071 |
child 4768 | 430b89aed996 |
permissions | -rw-r--r-- |
0 | 1 |
"""DB-API 2.0 compliant module |
2 |
||
3 |
Take a look at http://www.python.org/peps/pep-0249.html |
|
4 |
||
5 |
(most parts of this document are reported here in docstrings) |
|
6 |
||
7 |
:organization: Logilab |
|
4212
ab6573088b4a
update copyright: welcome 2010
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
3833
diff
changeset
|
8 |
:copyright: 2001-2010 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 9 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1923
diff
changeset
|
10 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 11 |
""" |
12 |
__docformat__ = "restructuredtext en" |
|
13 |
||
1132 | 14 |
from logging import getLogger |
0 | 15 |
from time import time, clock |
2496
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
16 |
from itertools import count |
0 | 17 |
|
1923
3802c2e37e72
handle speaking to an instance using old entity types
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1882
diff
changeset
|
18 |
from logilab.common.logging_ext import set_log_methods |
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
19 |
from logilab.common.decorators import monkeypatch |
2657
de974465d381
[appobject] kill VObject class, move base selector classes to appobject
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2650
diff
changeset
|
20 |
from logilab.common.deprecation import deprecated |
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
21 |
|
2792
135580d15d42
rename and move cw.RequestSessionMixIn to cw.req.RequestSessionBase; move some appobjects methods where they actually belong to
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2770
diff
changeset
|
22 |
from cubicweb import ETYPE_NAME_MAP, ConnectionError, cwvreg, cwconfig |
135580d15d42
rename and move cw.RequestSessionMixIn to cw.req.RequestSessionBase; move some appobjects methods where they actually belong to
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2770
diff
changeset
|
23 |
from cubicweb.req import RequestSessionBase |
135580d15d42
rename and move cw.RequestSessionMixIn to cw.req.RequestSessionBase; move some appobjects methods where they actually belong to
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2770
diff
changeset
|
24 |
|
1524 | 25 |
|
0 | 26 |
_MARKER = object() |
27 |
||
2496
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
28 |
def _fake_property_value(self, name): |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
29 |
try: |
4716
55b6a3262071
fix some pylint detected errors
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4705
diff
changeset
|
30 |
return super(DBAPIRequest, self).property_value(name) |
2496
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
31 |
except KeyError: |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
32 |
return '' |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
33 |
|
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
34 |
def multiple_connections_fix(): |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
35 |
"""some monkey patching necessary when an application has to deal with |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
36 |
several connections to different repositories. It tries to hide buggy class |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
37 |
attributes since classes are not designed to be shared among multiple |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
38 |
registries. |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
39 |
""" |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
40 |
defaultcls = cwvreg.VRegistry.REGISTRY_FACTORY[None] |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
41 |
|
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
42 |
etypescls = cwvreg.VRegistry.REGISTRY_FACTORY['etypes'] |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
43 |
orig_etype_class = etypescls.orig_etype_class = etypescls.etype_class |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
44 |
@monkeypatch(defaultcls) |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
45 |
def etype_class(self, etype): |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
46 |
"""return an entity class for the given entity type. |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
47 |
Try to find out a specific class for this kind of entity or |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
48 |
default to a dump of the class registered for 'Any' |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
49 |
""" |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
50 |
usercls = orig_etype_class(self, etype) |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
51 |
if etype == 'Any': |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
52 |
return usercls |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
53 |
usercls.e_schema = self.schema.eschema(etype) |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
54 |
return usercls |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
55 |
|
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
56 |
def multiple_connections_unfix(): |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
57 |
etypescls = cwvreg.VRegistry.REGISTRY_FACTORY['etypes'] |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
58 |
etypescls.etype_class = etypescls.orig_etype_class |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
59 |
|
0 | 60 |
class ConnectionProperties(object): |
61 |
def __init__(self, cnxtype=None, lang=None, close=True, log=False): |
|
62 |
self.cnxtype = cnxtype or 'pyro' |
|
63 |
self.lang = lang |
|
64 |
self.log_queries = log |
|
65 |
self.close_on_del = close |
|
66 |
||
67 |
||
68 |
def get_repository(method, database=None, config=None, vreg=None): |
|
69 |
"""get a proxy object to the CubicWeb repository, using a specific RPC method. |
|
1524 | 70 |
|
0 | 71 |
Only 'in-memory' and 'pyro' are supported for now. Either vreg or config |
72 |
argument should be given |
|
73 |
""" |
|
74 |
assert method in ('pyro', 'inmemory') |
|
75 |
assert vreg or config |
|
76 |
if vreg and not config: |
|
77 |
config = vreg.config |
|
78 |
if method == 'inmemory': |
|
79 |
# get local access to the repository |
|
80 |
from cubicweb.server.repository import Repository |
|
81 |
return Repository(config, vreg=vreg) |
|
82 |
else: # method == 'pyro' |
|
83 |
# resolve the Pyro object |
|
2665
0c6281487f90
[pyro] use lgc.pyro_ext, simplify pyro related options
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2657
diff
changeset
|
84 |
from logilab.common.pyro_ext import ns_get_proxy |
0 | 85 |
try: |
2665
0c6281487f90
[pyro] use lgc.pyro_ext, simplify pyro related options
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2657
diff
changeset
|
86 |
return ns_get_proxy(database, |
0c6281487f90
[pyro] use lgc.pyro_ext, simplify pyro related options
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2657
diff
changeset
|
87 |
defaultnsgroup=config['pyro-ns-group'], |
0c6281487f90
[pyro] use lgc.pyro_ext, simplify pyro related options
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2657
diff
changeset
|
88 |
nshost=config['pyro-ns-host']) |
0c6281487f90
[pyro] use lgc.pyro_ext, simplify pyro related options
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2657
diff
changeset
|
89 |
except Exception, ex: |
0c6281487f90
[pyro] use lgc.pyro_ext, simplify pyro related options
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2657
diff
changeset
|
90 |
raise ConnectionError(str(ex)) |
1524 | 91 |
|
3647
2941f4a0aab9
refactor repo authentication to allow pluggable authentifier to login with something else than a password
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
92 |
def repo_connect(repo, login, **kwargs): |
0 | 93 |
"""Constructor to create a new connection to the CubicWeb repository. |
1524 | 94 |
|
0 | 95 |
Returns a Connection instance. |
96 |
""" |
|
3647
2941f4a0aab9
refactor repo authentication to allow pluggable authentifier to login with something else than a password
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
97 |
if not 'cnxprops' in kwargs: |
2941f4a0aab9
refactor repo authentication to allow pluggable authentifier to login with something else than a password
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
98 |
kwargs['cnxprops'] = ConnectionProperties('inmemory') |
2941f4a0aab9
refactor repo authentication to allow pluggable authentifier to login with something else than a password
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
99 |
cnxid = repo.connect(unicode(login), **kwargs) |
2941f4a0aab9
refactor repo authentication to allow pluggable authentifier to login with something else than a password
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
100 |
cnx = Connection(repo, cnxid, kwargs['cnxprops']) |
2941f4a0aab9
refactor repo authentication to allow pluggable authentifier to login with something else than a password
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
101 |
if kwargs['cnxprops'].cnxtype == 'inmemory': |
0 | 102 |
cnx.vreg = repo.vreg |
103 |
return cnx |
|
1524 | 104 |
|
3647
2941f4a0aab9
refactor repo authentication to allow pluggable authentifier to login with something else than a password
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
105 |
def connect(database=None, login=None, host=None, group=None, |
2941f4a0aab9
refactor repo authentication to allow pluggable authentifier to login with something else than a password
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
106 |
cnxprops=None, setvreg=True, mulcnx=True, initlog=True, **kwargs): |
0 | 107 |
"""Constructor for creating a connection to the CubicWeb repository. |
108 |
Returns a Connection object. |
|
109 |
||
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
110 |
When method is 'pyro', setvreg is True, try to deal with connections to |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
111 |
differents instances in the same process unless specified otherwise by |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
112 |
setting the mulcnx to False. |
0 | 113 |
""" |
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
114 |
config = cwconfig.CubicWebNoAppConfiguration() |
0 | 115 |
if host: |
116 |
config.global_set_option('pyro-ns-host', host) |
|
117 |
if group: |
|
118 |
config.global_set_option('pyro-ns-group', group) |
|
119 |
cnxprops = cnxprops or ConnectionProperties() |
|
120 |
method = cnxprops.cnxtype |
|
121 |
repo = get_repository(method, database, config=config) |
|
122 |
if method == 'inmemory': |
|
123 |
vreg = repo.vreg |
|
124 |
elif setvreg: |
|
125 |
if mulcnx: |
|
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
126 |
multiple_connections_fix() |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
127 |
vreg = cwvreg.CubicWebVRegistry(config, initlog=initlog) |
1923
3802c2e37e72
handle speaking to an instance using old entity types
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1882
diff
changeset
|
128 |
schema = repo.get_schema() |
3802c2e37e72
handle speaking to an instance using old entity types
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1882
diff
changeset
|
129 |
for oldetype, newetype in ETYPE_NAME_MAP.items(): |
3802c2e37e72
handle speaking to an instance using old entity types
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1882
diff
changeset
|
130 |
if oldetype in schema: |
3802c2e37e72
handle speaking to an instance using old entity types
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1882
diff
changeset
|
131 |
print 'aliasing', newetype, 'to', oldetype |
3802c2e37e72
handle speaking to an instance using old entity types
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1882
diff
changeset
|
132 |
schema._entities[newetype] = schema._entities[oldetype] |
3802c2e37e72
handle speaking to an instance using old entity types
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1882
diff
changeset
|
133 |
vreg.set_schema(schema) |
0 | 134 |
else: |
135 |
vreg = None |
|
3647
2941f4a0aab9
refactor repo authentication to allow pluggable authentifier to login with something else than a password
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
136 |
cnx = repo_connect(repo, login, cnxprops=cnxprops, **kwargs) |
0 | 137 |
cnx.vreg = vreg |
138 |
return cnx |
|
139 |
||
3647
2941f4a0aab9
refactor repo authentication to allow pluggable authentifier to login with something else than a password
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
140 |
def in_memory_cnx(config, login, **kwargs): |
0 | 141 |
"""usefull method for testing and scripting to get a dbapi.Connection |
1524 | 142 |
object connected to an in-memory repository instance |
0 | 143 |
""" |
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
144 |
if isinstance(config, cwvreg.CubicWebVRegistry): |
0 | 145 |
vreg = config |
146 |
config = None |
|
147 |
else: |
|
148 |
vreg = None |
|
149 |
# get local access to the repository |
|
150 |
repo = get_repository('inmemory', config=config, vreg=vreg) |
|
151 |
# connection to the CubicWeb repository |
|
152 |
cnxprops = ConnectionProperties('inmemory') |
|
3647
2941f4a0aab9
refactor repo authentication to allow pluggable authentifier to login with something else than a password
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3293
diff
changeset
|
153 |
cnx = repo_connect(repo, login, cnxprops=cnxprops, **kwargs) |
0 | 154 |
return repo, cnx |
155 |
||
156 |
||
2792
135580d15d42
rename and move cw.RequestSessionMixIn to cw.req.RequestSessionBase; move some appobjects methods where they actually belong to
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2770
diff
changeset
|
157 |
class DBAPIRequest(RequestSessionBase): |
1524 | 158 |
|
0 | 159 |
def __init__(self, vreg, cnx=None): |
160 |
super(DBAPIRequest, self).__init__(vreg) |
|
161 |
try: |
|
162 |
# no vreg or config which doesn't handle translations |
|
163 |
self.translations = vreg.config.translations |
|
164 |
except AttributeError: |
|
165 |
self.translations = {} |
|
166 |
self.set_default_language(vreg) |
|
167 |
# cache entities built during the request |
|
168 |
self._eid_cache = {} |
|
169 |
# these args are initialized after a connection is |
|
170 |
# established |
|
171 |
self.cnx = None # connection associated to the request |
|
172 |
self._user = None # request's user, set at authentication |
|
173 |
if cnx is not None: |
|
174 |
self.set_connection(cnx) |
|
175 |
||
176 |
def base_url(self): |
|
177 |
return self.vreg.config['base-url'] |
|
1524 | 178 |
|
0 | 179 |
def from_controller(self): |
180 |
return 'view' |
|
1524 | 181 |
|
0 | 182 |
def set_connection(self, cnx, user=None): |
183 |
"""method called by the session handler when the user is authenticated |
|
184 |
or an anonymous connection is open |
|
185 |
""" |
|
186 |
self.cnx = cnx |
|
187 |
self.cursor = cnx.cursor(self) |
|
188 |
self.set_user(user) |
|
1524 | 189 |
|
0 | 190 |
def set_default_language(self, vreg): |
191 |
try: |
|
192 |
self.lang = vreg.property_value('ui.language') |
|
193 |
except: # property may not be registered |
|
194 |
self.lang = 'en' |
|
195 |
# use req.__ to translate a message without registering it to the catalog |
|
196 |
try: |
|
3275
5247789df541
[gettext] provide GNU contexts to avoid translations ambiguities
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
3258
diff
changeset
|
197 |
gettext, pgettext = self.translations[self.lang] |
5247789df541
[gettext] provide GNU contexts to avoid translations ambiguities
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
3258
diff
changeset
|
198 |
self._ = self.__ = gettext |
5247789df541
[gettext] provide GNU contexts to avoid translations ambiguities
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
3258
diff
changeset
|
199 |
self.pgettext = pgettext |
0 | 200 |
except KeyError: |
201 |
# this occurs usually during test execution |
|
202 |
self._ = self.__ = unicode |
|
4721
8f63691ccb7f
pylint style fixes
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4716
diff
changeset
|
203 |
self.pgettext = lambda x, y: y |
2111
5e142c7a4531
different message
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
204 |
self.debug('request default language: %s', self.lang) |
0 | 205 |
|
206 |
def decorate_rset(self, rset): |
|
207 |
rset.vreg = self.vreg |
|
208 |
rset.req = self |
|
209 |
return rset |
|
1524 | 210 |
|
0 | 211 |
def describe(self, eid): |
212 |
"""return a tuple (type, sourceuri, extid) for the entity with id <eid>""" |
|
213 |
return self.cnx.describe(eid) |
|
1524 | 214 |
|
0 | 215 |
def source_defs(self): |
216 |
"""return the definition of sources used by the repository.""" |
|
217 |
return self.cnx.source_defs() |
|
1524 | 218 |
|
0 | 219 |
# entities cache management ############################################### |
1524 | 220 |
|
0 | 221 |
def entity_cache(self, eid): |
222 |
return self._eid_cache[eid] |
|
1524 | 223 |
|
0 | 224 |
def set_entity_cache(self, entity): |
225 |
self._eid_cache[entity.eid] = entity |
|
226 |
||
227 |
def cached_entities(self): |
|
228 |
return self._eid_cache.values() |
|
1524 | 229 |
|
0 | 230 |
def drop_entity_cache(self, eid=None): |
231 |
if eid is None: |
|
232 |
self._eid_cache = {} |
|
233 |
else: |
|
234 |
del self._eid_cache[eid] |
|
235 |
||
236 |
# low level session data management ####################################### |
|
237 |
||
238 |
def session_data(self): |
|
239 |
"""return a dictionnary containing session data""" |
|
240 |
return self.cnx.session_data() |
|
241 |
||
242 |
def get_session_data(self, key, default=None, pop=False): |
|
243 |
"""return value associated to `key` in session data""" |
|
4592
ddbab12acae0
ensure cnx is set first (necessary to introduce of a form object to handle the login form)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4252
diff
changeset
|
244 |
if self.cnx is None: |
ddbab12acae0
ensure cnx is set first (necessary to introduce of a form object to handle the login form)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4252
diff
changeset
|
245 |
return None # before the connection has been established |
0 | 246 |
return self.cnx.get_session_data(key, default, pop) |
1524 | 247 |
|
0 | 248 |
def set_session_data(self, key, value): |
249 |
"""set value associated to `key` in session data""" |
|
250 |
return self.cnx.set_session_data(key, value) |
|
1524 | 251 |
|
0 | 252 |
def del_session_data(self, key): |
253 |
"""remove value associated to `key` in session data""" |
|
254 |
return self.cnx.del_session_data(key) |
|
255 |
||
256 |
def get_shared_data(self, key, default=None, pop=False): |
|
257 |
"""return value associated to `key` in shared data""" |
|
258 |
return self.cnx.get_shared_data(key, default, pop) |
|
1524 | 259 |
|
0 | 260 |
def set_shared_data(self, key, value, querydata=False): |
261 |
"""set value associated to `key` in shared data |
|
262 |
||
263 |
if `querydata` is true, the value will be added to the repository |
|
264 |
session's query data which are cleared on commit/rollback of the current |
|
265 |
transaction, and won't be available through the connexion, only on the |
|
266 |
repository side. |
|
267 |
""" |
|
268 |
return self.cnx.set_shared_data(key, value, querydata) |
|
269 |
||
270 |
# server session compat layer ############################################# |
|
271 |
||
3110
757d36162235
enhance notification mecanism: recipients may return user entities, which will be used to create a fake session so one can check security during notification if necessary
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2665
diff
changeset
|
272 |
def hijack_user(self, user): |
757d36162235
enhance notification mecanism: recipients may return user entities, which will be used to create a fake session so one can check security during notification if necessary
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2665
diff
changeset
|
273 |
"""return a fake request/session using specified user""" |
757d36162235
enhance notification mecanism: recipients may return user entities, which will be used to create a fake session so one can check security during notification if necessary
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2665
diff
changeset
|
274 |
req = DBAPIRequest(self.vreg) |
757d36162235
enhance notification mecanism: recipients may return user entities, which will be used to create a fake session so one can check security during notification if necessary
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2665
diff
changeset
|
275 |
req.set_connection(self.cnx, user) |
757d36162235
enhance notification mecanism: recipients may return user entities, which will be used to create a fake session so one can check security during notification if necessary
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2665
diff
changeset
|
276 |
return req |
757d36162235
enhance notification mecanism: recipients may return user entities, which will be used to create a fake session so one can check security during notification if necessary
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2665
diff
changeset
|
277 |
|
0 | 278 |
@property |
279 |
def user(self): |
|
280 |
if self._user is None and self.cnx: |
|
2245
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2111
diff
changeset
|
281 |
self.set_user(self.cnx.user(self, {'lang': self.lang})) |
0 | 282 |
return self._user |
283 |
||
284 |
def set_user(self, user): |
|
285 |
self._user = user |
|
286 |
if user: |
|
287 |
self.set_entity_cache(user) |
|
1524 | 288 |
|
0 | 289 |
def execute(self, *args, **kwargs): |
290 |
"""Session interface compatibility""" |
|
291 |
return self.cursor.execute(*args, **kwargs) |
|
292 |
||
293 |
set_log_methods(DBAPIRequest, getLogger('cubicweb.dbapi')) |
|
1524 | 294 |
|
295 |
||
0 | 296 |
# exceptions ################################################################## |
297 |
||
298 |
class ProgrammingError(Exception): #DatabaseError): |
|
299 |
"""Exception raised for errors that are related to the database's operation |
|
300 |
and not necessarily under the control of the programmer, e.g. an unexpected |
|
301 |
disconnect occurs, the data source name is not found, a transaction could |
|
302 |
not be processed, a memory allocation error occurred during processing, |
|
303 |
etc. |
|
304 |
""" |
|
305 |
||
306 |
# module level objects ######################################################## |
|
307 |
||
308 |
||
309 |
apilevel = '2.0' |
|
310 |
||
311 |
"""Integer constant stating the level of thread safety the interface supports. |
|
312 |
Possible values are: |
|
313 |
||
314 |
0 Threads may not share the module. |
|
315 |
1 Threads may share the module, but not connections. |
|
316 |
2 Threads may share the module and connections. |
|
317 |
3 Threads may share the module, connections and |
|
318 |
cursors. |
|
319 |
||
320 |
Sharing in the above context means that two threads may use a resource without |
|
321 |
wrapping it using a mutex semaphore to implement resource locking. Note that |
|
322 |
you cannot always make external resources thread safe by managing access using |
|
323 |
a mutex: the resource may rely on global variables or other external sources |
|
324 |
that are beyond your control. |
|
325 |
""" |
|
326 |
threadsafety = 1 |
|
327 |
||
328 |
"""String constant stating the type of parameter marker formatting expected by |
|
329 |
the interface. Possible values are : |
|
330 |
||
1524 | 331 |
'qmark' Question mark style, |
0 | 332 |
e.g. '...WHERE name=?' |
1524 | 333 |
'numeric' Numeric, positional style, |
0 | 334 |
e.g. '...WHERE name=:1' |
1524 | 335 |
'named' Named style, |
0 | 336 |
e.g. '...WHERE name=:name' |
1524 | 337 |
'format' ANSI C printf format codes, |
0 | 338 |
e.g. '...WHERE name=%s' |
1524 | 339 |
'pyformat' Python extended format codes, |
0 | 340 |
e.g. '...WHERE name=%(name)s' |
341 |
""" |
|
342 |
paramstyle = 'pyformat' |
|
343 |
||
344 |
||
345 |
# connection object ########################################################### |
|
346 |
||
347 |
class Connection(object): |
|
3258
6536ee4f37f7
update the documentation
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
3110
diff
changeset
|
348 |
"""DB-API 2.0 compatible Connection object for CubicWeb |
0 | 349 |
""" |
350 |
# make exceptions available through the connection object |
|
351 |
ProgrammingError = ProgrammingError |
|
352 |
||
353 |
def __init__(self, repo, cnxid, cnxprops=None): |
|
354 |
self._repo = repo |
|
355 |
self.sessionid = cnxid |
|
356 |
self._close_on_del = getattr(cnxprops, 'close_on_del', True) |
|
357 |
self._cnxtype = getattr(cnxprops, 'cnxtype', 'pyro') |
|
358 |
self._closed = None |
|
359 |
if cnxprops and cnxprops.log_queries: |
|
360 |
self.executed_queries = [] |
|
361 |
self.cursor_class = LogCursor |
|
362 |
else: |
|
363 |
self.cursor_class = Cursor |
|
364 |
self.anonymous_connection = False |
|
365 |
self.vreg = None |
|
366 |
# session's data |
|
367 |
self.data = {} |
|
368 |
||
369 |
def __repr__(self): |
|
370 |
if self.anonymous_connection: |
|
371 |
return '<Connection %s (anonymous)>' % self.sessionid |
|
372 |
return '<Connection %s>' % self.sessionid |
|
373 |
||
374 |
def request(self): |
|
375 |
return DBAPIRequest(self.vreg, self) |
|
1524 | 376 |
|
0 | 377 |
def session_data(self): |
378 |
"""return a dictionnary containing session data""" |
|
379 |
return self.data |
|
1524 | 380 |
|
0 | 381 |
def get_session_data(self, key, default=None, pop=False): |
382 |
"""return value associated to `key` in session data""" |
|
383 |
if pop: |
|
384 |
return self.data.pop(key, default) |
|
385 |
else: |
|
386 |
return self.data.get(key, default) |
|
1524 | 387 |
|
0 | 388 |
def set_session_data(self, key, value): |
389 |
"""set value associated to `key` in session data""" |
|
390 |
self.data[key] = value |
|
1524 | 391 |
|
0 | 392 |
def del_session_data(self, key): |
393 |
"""remove value associated to `key` in session data""" |
|
394 |
try: |
|
395 |
del self.data[key] |
|
396 |
except KeyError: |
|
1524 | 397 |
pass |
0 | 398 |
|
399 |
def check(self): |
|
400 |
"""raise `BadSessionId` if the connection is no more valid""" |
|
1132 | 401 |
self._repo.check_session(self.sessionid) |
0 | 402 |
|
2245
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2111
diff
changeset
|
403 |
def set_session_props(self, **props): |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2111
diff
changeset
|
404 |
"""raise `BadSessionId` if the connection is no more valid""" |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2111
diff
changeset
|
405 |
self._repo.set_session_props(self.sessionid, props) |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2111
diff
changeset
|
406 |
|
0 | 407 |
def get_shared_data(self, key, default=None, pop=False): |
408 |
"""return value associated to `key` in shared data""" |
|
409 |
return self._repo.get_shared_data(self.sessionid, key, default, pop) |
|
1524 | 410 |
|
0 | 411 |
def set_shared_data(self, key, value, querydata=False): |
412 |
"""set value associated to `key` in shared data |
|
413 |
||
414 |
if `querydata` is true, the value will be added to the repository |
|
415 |
session's query data which are cleared on commit/rollback of the current |
|
416 |
transaction, and won't be available through the connexion, only on the |
|
417 |
repository side. |
|
418 |
""" |
|
419 |
return self._repo.set_shared_data(self.sessionid, key, value, querydata) |
|
1524 | 420 |
|
0 | 421 |
def get_schema(self): |
422 |
"""Return the schema currently used by the repository. |
|
1524 | 423 |
|
0 | 424 |
This is NOT part of the DB-API. |
425 |
""" |
|
426 |
if self._closed is not None: |
|
427 |
raise ProgrammingError('Closed connection') |
|
428 |
return self._repo.get_schema() |
|
429 |
||
2657
de974465d381
[appobject] kill VObject class, move base selector classes to appobject
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2650
diff
changeset
|
430 |
def load_appobjects(self, cubes=_MARKER, subpath=None, expand=True, |
3707
78596919ede3
[c-c] fixes for shell w/ pyro instance
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3275
diff
changeset
|
431 |
force_reload=None): |
0 | 432 |
config = self.vreg.config |
433 |
if cubes is _MARKER: |
|
434 |
cubes = self._repo.get_cubes() |
|
435 |
elif cubes is None: |
|
436 |
cubes = () |
|
437 |
else: |
|
438 |
if not isinstance(cubes, (list, tuple)): |
|
439 |
cubes = (cubes,) |
|
440 |
if expand: |
|
441 |
cubes = config.expand_cubes(cubes) |
|
442 |
if subpath is None: |
|
443 |
subpath = esubpath = ('entities', 'views') |
|
444 |
else: |
|
445 |
esubpath = subpath |
|
446 |
if 'views' in subpath: |
|
447 |
esubpath = list(subpath) |
|
448 |
esubpath.remove('views') |
|
449 |
esubpath.append('web/views') |
|
450 |
cubes = reversed([config.cube_dir(p) for p in cubes]) |
|
451 |
vpath = config.build_vregistry_path(cubes, evobjpath=esubpath, |
|
452 |
tvobjpath=subpath) |
|
453 |
self.vreg.register_objects(vpath, force_reload) |
|
454 |
if self._cnxtype == 'inmemory': |
|
455 |
# should reinit hooks manager as well |
|
456 |
hm, config = self._repo.hm, self._repo.config |
|
457 |
hm.set_schema(hm.schema) # reset structure |
|
458 |
hm.register_system_hooks(config) |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2266
diff
changeset
|
459 |
# instance specific hooks |
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2266
diff
changeset
|
460 |
if self._repo.config.instance_hooks: |
0 | 461 |
hm.register_hooks(config.load_hooks(self.vreg)) |
1524 | 462 |
|
2657
de974465d381
[appobject] kill VObject class, move base selector classes to appobject
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2650
diff
changeset
|
463 |
load_vobjects = deprecated()(load_appobjects) |
de974465d381
[appobject] kill VObject class, move base selector classes to appobject
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2650
diff
changeset
|
464 |
|
2496
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
465 |
def use_web_compatible_requests(self, baseurl, sitetitle=None): |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
466 |
"""monkey patch DBAPIRequest to fake a cw.web.request, so you should |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
467 |
able to call html views using rset from a simple dbapi connection. |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
468 |
|
2657
de974465d381
[appobject] kill VObject class, move base selector classes to appobject
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2650
diff
changeset
|
469 |
You should call `load_appobjects` at some point to register those views. |
2496
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
470 |
""" |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
471 |
from cubicweb.web.request import CubicWebRequestBase as cwrb |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
472 |
DBAPIRequest.build_ajax_replace_url = cwrb.build_ajax_replace_url.im_func |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
473 |
DBAPIRequest.list_form_param = cwrb.list_form_param.im_func |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
474 |
DBAPIRequest.property_value = _fake_property_value |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
475 |
DBAPIRequest.next_tabindex = count().next |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
476 |
DBAPIRequest.form = {} |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
477 |
DBAPIRequest.data = {} |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
478 |
fake = lambda *args, **kwargs: None |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
479 |
DBAPIRequest.relative_path = fake |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
480 |
DBAPIRequest.url = fake |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
481 |
DBAPIRequest.next_tabindex = fake |
3832
ce8dd861f442
#473188: missing get_page_data when patching bare db-api request for web compatibility
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3707
diff
changeset
|
482 |
DBAPIRequest.get_page_data = fake |
3833
5507aa75f601
add set_page_data as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3832
diff
changeset
|
483 |
DBAPIRequest.set_page_data = fake |
2496
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
484 |
DBAPIRequest.add_js = fake #cwrb.add_js.im_func |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
485 |
DBAPIRequest.add_css = fake #cwrb.add_css.im_func |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
486 |
# XXX could ask the repo for it's base-url configuration |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
487 |
self.vreg.config.set_option('base-url', baseurl) |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
488 |
# XXX why is this needed? if really needed, could be fetched by a query |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
489 |
if sitetitle is not None: |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
490 |
self.vreg['propertydefs']['ui.site-title'] = {'default': sitetitle} |
fbd1fd2ca312
#343624: access to ORM and views outside web engine
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
491 |
|
0 | 492 |
def source_defs(self): |
493 |
"""Return the definition of sources used by the repository. |
|
1524 | 494 |
|
0 | 495 |
This is NOT part of the DB-API. |
496 |
""" |
|
497 |
if self._closed is not None: |
|
498 |
raise ProgrammingError('Closed connection') |
|
499 |
return self._repo.source_defs() |
|
500 |
||
322
0d9aca19b3d0
make req argument optional
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
169
diff
changeset
|
501 |
def user(self, req=None, props=None): |
0 | 502 |
"""return the User object associated to this connection""" |
503 |
# cnx validity is checked by the call to .user_info |
|
2245
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2111
diff
changeset
|
504 |
eid, login, groups, properties = self._repo.user_info(self.sessionid, |
7463e1a748dd
new set_session_props method exposed by the repository, use it to be sure session language is in sync the request language
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2111
diff
changeset
|
505 |
props) |
0 | 506 |
if req is None: |
507 |
req = self.request() |
|
1923
3802c2e37e72
handle speaking to an instance using old entity types
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1882
diff
changeset
|
508 |
rset = req.eid_rset(eid, 'CWUser') |
2650
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
509 |
user = self.vreg['etypes'].etype_class('CWUser')(req, rset, row=0, |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
510 |
groups=groups, |
18aec79ec3a3
R [vreg] important refactoring of the vregistry, moving behaviour to end dictionnary (and so leaving room for more flexibility ; keep bw compat ; update api usage in cw
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2496
diff
changeset
|
511 |
properties=properties) |
0 | 512 |
user['login'] = login # cache login |
513 |
return user |
|
514 |
||
515 |
def __del__(self): |
|
516 |
"""close the remote connection if necessary""" |
|
517 |
if self._closed is None and self._close_on_del: |
|
518 |
try: |
|
519 |
self.close() |
|
520 |
except: |
|
521 |
pass |
|
1524 | 522 |
|
0 | 523 |
def describe(self, eid): |
524 |
return self._repo.describe(self.sessionid, eid) |
|
1524 | 525 |
|
0 | 526 |
def close(self): |
527 |
"""Close the connection now (rather than whenever __del__ is called). |
|
1524 | 528 |
|
0 | 529 |
The connection will be unusable from this point forward; an Error (or |
530 |
subclass) exception will be raised if any operation is attempted with |
|
531 |
the connection. The same applies to all cursor objects trying to use the |
|
532 |
connection. Note that closing a connection without committing the |
|
533 |
changes first will cause an implicit rollback to be performed. |
|
534 |
""" |
|
535 |
if self._closed: |
|
536 |
raise ProgrammingError('Connection is already closed') |
|
537 |
self._repo.close(self.sessionid) |
|
538 |
self._closed = 1 |
|
539 |
||
540 |
def commit(self): |
|
541 |
"""Commit any pending transaction to the database. Note that if the |
|
542 |
database supports an auto-commit feature, this must be initially off. An |
|
543 |
interface method may be provided to turn it back on. |
|
1524 | 544 |
|
0 | 545 |
Database modules that do not support transactions should implement this |
546 |
method with void functionality. |
|
547 |
""" |
|
548 |
if not self._closed is None: |
|
549 |
raise ProgrammingError('Connection is already closed') |
|
550 |
self._repo.commit(self.sessionid) |
|
551 |
||
552 |
def rollback(self): |
|
553 |
"""This method is optional since not all databases provide transaction |
|
554 |
support. |
|
1524 | 555 |
|
0 | 556 |
In case a database does provide transactions this method causes the the |
557 |
database to roll back to the start of any pending transaction. Closing |
|
558 |
a connection without committing the changes first will cause an implicit |
|
559 |
rollback to be performed. |
|
560 |
""" |
|
561 |
if not self._closed is None: |
|
562 |
raise ProgrammingError('Connection is already closed') |
|
563 |
self._repo.rollback(self.sessionid) |
|
564 |
||
565 |
def cursor(self, req=None): |
|
566 |
"""Return a new Cursor Object using the connection. If the database |
|
567 |
does not provide a direct cursor concept, the module will have to |
|
568 |
emulate cursors using other means to the extent needed by this |
|
569 |
specification. |
|
570 |
""" |
|
571 |
if self._closed is not None: |
|
572 |
raise ProgrammingError('Can\'t get cursor on closed connection') |
|
573 |
if req is None: |
|
574 |
req = self.request() |
|
575 |
return self.cursor_class(self, self._repo, req=req) |
|
576 |
||
577 |
||
578 |
# cursor object ############################################################### |
|
579 |
||
580 |
class Cursor(object): |
|
581 |
"""These objects represent a database cursor, which is used to manage the |
|
582 |
context of a fetch operation. Cursors created from the same connection are |
|
583 |
not isolated, i.e., any changes done to the database by a cursor are |
|
584 |
immediately visible by the other cursors. Cursors created from different |
|
585 |
connections can or can not be isolated, depending on how the transaction |
|
586 |
support is implemented (see also the connection's rollback() and commit() |
|
587 |
methods.) |
|
588 |
""" |
|
1524 | 589 |
|
0 | 590 |
def __init__(self, connection, repo, req=None): |
591 |
"""This read-only attribute return a reference to the Connection |
|
592 |
object on which the cursor was created. |
|
593 |
""" |
|
594 |
self.connection = connection |
|
595 |
"""optionnal issuing request instance""" |
|
596 |
self.req = req |
|
597 |
||
598 |
"""This read/write attribute specifies the number of rows to fetch at a |
|
599 |
time with fetchmany(). It defaults to 1 meaning to fetch a single row |
|
600 |
at a time. |
|
1524 | 601 |
|
0 | 602 |
Implementations must observe this value with respect to the fetchmany() |
603 |
method, but are free to interact with the database a single row at a |
|
604 |
time. It may also be used in the implementation of executemany(). |
|
605 |
""" |
|
606 |
self.arraysize = 1 |
|
607 |
||
608 |
self._repo = repo |
|
609 |
self._sessid = connection.sessionid |
|
610 |
self._res = None |
|
611 |
self._closed = None |
|
612 |
self._index = 0 |
|
613 |
||
1524 | 614 |
|
0 | 615 |
def close(self): |
616 |
"""Close the cursor now (rather than whenever __del__ is called). The |
|
617 |
cursor will be unusable from this point forward; an Error (or subclass) |
|
618 |
exception will be raised if any operation is attempted with the cursor. |
|
619 |
""" |
|
620 |
self._closed = True |
|
621 |
||
1524 | 622 |
|
0 | 623 |
def execute(self, operation, parameters=None, eid_key=None, build_descr=True): |
624 |
"""Prepare and execute a database operation (query or command). |
|
625 |
Parameters may be provided as sequence or mapping and will be bound to |
|
626 |
variables in the operation. Variables are specified in a |
|
627 |
database-specific notation (see the module's paramstyle attribute for |
|
628 |
details). |
|
1524 | 629 |
|
0 | 630 |
A reference to the operation will be retained by the cursor. If the |
631 |
same operation object is passed in again, then the cursor can optimize |
|
632 |
its behavior. This is most effective for algorithms where the same |
|
633 |
operation is used, but different parameters are bound to it (many |
|
634 |
times). |
|
1524 | 635 |
|
0 | 636 |
For maximum efficiency when reusing an operation, it is best to use the |
637 |
setinputsizes() method to specify the parameter types and sizes ahead |
|
638 |
of time. It is legal for a parameter to not match the predefined |
|
639 |
information; the implementation should compensate, possibly with a loss |
|
640 |
of efficiency. |
|
1524 | 641 |
|
0 | 642 |
The parameters may also be specified as list of tuples to e.g. insert |
643 |
multiple rows in a single operation, but this kind of usage is |
|
644 |
depreciated: executemany() should be used instead. |
|
1524 | 645 |
|
0 | 646 |
Return values are not defined by the DB-API, but this here it returns a |
647 |
ResultSet object. |
|
648 |
""" |
|
649 |
self._res = res = self._repo.execute(self._sessid, operation, |
|
650 |
parameters, eid_key, build_descr) |
|
651 |
self.req.decorate_rset(res) |
|
652 |
self._index = 0 |
|
653 |
return res |
|
1524 | 654 |
|
0 | 655 |
|
656 |
def executemany(self, operation, seq_of_parameters): |
|
657 |
"""Prepare a database operation (query or command) and then execute it |
|
658 |
against all parameter sequences or mappings found in the sequence |
|
659 |
seq_of_parameters. |
|
1524 | 660 |
|
0 | 661 |
Modules are free to implement this method using multiple calls to the |
662 |
execute() method or by using array operations to have the database |
|
663 |
process the sequence as a whole in one call. |
|
1524 | 664 |
|
0 | 665 |
Use of this method for an operation which produces one or more result |
666 |
sets constitutes undefined behavior, and the implementation is |
|
667 |
permitted (but not required) to raise an exception when it detects that |
|
668 |
a result set has been created by an invocation of the operation. |
|
1524 | 669 |
|
0 | 670 |
The same comments as for execute() also apply accordingly to this |
671 |
method. |
|
1524 | 672 |
|
0 | 673 |
Return values are not defined. |
674 |
""" |
|
675 |
for parameters in seq_of_parameters: |
|
676 |
self.execute(operation, parameters) |
|
677 |
if self._res.rows is not None: |
|
678 |
self._res = None |
|
679 |
raise ProgrammingError('Operation returned a result set') |
|
680 |
||
681 |
||
682 |
def fetchone(self): |
|
683 |
"""Fetch the next row of a query result set, returning a single |
|
684 |
sequence, or None when no more data is available. |
|
1524 | 685 |
|
0 | 686 |
An Error (or subclass) exception is raised if the previous call to |
687 |
execute*() did not produce any result set or no call was issued yet. |
|
688 |
""" |
|
689 |
if self._res is None: |
|
690 |
raise ProgrammingError('No result set') |
|
691 |
row = self._res.rows[self._index] |
|
692 |
self._index += 1 |
|
693 |
return row |
|
694 |
||
1524 | 695 |
|
0 | 696 |
def fetchmany(self, size=None): |
697 |
"""Fetch the next set of rows of a query result, returning a sequence |
|
698 |
of sequences (e.g. a list of tuples). An empty sequence is returned |
|
699 |
when no more rows are available. |
|
1524 | 700 |
|
0 | 701 |
The number of rows to fetch per call is specified by the parameter. If |
702 |
it is not given, the cursor's arraysize determines the number of rows |
|
703 |
to be fetched. The method should try to fetch as many rows as indicated |
|
704 |
by the size parameter. If this is not possible due to the specified |
|
705 |
number of rows not being available, fewer rows may be returned. |
|
1524 | 706 |
|
0 | 707 |
An Error (or subclass) exception is raised if the previous call to |
708 |
execute*() did not produce any result set or no call was issued yet. |
|
1524 | 709 |
|
0 | 710 |
Note there are performance considerations involved with the size |
711 |
parameter. For optimal performance, it is usually best to use the |
|
712 |
arraysize attribute. If the size parameter is used, then it is best |
|
713 |
for it to retain the same value from one fetchmany() call to the next. |
|
714 |
""" |
|
715 |
if self._res is None: |
|
716 |
raise ProgrammingError('No result set') |
|
717 |
if size is None: |
|
718 |
size = self.arraysize |
|
719 |
rows = self._res.rows[self._index:self._index + size] |
|
720 |
self._index += size |
|
721 |
return rows |
|
722 |
||
1524 | 723 |
|
0 | 724 |
def fetchall(self): |
725 |
"""Fetch all (remaining) rows of a query result, returning them as a |
|
726 |
sequence of sequences (e.g. a list of tuples). Note that the cursor's |
|
727 |
arraysize attribute can affect the performance of this operation. |
|
1524 | 728 |
|
0 | 729 |
An Error (or subclass) exception is raised if the previous call to |
730 |
execute*() did not produce any result set or no call was issued yet. |
|
731 |
""" |
|
732 |
if self._res is None: |
|
733 |
raise ProgrammingError('No result set') |
|
734 |
if not self._res.rows: |
|
735 |
return [] |
|
736 |
rows = self._res.rows[self._index:] |
|
737 |
self._index = len(self._res) |
|
738 |
return rows |
|
739 |
||
740 |
||
741 |
def setinputsizes(self, sizes): |
|
742 |
"""This can be used before a call to execute*() to predefine memory |
|
743 |
areas for the operation's parameters. |
|
1524 | 744 |
|
0 | 745 |
sizes is specified as a sequence -- one item for each input parameter. |
746 |
The item should be a Type Object that corresponds to the input that |
|
747 |
will be used, or it should be an integer specifying the maximum length |
|
748 |
of a string parameter. If the item is None, then no predefined memory |
|
749 |
area will be reserved for that column (this is useful to avoid |
|
750 |
predefined areas for large inputs). |
|
1524 | 751 |
|
0 | 752 |
This method would be used before the execute*() method is invoked. |
1524 | 753 |
|
0 | 754 |
Implementations are free to have this method do nothing and users are |
755 |
free to not use it. |
|
756 |
""" |
|
757 |
pass |
|
758 |
||
1524 | 759 |
|
0 | 760 |
def setoutputsize(self, size, column=None): |
761 |
"""Set a column buffer size for fetches of large columns (e.g. LONGs, |
|
762 |
BLOBs, etc.). The column is specified as an index into the result |
|
763 |
sequence. Not specifying the column will set the default size for all |
|
764 |
large columns in the cursor. |
|
1524 | 765 |
|
0 | 766 |
This method would be used before the execute*() method is invoked. |
1524 | 767 |
|
0 | 768 |
Implementations are free to have this method do nothing and users are |
769 |
free to not use it. |
|
1524 | 770 |
""" |
0 | 771 |
pass |
772 |
||
1524 | 773 |
|
0 | 774 |
class LogCursor(Cursor): |
775 |
"""override the standard cursor to log executed queries""" |
|
1524 | 776 |
|
0 | 777 |
def execute(self, operation, parameters=None, eid_key=None, build_descr=True): |
778 |
"""override the standard cursor to log executed queries""" |
|
779 |
tstart, cstart = time(), clock() |
|
780 |
rset = Cursor.execute(self, operation, parameters, eid_key, build_descr) |
|
781 |
self.connection.executed_queries.append((operation, parameters, |
|
782 |
time() - tstart, clock() - cstart)) |
|
783 |
return rset |
|
784 |