author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Fri, 22 Jan 2010 08:49:16 +0100 | |
changeset 4322 | f65743cc53e4 |
parent 4314 | e12ee4a009bc |
child 4342 | b4e186da08f2 |
permissions | -rw-r--r-- |
0 | 1 |
"""SQL utilities functions and classes. |
2 |
||
3 |
:organization: Logilab |
|
4212
ab6573088b4a
update copyright: welcome 2010
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
4195
diff
changeset
|
4 |
:copyright: 2001-2010 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 5 |
: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:
1954
diff
changeset
|
6 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 7 |
""" |
8 |
__docformat__ = "restructuredtext en" |
|
9 |
||
2493
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
10 |
import os |
4298
2ca56131079e
enable cubicweb-ctl db-dump and db-restore on Windows with SQL Server
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
4212
diff
changeset
|
11 |
import subprocess |
2493
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
12 |
from os.path import exists |
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
13 |
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
|
14 |
from datetime import datetime, date, timedelta |
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
15 |
|
1783 | 16 |
import logilab.common as lgc |
0 | 17 |
from logilab.common.shellutils import ProgressBar |
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
18 |
from logilab.common import db |
0 | 19 |
from logilab.common.adbh import get_adv_func_helper |
20 |
from logilab.common.sqlgen import SQLGenerator |
|
21 |
||
22 |
from indexer import get_indexer |
|
23 |
||
24 |
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
|
25 |
from cubicweb.utils import todate, todatetime |
4023
eae23c40627a
drop common subpackage
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3689
diff
changeset
|
26 |
from cubicweb.uilib import remove_html_tags |
2493
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
27 |
from cubicweb.toolsutils import restrict_perms_to_user |
2596
d02eed70937f
[R repo, schema] use VIRTUAL_RTYPES const
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2512
diff
changeset
|
28 |
from cubicweb.schema import PURE_VIRTUAL_RTYPES |
0 | 29 |
from cubicweb.server import SQL_CONNECT_HOOKS |
1132 | 30 |
from cubicweb.server.utils import crypt_password |
0 | 31 |
|
32 |
||
1783 | 33 |
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
|
34 |
SQL_PREFIX = 'cw_' |
0 | 35 |
|
36 |
||
3623
9b838e2d72bb
avoid progress bar when test launched from apycot
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2759
diff
changeset
|
37 |
def sqlexec(sqlstmts, cursor_or_execute, withpb=not os.environ.get('APYCOT_ROOT'), |
9b838e2d72bb
avoid progress bar when test launched from apycot
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2759
diff
changeset
|
38 |
pbtitle='', delimiter=';'): |
0 | 39 |
"""execute sql statements ignoring DROP/ CREATE GROUP or USER statements |
40 |
error. If a cnx is given, commit at each statement |
|
41 |
""" |
|
42 |
if hasattr(cursor_or_execute, 'execute'): |
|
43 |
execute = cursor_or_execute.execute |
|
44 |
else: |
|
45 |
execute = cursor_or_execute |
|
46 |
sqlstmts = sqlstmts.split(delimiter) |
|
47 |
if withpb: |
|
2396
8bfb99d7bbcc
[cw-ctl] improve dialog messages
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1977
diff
changeset
|
48 |
pb = ProgressBar(len(sqlstmts), title=pbtitle) |
0 | 49 |
for sql in sqlstmts: |
50 |
sql = sql.strip() |
|
51 |
if withpb: |
|
52 |
pb.update() |
|
53 |
if not sql: |
|
54 |
continue |
|
55 |
# some dbapi modules doesn't accept unicode for sql string |
|
56 |
execute(str(sql)) |
|
57 |
if withpb: |
|
58 |
print |
|
59 |
||
60 |
||
61 |
def sqlgrants(schema, driver, user, |
|
62 |
text_index=True, set_owner=True, |
|
63 |
skip_relations=(), skip_entities=()): |
|
64 |
"""return sql to give all access privileges to the given user on the system |
|
65 |
schema |
|
66 |
""" |
|
67 |
from yams.schema2sql import grant_schema |
|
68 |
from cubicweb.server.sources import native |
|
69 |
output = [] |
|
70 |
w = output.append |
|
71 |
w(native.grant_schema(user, set_owner)) |
|
72 |
w('') |
|
73 |
if text_index: |
|
74 |
indexer = get_indexer(driver) |
|
75 |
w(indexer.sql_grant_user(user)) |
|
76 |
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
|
77 |
w(grant_schema(schema, user, set_owner, skip_entities=skip_entities, prefix=SQL_PREFIX)) |
0 | 78 |
return '\n'.join(output) |
79 |
||
1619
e4845b54a704
force proper date/datetime according to type (necessary for sqlite at least)
sylvain.thenault@logilab.fr
parents:
1408
diff
changeset
|
80 |
|
e4845b54a704
force proper date/datetime according to type (necessary for sqlite at least)
sylvain.thenault@logilab.fr
parents:
1408
diff
changeset
|
81 |
def sqlschema(schema, driver, text_index=True, |
0 | 82 |
user=None, set_owner=False, |
2596
d02eed70937f
[R repo, schema] use VIRTUAL_RTYPES const
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2512
diff
changeset
|
83 |
skip_relations=PURE_VIRTUAL_RTYPES, skip_entities=()): |
0 | 84 |
"""return the system sql schema, according to the given parameters""" |
85 |
from yams.schema2sql import schema2sql |
|
86 |
from cubicweb.server.sources import native |
|
87 |
if set_owner: |
|
88 |
assert user, 'user is argument required when set_owner is true' |
|
89 |
output = [] |
|
90 |
w = output.append |
|
91 |
w(native.sql_schema(driver)) |
|
92 |
w('') |
|
93 |
if text_index: |
|
94 |
indexer = get_indexer(driver) |
|
95 |
w(indexer.sql_init_fti()) |
|
96 |
w('') |
|
97 |
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
|
98 |
w(schema2sql(dbhelper, schema, prefix=SQL_PREFIX, |
0 | 99 |
skip_entities=skip_entities, skip_relations=skip_relations)) |
100 |
if dbhelper.users_support and user: |
|
101 |
w('') |
|
102 |
w(sqlgrants(schema, driver, user, text_index, set_owner, |
|
103 |
skip_relations, skip_entities)) |
|
104 |
return '\n'.join(output) |
|
105 |
||
1619
e4845b54a704
force proper date/datetime according to type (necessary for sqlite at least)
sylvain.thenault@logilab.fr
parents:
1408
diff
changeset
|
106 |
|
e4845b54a704
force proper date/datetime according to type (necessary for sqlite at least)
sylvain.thenault@logilab.fr
parents:
1408
diff
changeset
|
107 |
def sqldropschema(schema, driver, text_index=True, |
2596
d02eed70937f
[R repo, schema] use VIRTUAL_RTYPES const
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2512
diff
changeset
|
108 |
skip_relations=PURE_VIRTUAL_RTYPES, skip_entities=()): |
0 | 109 |
"""return the sql to drop the schema, according to the given parameters""" |
110 |
from yams.schema2sql import dropschema2sql |
|
111 |
from cubicweb.server.sources import native |
|
112 |
output = [] |
|
113 |
w = output.append |
|
114 |
w(native.sql_drop_schema(driver)) |
|
115 |
w('') |
|
116 |
if text_index: |
|
117 |
indexer = get_indexer(driver) |
|
118 |
w(indexer.sql_drop_fti()) |
|
119 |
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
|
120 |
w(dropschema2sql(schema, prefix=SQL_PREFIX, |
1954 | 121 |
skip_entities=skip_entities, |
122 |
skip_relations=skip_relations)) |
|
0 | 123 |
return '\n'.join(output) |
124 |
||
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
125 |
try: |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
126 |
from mx.DateTime import DateTimeType, DateTimeDeltaType |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
127 |
except ImportError: |
1953 | 128 |
DateTimeType = DateTimeDeltaType = None |
0 | 129 |
|
130 |
class SQLAdapterMixIn(object): |
|
131 |
"""Mixin for SQL data sources, getting a connection from a configuration |
|
132 |
dictionary and handling connection locking |
|
133 |
""" |
|
1619
e4845b54a704
force proper date/datetime according to type (necessary for sqlite at least)
sylvain.thenault@logilab.fr
parents:
1408
diff
changeset
|
134 |
|
0 | 135 |
def __init__(self, source_config): |
136 |
try: |
|
137 |
self.dbdriver = source_config['db-driver'].lower() |
|
138 |
self.dbname = source_config['db-name'] |
|
139 |
except KeyError: |
|
140 |
raise ConfigurationError('missing some expected entries in sources file') |
|
141 |
self.dbhost = source_config.get('db-host') |
|
142 |
port = source_config.get('db-port') |
|
143 |
self.dbport = port and int(port) or None |
|
144 |
self.dbuser = source_config.get('db-user') |
|
145 |
self.dbpasswd = source_config.get('db-password') |
|
146 |
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
|
147 |
self.dbapi_module = db.get_dbapi_compliant_module(self.dbdriver) |
4177
f0ab2b6d3553
SqlServer: support single sign on / Windows credential authentication
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
4176
diff
changeset
|
148 |
self.dbdriver_extra_args = source_config.get('db-extra-arguments') |
0 | 149 |
self.binary = self.dbapi_module.Binary |
150 |
self.dbhelper = self.dbapi_module.adv_func_helper |
|
151 |
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
|
152 |
|
0 | 153 |
def get_connection(self, user=None, password=None): |
154 |
"""open and return a connection to the database""" |
|
155 |
if user or self.dbuser: |
|
156 |
self.info('connecting to %s@%s for user %s', self.dbname, |
|
157 |
self.dbhost or 'localhost', user or self.dbuser) |
|
158 |
else: |
|
159 |
self.info('connecting to %s@%s', self.dbname, |
|
160 |
self.dbhost or 'localhost') |
|
4179
3a0b2f14e17b
only give extra_args if there is something to be fed (breaks some db connectors otherwise)
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
4177
diff
changeset
|
161 |
extra = {} |
3a0b2f14e17b
only give extra_args if there is something to be fed (breaks some db connectors otherwise)
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
4177
diff
changeset
|
162 |
if self.dbdriver_extra_args: |
3a0b2f14e17b
only give extra_args if there is something to be fed (breaks some db connectors otherwise)
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
4177
diff
changeset
|
163 |
extra = {'extra_args': self.dbdriver_extra_args} |
0 | 164 |
cnx = self.dbapi_module.connect(self.dbhost, self.dbname, |
165 |
user or self.dbuser, |
|
166 |
password or self.dbpasswd, |
|
4177
f0ab2b6d3553
SqlServer: support single sign on / Windows credential authentication
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
4176
diff
changeset
|
167 |
port=self.dbport, |
4179
3a0b2f14e17b
only give extra_args if there is something to be fed (breaks some db connectors otherwise)
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
4177
diff
changeset
|
168 |
**extra) |
0 | 169 |
init_cnx(self.dbdriver, cnx) |
170 |
#self.dbapi_module.type_code_test(cnx.cursor()) |
|
171 |
return cnx |
|
172 |
||
2759
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2739
diff
changeset
|
173 |
def backup_to_file(self, backupfile): |
2493
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
174 |
cmd = self.dbhelper.backup_command(self.dbname, self.dbhost, |
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
175 |
self.dbuser, backupfile, |
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
176 |
keepownership=False) |
4298
2ca56131079e
enable cubicweb-ctl db-dump and db-restore on Windows with SQL Server
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
4212
diff
changeset
|
177 |
if subprocess.call(cmd): |
2759
23d7a75693f8
R refactor backup and use tar.gz to store all sources
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2739
diff
changeset
|
178 |
raise Exception('Failed command: %s' % cmd) |
2493
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
179 |
|
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
180 |
def restore_from_file(self, backupfile, confirm, drop=True): |
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
181 |
for cmd in self.dbhelper.restore_commands(self.dbname, self.dbhost, |
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
182 |
self.dbuser, backupfile, |
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
183 |
self.encoding, |
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
184 |
keepownership=False, |
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
185 |
drop=drop): |
4298
2ca56131079e
enable cubicweb-ctl db-dump and db-restore on Windows with SQL Server
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
4212
diff
changeset
|
186 |
if subprocess.call(cmd): |
4195
86dcaf6bb92f
closes #601987
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4179
diff
changeset
|
187 |
print '-> Failed command: %s' % cmd |
86dcaf6bb92f
closes #601987
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4179
diff
changeset
|
188 |
if not confirm('Continue anyway?', default='n'): |
86dcaf6bb92f
closes #601987
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4179
diff
changeset
|
189 |
raise Exception('Failed command: %s' % cmd) |
2493
9806571ea790
major refactoring of database dump/restore:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2396
diff
changeset
|
190 |
|
0 | 191 |
def merge_args(self, args, query_args): |
192 |
if args is not None: |
|
193 |
args = dict(args) |
|
194 |
for key, val in args.items(): |
|
195 |
# convert cubicweb binary into db binary |
|
196 |
if isinstance(val, Binary): |
|
197 |
val = self.binary(val.getvalue()) |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
198 |
# XXX <3.2 bw compat |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
199 |
elif type(val) is DateTimeType: |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
200 |
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
|
201 |
DeprecationWarning) |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
202 |
val = datetime(val.year, val.month, val.day, |
1026 | 203 |
val.hour, val.minute, int(val.second)) |
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
204 |
elif type(val) is DateTimeDeltaType: |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
0
diff
changeset
|
205 |
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
|
206 |
DeprecationWarning) |
1026 | 207 |
val = timedelta(0, int(val.seconds), 0) |
0 | 208 |
args[key] = val |
209 |
# should not collide |
|
210 |
args.update(query_args) |
|
211 |
return args |
|
212 |
return query_args |
|
213 |
||
214 |
def process_result(self, cursor): |
|
215 |
"""return a list of CubicWeb compliant values from data in the given cursor |
|
216 |
""" |
|
217 |
descr = cursor.description |
|
218 |
encoding = self.encoding |
|
219 |
process_value = self.dbapi_module.process_value |
|
220 |
binary = Binary |
|
221 |
results = cursor.fetchall() |
|
222 |
for i, line in enumerate(results): |
|
223 |
result = [] |
|
224 |
for col, value in enumerate(line): |
|
225 |
if value is None: |
|
226 |
result.append(value) |
|
227 |
continue |
|
228 |
result.append(process_value(value, descr[col], encoding, binary)) |
|
229 |
results[i] = result |
|
230 |
return results |
|
231 |
||
232 |
||
233 |
def preprocess_entity(self, entity): |
|
234 |
"""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
|
235 |
to insert/update an entity into a SQL database |
0 | 236 |
""" |
237 |
attrs = {} |
|
238 |
eschema = entity.e_schema |
|
239 |
for attr, value in entity.items(): |
|
3689
deb13e88e037
follow yams 0.25 api changes to improve performance
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3623
diff
changeset
|
240 |
rschema = eschema.subjrels[attr] |
deb13e88e037
follow yams 0.25 api changes to improve performance
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3623
diff
changeset
|
241 |
if rschema.final: |
0 | 242 |
atype = str(entity.e_schema.destination(attr)) |
243 |
if atype == 'Boolean': |
|
244 |
value = self.dbhelper.boolean_value(value) |
|
245 |
elif atype == 'Password': |
|
246 |
# if value is a Binary instance, this mean we got it |
|
247 |
# from a query result and so it is already encrypted |
|
248 |
if isinstance(value, Binary): |
|
249 |
value = value.getvalue() |
|
250 |
else: |
|
251 |
value = crypt_password(value) |
|
4176
42247d70105b
SQL Server port: convert Password to Binary
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
3689
diff
changeset
|
252 |
value = self.binary(value) |
1619
e4845b54a704
force proper date/datetime according to type (necessary for sqlite at least)
sylvain.thenault@logilab.fr
parents:
1408
diff
changeset
|
253 |
# 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
|
254 |
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
|
255 |
value = todatetime(value) |
e4845b54a704
force proper date/datetime according to type (necessary for sqlite at least)
sylvain.thenault@logilab.fr
parents:
1408
diff
changeset
|
256 |
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
|
257 |
value = todate(value) |
0 | 258 |
elif isinstance(value, Binary): |
259 |
value = self.binary(value.getvalue()) |
|
1408
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
260 |
# XXX <3.2 bw compat |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
261 |
elif type(value) is DateTimeType: |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
262 |
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
|
263 |
DeprecationWarning) |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
264 |
value = datetime(value.year, value.month, value.day, |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
265 |
value.hour, value.minute, int(value.second)) |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
266 |
elif type(value) is DateTimeDeltaType: |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
267 |
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
|
268 |
DeprecationWarning) |
6bf19f175ea5
mx.DateTime fixes
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
1263
diff
changeset
|
269 |
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
|
270 |
attrs[SQL_PREFIX+str(attr)] = value |
0 | 271 |
return attrs |
272 |
||
273 |
||
274 |
from logging import getLogger |
|
275 |
from cubicweb import set_log_methods |
|
276 |
set_log_methods(SQLAdapterMixIn, getLogger('cubicweb.sqladapter')) |
|
277 |
||
278 |
def init_sqlite_connexion(cnx): |
|
279 |
# XXX should not be publicly exposed |
|
280 |
#def comma_join(strings): |
|
281 |
# return ', '.join(strings) |
|
282 |
#cnx.create_function("COMMA_JOIN", 1, comma_join) |
|
283 |
||
284 |
class concat_strings(object): |
|
285 |
def __init__(self): |
|
286 |
self.values = [] |
|
287 |
def step(self, value): |
|
288 |
if value is not None: |
|
289 |
self.values.append(value) |
|
290 |
def finalize(self): |
|
291 |
return ', '.join(self.values) |
|
292 |
# renamed to GROUP_CONCAT in cubicweb 2.45, keep old name for bw compat for |
|
293 |
# some time |
|
294 |
cnx.create_aggregate("CONCAT_STRINGS", 1, concat_strings) |
|
295 |
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
|
296 |
|
0 | 297 |
def _limit_size(text, maxsize, format='text/plain'): |
298 |
if len(text) < maxsize: |
|
299 |
return text |
|
300 |
if format in ('text/html', 'text/xhtml', 'text/xml'): |
|
301 |
text = remove_html_tags(text) |
|
302 |
if len(text) > maxsize: |
|
303 |
text = text[:maxsize] + '...' |
|
304 |
return text |
|
305 |
||
306 |
def limit_size3(text, format, maxsize): |
|
307 |
return _limit_size(text, maxsize, format) |
|
308 |
cnx.create_function("LIMIT_SIZE", 3, limit_size3) |
|
309 |
||
310 |
def limit_size2(text, maxsize): |
|
311 |
return _limit_size(text, maxsize) |
|
312 |
cnx.create_function("TEXT_LIMIT_SIZE", 2, limit_size2) |
|
313 |
import yams.constraints |
|
314 |
if hasattr(yams.constraints, 'patch_sqlite_decimal'): |
|
315 |
yams.constraints.patch_sqlite_decimal() |
|
316 |
||
4322
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
317 |
def fspath(eid, etype, attr): |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
318 |
try: |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
319 |
cu = cnx.cursor() |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
320 |
cu.execute('SELECT X.cw_%s FROM cw_%s as X ' |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
321 |
'WHERE X.cw_eid=%%(eid)s' % (attr, etype), |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
322 |
{'eid': eid}) |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
323 |
return cu.fetchone()[0] |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
324 |
except: |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
325 |
import traceback |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
326 |
traceback.print_exc() |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
327 |
raise |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
328 |
cnx.create_function('fspath', 3, fspath) |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
329 |
|
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
330 |
def _fsopen(fspath): |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
331 |
if fspath: |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
332 |
try: |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
333 |
return buffer(file(fspath).read()) |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
334 |
except: |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
335 |
import traceback |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
336 |
traceback.print_exc() |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
337 |
raise |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
338 |
cnx.create_function('_fsopen', 1, _fsopen) |
f65743cc53e4
first draft for a simple hooks based custom attribute storage,
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4314
diff
changeset
|
339 |
|
0 | 340 |
|
341 |
sqlite_hooks = SQL_CONNECT_HOOKS.setdefault('sqlite', []) |
|
342 |
sqlite_hooks.append(init_sqlite_connexion) |
|
343 |
||
344 |
def init_cnx(driver, cnx): |
|
345 |
for hook in SQL_CONNECT_HOOKS.get(driver, ()): |
|
346 |
hook(cnx) |