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