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