author | sylvain.thenault@logilab.fr |
Thu, 30 Apr 2009 00:35:37 +0200 | |
branch | tls-sprint |
changeset 1546 | 68c69980f6a1 |
parent 1408 | 6bf19f175ea5 |
child 1619 | e4845b54a704 |
permissions | -rw-r--r-- |
0 | 1 |
"""SQL utilities functions and classes. |
2 |
||
3 |
:organization: Logilab |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
4 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
6 |
""" |
|
7 |
__docformat__ = "restructuredtext en" |
|
8 |
||
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
9 |
from warnings import warn |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
10 |
from datetime import datetime, timedelta |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
11 |
|
0 | 12 |
from logilab.common.shellutils import ProgressBar |
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
13 |
from logilab.common import db |
0 | 14 |
from logilab.common.adbh import get_adv_func_helper |
15 |
from logilab.common.sqlgen import SQLGenerator |
|
16 |
||
17 |
from indexer import get_indexer |
|
18 |
||
19 |
from cubicweb import Binary, ConfigurationError |
|
20 |
from cubicweb.common.uilib import remove_html_tags |
|
21 |
from cubicweb.server import SQL_CONNECT_HOOKS |
|
1132 | 22 |
from cubicweb.server.utils import crypt_password |
0 | 23 |
|
24 |
||
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
25 |
db.USE_MX_DATETIME = False |
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
26 |
SQL_PREFIX = 'cw_' |
0 | 27 |
|
28 |
||
29 |
def sqlexec(sqlstmts, cursor_or_execute, withpb=True, delimiter=';'): |
|
30 |
"""execute sql statements ignoring DROP/ CREATE GROUP or USER statements |
|
31 |
error. If a cnx is given, commit at each statement |
|
32 |
""" |
|
33 |
if hasattr(cursor_or_execute, 'execute'): |
|
34 |
execute = cursor_or_execute.execute |
|
35 |
else: |
|
36 |
execute = cursor_or_execute |
|
37 |
sqlstmts = sqlstmts.split(delimiter) |
|
38 |
if withpb: |
|
39 |
pb = ProgressBar(len(sqlstmts)) |
|
40 |
for sql in sqlstmts: |
|
41 |
sql = sql.strip() |
|
42 |
if withpb: |
|
43 |
pb.update() |
|
44 |
if not sql: |
|
45 |
continue |
|
46 |
# some dbapi modules doesn't accept unicode for sql string |
|
47 |
execute(str(sql)) |
|
48 |
if withpb: |
|
49 |
print |
|
50 |
||
51 |
||
52 |
def sqlgrants(schema, driver, user, |
|
53 |
text_index=True, set_owner=True, |
|
54 |
skip_relations=(), skip_entities=()): |
|
55 |
"""return sql to give all access privileges to the given user on the system |
|
56 |
schema |
|
57 |
""" |
|
58 |
from yams.schema2sql import grant_schema |
|
59 |
from cubicweb.server.sources import native |
|
60 |
output = [] |
|
61 |
w = output.append |
|
62 |
w(native.grant_schema(user, set_owner)) |
|
63 |
w('') |
|
64 |
if text_index: |
|
65 |
indexer = get_indexer(driver) |
|
66 |
w(indexer.sql_grant_user(user)) |
|
67 |
w('') |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
68 |
w(grant_schema(schema, user, set_owner, skip_entities=skip_entities, prefix=SQL_PREFIX)) |
0 | 69 |
return '\n'.join(output) |
70 |
||
71 |
||
72 |
def sqlschema(schema, driver, text_index=True, |
|
73 |
user=None, set_owner=False, |
|
74 |
skip_relations=('has_text', 'identity'), skip_entities=()): |
|
75 |
"""return the system sql schema, according to the given parameters""" |
|
76 |
from yams.schema2sql import schema2sql |
|
77 |
from cubicweb.server.sources import native |
|
78 |
if set_owner: |
|
79 |
assert user, 'user is argument required when set_owner is true' |
|
80 |
output = [] |
|
81 |
w = output.append |
|
82 |
w(native.sql_schema(driver)) |
|
83 |
w('') |
|
84 |
if text_index: |
|
85 |
indexer = get_indexer(driver) |
|
86 |
w(indexer.sql_init_fti()) |
|
87 |
w('') |
|
88 |
dbhelper = get_adv_func_helper(driver) |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
89 |
w(schema2sql(dbhelper, schema, prefix=SQL_PREFIX, |
0 | 90 |
skip_entities=skip_entities, skip_relations=skip_relations)) |
91 |
if dbhelper.users_support and user: |
|
92 |
w('') |
|
93 |
w(sqlgrants(schema, driver, user, text_index, set_owner, |
|
94 |
skip_relations, skip_entities)) |
|
95 |
return '\n'.join(output) |
|
96 |
||
97 |
||
98 |
def sqldropschema(schema, driver, text_index=True, |
|
99 |
skip_relations=('has_text', 'identity'), skip_entities=()): |
|
100 |
"""return the sql to drop the schema, according to the given parameters""" |
|
101 |
from yams.schema2sql import dropschema2sql |
|
102 |
from cubicweb.server.sources import native |
|
103 |
output = [] |
|
104 |
w = output.append |
|
105 |
w(native.sql_drop_schema(driver)) |
|
106 |
w('') |
|
107 |
if text_index: |
|
108 |
indexer = get_indexer(driver) |
|
109 |
w(indexer.sql_drop_fti()) |
|
110 |
w('') |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
111 |
w(dropschema2sql(schema, prefix=SQL_PREFIX, |
0 | 112 |
skip_entities=skip_entities, skip_relations=skip_relations)) |
113 |
return '\n'.join(output) |
|
114 |
||
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
115 |
try: |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
116 |
from mx.DateTime import DateTimeType, DateTimeDeltaType |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
117 |
except ImportError: |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
118 |
DateTimeType, DateTimeDeltaType = None |
0 | 119 |
|
120 |
class SQLAdapterMixIn(object): |
|
121 |
"""Mixin for SQL data sources, getting a connection from a configuration |
|
122 |
dictionary and handling connection locking |
|
123 |
""" |
|
124 |
||
125 |
def __init__(self, source_config): |
|
126 |
try: |
|
127 |
self.dbdriver = source_config['db-driver'].lower() |
|
128 |
self.dbname = source_config['db-name'] |
|
129 |
except KeyError: |
|
130 |
raise ConfigurationError('missing some expected entries in sources file') |
|
131 |
self.dbhost = source_config.get('db-host') |
|
132 |
port = source_config.get('db-port') |
|
133 |
self.dbport = port and int(port) or None |
|
134 |
self.dbuser = source_config.get('db-user') |
|
135 |
self.dbpasswd = source_config.get('db-password') |
|
136 |
self.encoding = source_config.get('db-encoding', 'UTF-8') |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
137 |
self.dbapi_module = db.get_dbapi_compliant_module(self.dbdriver) |
0 | 138 |
self.binary = self.dbapi_module.Binary |
139 |
self.dbhelper = self.dbapi_module.adv_func_helper |
|
140 |
self.sqlgen = SQLGenerator() |
|
141 |
||
142 |
def get_connection(self, user=None, password=None): |
|
143 |
"""open and return a connection to the database""" |
|
144 |
if user or self.dbuser: |
|
145 |
self.info('connecting to %s@%s for user %s', self.dbname, |
|
146 |
self.dbhost or 'localhost', user or self.dbuser) |
|
147 |
else: |
|
148 |
self.info('connecting to %s@%s', self.dbname, |
|
149 |
self.dbhost or 'localhost') |
|
150 |
cnx = self.dbapi_module.connect(self.dbhost, self.dbname, |
|
151 |
user or self.dbuser, |
|
152 |
password or self.dbpasswd, |
|
153 |
port=self.dbport) |
|
154 |
init_cnx(self.dbdriver, cnx) |
|
155 |
#self.dbapi_module.type_code_test(cnx.cursor()) |
|
156 |
return cnx |
|
157 |
||
158 |
def merge_args(self, args, query_args): |
|
159 |
if args is not None: |
|
160 |
args = dict(args) |
|
161 |
for key, val in args.items(): |
|
162 |
# convert cubicweb binary into db binary |
|
163 |
if isinstance(val, Binary): |
|
164 |
val = self.binary(val.getvalue()) |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
165 |
# XXX <3.2 bw compat |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
166 |
elif type(val) is DateTimeType: |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
167 |
warn('found mx date time instance, please update to use datetime', |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
168 |
DeprecationWarning) |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
169 |
val = datetime(val.year, val.month, val.day, |
1026 | 170 |
val.hour, val.minute, int(val.second)) |
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
171 |
elif type(val) is DateTimeDeltaType: |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
172 |
warn('found mx date time instance, please update to use datetime', |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
173 |
DeprecationWarning) |
1026 | 174 |
val = timedelta(0, int(val.seconds), 0) |
0 | 175 |
args[key] = val |
176 |
# should not collide |
|
177 |
args.update(query_args) |
|
178 |
return args |
|
179 |
return query_args |
|
180 |
||
181 |
def process_result(self, cursor): |
|
182 |
"""return a list of CubicWeb compliant values from data in the given cursor |
|
183 |
""" |
|
184 |
descr = cursor.description |
|
185 |
encoding = self.encoding |
|
186 |
process_value = self.dbapi_module.process_value |
|
187 |
binary = Binary |
|
188 |
results = cursor.fetchall() |
|
189 |
for i, line in enumerate(results): |
|
190 |
result = [] |
|
191 |
for col, value in enumerate(line): |
|
192 |
if value is None: |
|
193 |
result.append(value) |
|
194 |
continue |
|
195 |
result.append(process_value(value, descr[col], encoding, binary)) |
|
196 |
results[i] = result |
|
197 |
return results |
|
198 |
||
199 |
||
200 |
def preprocess_entity(self, entity): |
|
201 |
"""return a dictionary to use as extra argument to cursor.execute |
|
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
202 |
to insert/update an entity into a SQL database |
0 | 203 |
""" |
204 |
attrs = {} |
|
205 |
eschema = entity.e_schema |
|
206 |
for attr, value in entity.items(): |
|
207 |
rschema = eschema.subject_relation(attr) |
|
208 |
if rschema.is_final(): |
|
209 |
atype = str(entity.e_schema.destination(attr)) |
|
210 |
if atype == 'Boolean': |
|
211 |
value = self.dbhelper.boolean_value(value) |
|
212 |
elif atype == 'Password': |
|
213 |
# if value is a Binary instance, this mean we got it |
|
214 |
# from a query result and so it is already encrypted |
|
215 |
if isinstance(value, Binary): |
|
216 |
value = value.getvalue() |
|
217 |
else: |
|
218 |
value = crypt_password(value) |
|
219 |
elif isinstance(value, Binary): |
|
220 |
value = self.binary(value.getvalue()) |
|
1408
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
221 |
# XXX <3.2 bw compat |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
222 |
elif type(value) is DateTimeType: |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
223 |
warn('found mx date time instance, please update to use datetime', |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
224 |
DeprecationWarning) |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
225 |
value = datetime(value.year, value.month, value.day, |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
226 |
value.hour, value.minute, int(value.second)) |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
227 |
elif type(value) is DateTimeDeltaType: |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
228 |
warn('found mx date time instance, please update to use datetime', |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
229 |
DeprecationWarning) |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
230 |
value = timedelta(0, int(value.seconds), 0) |
1251
af40e615dc89
introduce a 'cw_' prefix on entity table and column names so we don't conflict with sql or DBMS specific keywords
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
231 |
attrs[SQL_PREFIX+str(attr)] = value |
0 | 232 |
return attrs |
233 |
||
234 |
||
235 |
from logging import getLogger |
|
236 |
from cubicweb import set_log_methods |
|
237 |
set_log_methods(SQLAdapterMixIn, getLogger('cubicweb.sqladapter')) |
|
238 |
||
239 |
def init_sqlite_connexion(cnx): |
|
240 |
# XXX should not be publicly exposed |
|
241 |
#def comma_join(strings): |
|
242 |
# return ', '.join(strings) |
|
243 |
#cnx.create_function("COMMA_JOIN", 1, comma_join) |
|
244 |
||
245 |
class concat_strings(object): |
|
246 |
def __init__(self): |
|
247 |
self.values = [] |
|
248 |
def step(self, value): |
|
249 |
if value is not None: |
|
250 |
self.values.append(value) |
|
251 |
def finalize(self): |
|
252 |
return ', '.join(self.values) |
|
253 |
# renamed to GROUP_CONCAT in cubicweb 2.45, keep old name for bw compat for |
|
254 |
# some time |
|
255 |
cnx.create_aggregate("CONCAT_STRINGS", 1, concat_strings) |
|
256 |
cnx.create_aggregate("GROUP_CONCAT", 1, concat_strings) |
|
257 |
||
258 |
def _limit_size(text, maxsize, format='text/plain'): |
|
259 |
if len(text) < maxsize: |
|
260 |
return text |
|
261 |
if format in ('text/html', 'text/xhtml', 'text/xml'): |
|
262 |
text = remove_html_tags(text) |
|
263 |
if len(text) > maxsize: |
|
264 |
text = text[:maxsize] + '...' |
|
265 |
return text |
|
266 |
||
267 |
def limit_size3(text, format, maxsize): |
|
268 |
return _limit_size(text, maxsize, format) |
|
269 |
cnx.create_function("LIMIT_SIZE", 3, limit_size3) |
|
270 |
||
271 |
def limit_size2(text, maxsize): |
|
272 |
return _limit_size(text, maxsize) |
|
273 |
cnx.create_function("TEXT_LIMIT_SIZE", 2, limit_size2) |
|
274 |
import yams.constraints |
|
275 |
if hasattr(yams.constraints, 'patch_sqlite_decimal'): |
|
276 |
yams.constraints.patch_sqlite_decimal() |
|
277 |
||
278 |
||
279 |
sqlite_hooks = SQL_CONNECT_HOOKS.setdefault('sqlite', []) |
|
280 |
sqlite_hooks.append(init_sqlite_connexion) |
|
281 |
||
282 |
def init_cnx(driver, cnx): |
|
283 |
for hook in SQL_CONNECT_HOOKS.get(driver, ()): |
|
284 |
hook(cnx) |