/usr/lib/python2.7/dist-packages/trytond/backend/mysql/database.py is in tryton-server 3.0.2-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | #This file is part of Tryton. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
from trytond.backend.database import DatabaseInterface, CursorInterface
from trytond.config import CONFIG
import MySQLdb
import MySQLdb.cursors
import MySQLdb.converters
from MySQLdb import IntegrityError as DatabaseIntegrityError
from MySQLdb import OperationalError as DatabaseOperationalError
import os
import time
import tempfile
from sql import Flavor, Expression
from sql.functions import Extract, Overlay, CharLength
__all__ = ['Database', 'DatabaseIntegrityError', 'DatabaseOperationalError',
'Cursor']
class MySQLExtract(Extract):
def is_epoch(self):
return self.args[0].upper() == 'EPOCH'
def __str__(self):
if self.is_epoch():
return 'UNIX_TIMESTAMP(%s)' % self._format(self.args[1])
return super(MySQLExtract, self).__str__()
@property
def params(self):
if self.is_epoch():
arg = self.args[1]
if isinstance(arg, Expression):
return arg.params
else:
return (arg,)
return super(MySQLExtract, self).params
class MySQLOverlay(Overlay):
@property
def mysql_args(self):
if len(self.args) == 3:
string, placing, from_ = self.args
for_ = CharLength(placing)
else:
string, placing, from_, for_ = self.args
return (string, from_, placing, string, from_, for_)
def __str__(self):
return ('CONCAT(SUBSTRING(%s FROM 1 FOR %s), %s, '
'SUBSTRING(%s FROM %s + 1 + %s))'
% tuple(map(self._format, self.mysql_args)))
@property
def params(self):
p = ()
for arg in self.mysql_args:
if isinstance(arg, Expression):
p += arg.params
else:
p += (arg,)
return p
MAPPING = {
Extract: MySQLExtract,
Overlay: MySQLOverlay,
}
class Database(DatabaseInterface):
_list_cache = None
_list_cache_timestamp = None
flavor = Flavor(max_limit=18446744073709551610, function_mapping=MAPPING)
def connect(self):
return self
def cursor(self, autocommit=False, readonly=False):
conv = MySQLdb.converters.conversions.copy()
conv[float] = lambda value, _: repr(value)
conv[MySQLdb.constants.FIELD_TYPE.TIME] = MySQLdb.times.Time_or_None
args = {
'db': self.database_name,
'sql_mode': 'traditional,postgresql',
'use_unicode': True,
'charset': 'utf8',
'conv': conv,
}
if CONFIG['db_host']:
args['host'] = CONFIG['db_host']
if CONFIG['db_port']:
args['port'] = int(CONFIG['db_port'])
if CONFIG['db_user']:
args['user'] = CONFIG['db_user']
if CONFIG['db_password']:
args['passwd'] = CONFIG['db_password']
conn = MySQLdb.connect(**args)
return Cursor(conn, self.database_name)
def close(self):
return
def create(self, cursor, database_name):
cursor.execute('CREATE DATABASE `' + database_name + '` '
'DEFAULT CHARACTER SET = \'utf8\'')
Database._list_cache = None
def drop(self, cursor, database_name):
cursor.execute('DROP DATABASE `' + database_name + '`')
Database._list_cache = None
@staticmethod
def dump(database_name):
from trytond.tools import exec_pg_command_pipe
cmd = ['mysqldump', '--no-create-db']
if CONFIG['db_user']:
cmd.append('--user=' + CONFIG['db_user'])
if CONFIG['db_host']:
cmd.append('--host=' + CONFIG['db_host'])
if CONFIG['db_port']:
cmd.append('--port=' + CONFIG['db_port'])
if CONFIG['db_password']:
cmd.append('--password=' + CONFIG['db_password'])
cmd.append(database_name)
pipe = exec_pg_command_pipe(*tuple(cmd))
pipe.stdin.close()
data = pipe.stdout.read()
res = pipe.wait()
if res:
raise Exception('Couldn\'t dump database!')
return data
@staticmethod
def restore(database_name, data):
from trytond.tools import exec_pg_command_pipe
database = Database().connect()
cursor = database.cursor(autocommit=True)
database.create(cursor, database_name)
cursor.commit()
cursor.close()
cmd = ['mysql']
if CONFIG['db_user']:
cmd.append('--user=' + CONFIG['db_user'])
if CONFIG['db_host']:
cmd.append('--host=' + CONFIG['db_host'])
if CONFIG['db_port']:
cmd.append('--port=' + CONFIG['db_port'])
if CONFIG['db_password']:
cmd.append('--password=' + CONFIG['db_password'])
cmd.append(database_name)
fd, file_name = tempfile.mkstemp()
with os.fdopen(fd, 'wb+') as fd:
fd.write(data)
cmd.append('<')
cmd.append(file_name)
args2 = tuple(cmd)
pipe = exec_pg_command_pipe(*args2)
pipe.stdin.close()
res = pipe.wait()
os.remove(file_name)
if res:
raise Exception('Couldn\'t restore database')
database = Database(database_name).connect()
cursor = database.cursor()
if not cursor.test():
cursor.close()
database.close()
raise Exception('Couldn\'t restore database!')
cursor.close()
database.close()
Database._list_cache = None
return True
@staticmethod
def list(cursor):
now = time.time()
timeout = int(CONFIG['session_timeout'])
res = Database._list_cache
if res and abs(Database._list_cache_timestamp - now) < timeout:
return res
cursor.execute('SHOW DATABASES')
res = []
for db_name, in cursor.fetchall():
try:
database = Database(db_name).connect()
except Exception:
continue
cursor2 = database.cursor()
if cursor2.test():
res.append(db_name)
cursor2.close(close=True)
else:
cursor2.close()
database.close()
Database._list_cache = res
Database._list_cache_timestamp = now
return res
@staticmethod
def init(cursor):
from trytond.modules import get_module_info
sql_file = os.path.join(os.path.dirname(__file__), 'init.sql')
with open(sql_file) as fp:
for line in fp.read().split(';'):
if (len(line) > 0) and (not line.isspace()):
cursor.execute(line)
for module in ('ir', 'res', 'webdav'):
state = 'uninstalled'
if module in ('ir', 'res'):
state = 'to install'
info = get_module_info(module)
cursor.execute('INSERT INTO ir_module_module '
'(create_uid, create_date, name, state) '
'VALUES (%s, now(), %s, %s)',
(0, module, state))
cursor.execute('SELECT LAST_INSERT_ID()')
module_id, = cursor.fetchone()
for dependency in info.get('depends', []):
cursor.execute('INSERT INTO ir_module_module_dependency '
'(create_uid, create_date, module, name) '
'VALUES (%s, now(), %s, %s)',
(0, module_id, dependency))
class _Cursor(MySQLdb.cursors.Cursor):
def __build_dict(self, row):
return dict((desc[0], row[i])
for i, desc in enumerate(self.description))
def dictfetchone(self):
row = self.fetchone()
if row:
return self.__build_dict(row)
else:
return row
def dictfetchmany(self, size):
rows = self.fetchmany(size)
return [self.__build_dict(row) for row in rows]
def dictfetchall(self):
rows = self.fetchall()
return [self.__build_dict(row) for row in rows]
def fetchall(self):
return list(super(_Cursor, self).fetchall())
class Cursor(CursorInterface):
def __init__(self, conn, database_name):
super(Cursor, self).__init__()
self._conn = conn
self.database_name = database_name
self.dbname = self.database_name # XXX to remove
self.cursor = conn.cursor(_Cursor)
def __getattr__(self, name):
return getattr(self.cursor, name)
def execute(self, sql, params=None):
if params:
return self.cursor.execute(sql, params)
else:
return self.cursor.execute(sql)
def close(self, close=False):
self.cursor.close()
self.rollback()
def commit(self):
super(Cursor, self).commit()
self._conn.commit()
def rollback(self):
super(Cursor, self).rollback()
self._conn.rollback()
def test(self):
self.cursor.execute("SHOW TABLES")
for table, in self.cursor.fetchall():
if table in (
'ir_model',
'ir_model_field',
'ir_ui_view',
'ir_ui_menu',
'res_user',
'res_group',
'ir_module_module',
'ir_module_module_dependency',
'ir_translation',
'ir_lang',
):
return True
return False
def lastid(self):
self.cursor.execute('SELECT LAST_INSERT_ID()')
return self.cursor.fetchone()[0]
def lock(self, table):
# Lock of table doesn't work because MySQL require
# that the session locks all tables that will be accessed
# but 'FLUSH TABLES WITH READ LOCK' creates deadlock
pass
def has_constraint(self):
return False
def limit_clause(self, select, limit=None, offset=None):
if offset and limit is None:
limit = 18446744073709551610 # max bigint
if limit is not None:
select += ' LIMIT %d' % limit
if offset is not None and offset != 0:
select += ' OFFSET %d' % offset
return select
def update_auto_increment(self, table, value):
self.cursor.execute('ALTER TABLE `%s` AUTO_INCREMENT = %%s' % table,
value)
|