Files
tryton/trytond/model/modelsql.py
T

2086 lines
93 KiB
Python
Raw Normal View History

2009-02-02 13:08:25 +01:00
#This file is part of Tryton. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
2010-08-19 22:01:12 +02:00
import contextlib
import datetime
import re
from functools import reduce
2010-10-11 13:20:09 +02:00
from decimal import Decimal
2013-01-06 22:18:13 +01:00
from itertools import islice, izip
2012-11-23 17:59:04 +01:00
from trytond.model import ModelStorage
2009-02-03 18:58:25 +01:00
from trytond.model import fields
from trytond.backend import FIELDS, TableHandler
2011-11-02 15:49:38 +01:00
from trytond.backend import DatabaseIntegrityError
2009-09-08 13:03:57 +02:00
from trytond.tools import reduce_ids
2011-06-14 11:44:26 +02:00
from trytond.const import OPERATORS, RECORD_CACHE_SIZE
2010-08-19 22:01:12 +02:00
from trytond.transaction import Transaction
2011-07-03 13:20:58 +02:00
from trytond.pool import Pool
2011-06-14 11:44:26 +02:00
from trytond.cache import LRUDict
2011-09-05 20:30:26 +02:00
from trytond.exceptions import ConcurrencyException
_RE_UNIQUE = re.compile('UNIQUE\s*\((.*)\)', re.I)
_RE_CHECK = re.compile('CHECK\s*\((.*)\)', re.I)
2009-02-02 13:08:25 +01:00
2009-02-12 11:33:39 +01:00
class ModelSQL(ModelStorage):
2009-02-02 13:08:25 +01:00
"""
2009-09-13 15:37:11 +02:00
Define a model with storage in database.
2009-02-02 13:08:25 +01:00
"""
2012-04-01 23:08:15 +02:00
_table = None # The name of the table in database
2009-02-02 13:08:25 +01:00
_order = None
2012-04-01 23:08:15 +02:00
_order_name = None # Use to force order field when sorting on Many2One
_history = False
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
@classmethod
def __setup__(cls):
super(ModelSQL, cls).__setup__()
cls._sql_constraints = []
cls._order = [('id', 'ASC')]
cls._sql_error_messages = {}
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
if not cls._table:
cls._table = cls.__name__.replace('.', '_')
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
assert cls._table[-9:] != '__history', \
2013-02-27 22:50:31 +01:00
'Model _table %s cannot end with "__history"' % cls._table
2012-09-24 22:16:53 +02:00
@classmethod
def __register__(cls, module_name):
super(ModelSQL, cls).__register__(module_name)
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
if cls.table_query():
2009-02-02 13:08:25 +01:00
return
2011-07-03 13:20:58 +02:00
pool = Pool()
2009-02-02 13:08:25 +01:00
# create/update table in the database
2012-09-24 22:16:53 +02:00
table = TableHandler(Transaction().cursor, cls, module_name)
if cls._history:
history_table = TableHandler(Transaction().cursor, cls,
2010-08-19 22:01:12 +02:00
module_name, history=True)
2009-11-10 14:00:13 +01:00
timestamp_field = FIELDS['timestamp']
2009-02-03 18:58:25 +01:00
integer_field = FIELDS['integer']
2009-02-02 13:08:25 +01:00
logs = (
2009-11-10 14:00:13 +01:00
('create_date', timestamp_field.sql_type(None),
timestamp_field.sql_format, lambda *a: datetime.datetime.now(),
2012-09-24 22:16:53 +02:00
cls.create_date.string),
2009-11-10 14:00:13 +01:00
('write_date', timestamp_field.sql_type(None),
2012-09-24 22:16:53 +02:00
timestamp_field.sql_format, None, cls.write_date.string),
2009-02-03 18:58:25 +01:00
('create_uid', (integer_field.sql_type(None)[0],
'INTEGER REFERENCES res_user ON DELETE SET NULL',),
2012-09-24 22:16:53 +02:00
integer_field.sql_format, lambda *a: 0, cls.create_uid.string),
2009-02-03 18:58:25 +01:00
('write_uid', (integer_field.sql_type(None)[0],
'INTEGER REFERENCES res_user ON DELETE SET NULL'),
2012-09-24 22:16:53 +02:00
integer_field.sql_format, None, cls.write_uid.string),
2009-02-02 13:08:25 +01:00
)
for log in logs:
table.add_raw_column(log[0], log[1], log[2],
default_fun=log[3], migrate=False, string=log[4])
2012-09-24 22:16:53 +02:00
if cls._history:
history_logs = (
2009-11-10 14:00:13 +01:00
('create_date', timestamp_field.sql_type(None),
2012-09-24 22:16:53 +02:00
timestamp_field.sql_format, cls.create_date.string),
2009-11-10 14:00:13 +01:00
('write_date', timestamp_field.sql_type(None),
2012-09-24 22:16:53 +02:00
timestamp_field.sql_format, cls.write_date.string),
('create_uid', (integer_field.sql_type(None)[0],
'INTEGER REFERENCES res_user ON DELETE SET NULL',),
2012-09-24 22:16:53 +02:00
integer_field.sql_format, cls.create_uid.string),
('write_uid', (integer_field.sql_type(None)[0],
'INTEGER REFERENCES res_user ON DELETE SET NULL'),
2012-09-24 22:16:53 +02:00
integer_field.sql_format, cls.write_uid.string),
)
for log in history_logs:
history_table.add_raw_column(log[0], log[1], log[2],
2010-01-12 09:08:16 +01:00
migrate=False, string=log[3])
history_table.index_action('id', action='add')
2012-09-24 22:16:53 +02:00
for field_name, field in cls._fields.iteritems():
2009-02-02 13:08:25 +01:00
default_fun = None
if field_name in (
'id',
'write_uid',
'write_date',
'create_uid',
'create_date',
2009-02-26 00:44:41 +01:00
'rec_name',
2009-02-02 13:08:25 +01:00
):
continue
2009-02-03 18:58:25 +01:00
if not hasattr(field, 'set'):
2012-09-24 22:16:53 +02:00
if field_name in cls._defaults:
default_fun = cls._defaults[field_name]
2009-02-02 13:08:25 +01:00
def unpack_wrapper(fun):
def unpack_result(*a):
2012-04-01 23:08:15 +02:00
try:
# XXX ugly hack: some default fct try
# to access the non-existing table
2009-02-02 13:08:25 +01:00
result = fun(*a)
2010-07-08 19:53:39 +02:00
except Exception:
2009-02-02 13:08:25 +01:00
return None
2012-09-24 22:16:53 +02:00
clean_results = cls._clean_defaults(
2009-02-02 13:08:25 +01:00
{field_name: result})
return clean_results[field_name]
return unpack_result
default_fun = unpack_wrapper(default_fun)
if hasattr(field, 'size') and isinstance(field.size, int):
field_size = field.size
else:
field_size = None
2009-02-03 18:58:25 +01:00
table.add_raw_column(field_name,
FIELDS[field._type].sql_type(field),
FIELDS[field._type].sql_format, default_fun,
field_size, string=field.string)
2012-09-24 22:16:53 +02:00
if cls._history:
history_table.add_raw_column(field_name,
FIELDS[field._type].sql_type(field), None,
string=field.string)
2009-02-02 13:08:25 +01:00
if isinstance(field, (fields.Integer, fields.Float)):
# migration from tryton 2.2
table.db_default(field_name, None)
2009-02-02 13:08:25 +01:00
if isinstance(field, (fields.Boolean)):
table.db_default(field_name, False)
2009-02-02 13:08:25 +01:00
if isinstance(field, fields.Many2One):
2009-02-03 18:58:25 +01:00
if field.model_name in ('res.user', 'res.group'):
2012-04-01 23:08:15 +02:00
ref = field.model_name.replace('.', '_')
2009-02-02 13:08:25 +01:00
else:
2011-07-03 13:20:58 +02:00
ref = pool.get(field.model_name)._table
2009-02-02 13:08:25 +01:00
table.add_fk(field_name, ref, field.ondelete)
table.index_action(
field_name, action=field.select and 'add' or 'remove')
required = field.required
table.not_null_action(
field_name, action=required and 'add' or 'remove')
elif not isinstance(field, (fields.One2Many, fields.Function,
2013-02-27 22:50:31 +01:00
fields.Many2Many)):
2009-02-02 13:08:25 +01:00
raise Exception('Unknow field type !')
2012-09-24 22:16:53 +02:00
for field_name, field in cls._fields.iteritems():
2009-02-02 13:08:25 +01:00
if isinstance(field, fields.Many2One) \
2012-09-24 22:16:53 +02:00
and field.model_name == cls.__name__ \
2009-02-02 13:08:25 +01:00
and field.left and field.right:
2010-08-19 22:01:12 +02:00
with Transaction().set_user(0):
2012-09-24 22:16:53 +02:00
cls._rebuild_tree(field_name, False, 0)
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
for ident, constraint, _ in cls._sql_constraints:
2009-02-02 13:08:25 +01:00
table.add_constraint(ident, constraint)
2012-09-24 22:16:53 +02:00
if cls._history:
cls._update_history_table()
2010-08-19 22:01:12 +02:00
cursor = Transaction().cursor
2012-09-24 22:16:53 +02:00
cursor.execute('SELECT id FROM "' + cls._table + '"')
if cursor.fetchone():
2012-09-24 22:16:53 +02:00
cursor.execute('SELECT id FROM "' + cls._table + '__history"')
if not cursor.fetchone():
2012-09-24 22:16:53 +02:00
columns = ['"' + str(x) + '"' for x in cls._fields
if not hasattr(cls._fields[x], 'set')]
2013-02-27 22:50:31 +01:00
cursor.execute('INSERT INTO "' + cls._table + '__history" '
'(' + ','.join(columns) + ') '
'SELECT ' + ','.join(columns) +
' FROM "' + cls._table + '"')
cursor.execute('UPDATE "' + cls._table + '__history" '
'SET write_date = NULL')
2012-09-24 22:16:53 +02:00
@classmethod
def _update_history_table(cls):
if cls._history:
table = TableHandler(Transaction().cursor, cls)
history_table = TableHandler(Transaction().cursor, cls,
2010-08-19 22:01:12 +02:00
history=True)
for column_name in table._columns:
string = ''
2012-09-24 22:16:53 +02:00
if column_name in cls._fields:
string = cls._fields[column_name].string
history_table.add_raw_column(column_name,
2012-09-24 22:16:53 +02:00
(table._columns[column_name]['typname'],
table._columns[column_name]['typname']),
None, string=string)
2012-09-24 22:16:53 +02:00
@classmethod
def _get_error_messages(cls):
res = super(ModelSQL, cls)._get_error_messages()
res += cls._sql_error_messages.values()
for _, _, error in cls._sql_constraints:
2009-02-02 13:08:25 +01:00
res.append(error)
return res
2012-09-24 22:16:53 +02:00
@staticmethod
def table_query():
2009-02-02 13:08:25 +01:00
'''
Return None if the model is a real table in the database
or return a tuple with the SQL query and the arguments.
'''
return None
2012-09-24 22:16:53 +02:00
@classmethod
2013-01-06 22:18:13 +01:00
def create(cls, vlist):
super(ModelSQL, cls).create(vlist)
2010-08-19 22:01:12 +02:00
cursor = Transaction().cursor
2011-07-03 13:20:58 +02:00
pool = Pool()
2012-09-24 22:16:53 +02:00
if cls.table_query():
2009-02-02 13:08:25 +01:00
return False
2013-01-06 22:18:13 +01:00
modified_fields = set()
new_ids = []
vlist = [v.copy() for v in vlist]
for values in vlist:
# Clean values
for key in ('create_uid', 'create_date', 'write_uid', 'write_date',
'id'):
if key in values:
del values[key]
modified_fields |= set(values.keys())
2009-02-02 13:08:25 +01:00
2013-01-06 22:18:13 +01:00
# Get default values
default = []
for i in cls._fields.keys():
if not i in values \
and i not in ('create_uid', 'create_date',
'write_uid', 'write_date'):
default.append(i)
2009-02-02 13:08:25 +01:00
2013-01-06 22:18:13 +01:00
if len(default):
defaults = cls.default_get(default, with_rec_name=False)
for field in defaults.keys():
if '.' in field:
del defaults[field]
if field in ('create_uid', 'create_date',
2009-02-02 13:08:25 +01:00
'write_uid', 'write_date'):
2013-01-06 22:18:13 +01:00
del defaults[field]
if field in values:
del defaults[field]
values.update(cls._clean_defaults(defaults))
2009-02-02 13:08:25 +01:00
2013-01-06 22:18:13 +01:00
(upd0, upd1, upd2) = ('', '', [])
2009-02-02 13:08:25 +01:00
2013-01-06 22:18:13 +01:00
# Insert record
for fname, value in values.iteritems():
field = cls._fields[fname]
if not hasattr(field, 'set'):
upd0 = upd0 + ',"' + fname + '"'
upd1 = upd1 + ', %s'
upd2.append(FIELDS[field._type].sql_format(value))
upd0 += ', create_uid, create_date'
upd1 += ', %s, %s'
upd2.append(Transaction().user)
upd2.append(datetime.datetime.now())
try:
if cursor.has_returning():
2012-09-24 22:16:53 +02:00
cursor.execute('INSERT INTO "' + cls._table + '" '
2011-08-21 10:20:23 +02:00
'(' + upd0[1:] + ') '
2013-01-06 22:18:13 +01:00
'VALUES (' + upd1[1:] + ') RETURNING id',
2011-08-21 10:20:23 +02:00
tuple(upd2))
2013-01-06 22:18:13 +01:00
id_new, = cursor.fetchone()
else:
id_new = cursor.nextid(cls._table)
if id_new:
cursor.execute('INSERT INTO "' + cls._table + '" '
'(id' + upd0 + ') '
'VALUES (' + str(id_new) + upd1 + ')',
tuple(upd2))
else:
cursor.execute('INSERT INTO "' + cls._table + '" '
'(' + upd0[1:] + ') '
'VALUES (' + upd1[1:] + ')',
tuple(upd2))
id_new = cursor.lastid()
new_ids.append(id_new)
except DatabaseIntegrityError, exception:
with contextlib.nested(Transaction().new_cursor(),
Transaction().set_user(0)):
for field_name in cls._fields:
field = cls._fields[field_name]
# Check required fields
2013-02-27 22:50:31 +01:00
if (field.required
and not hasattr(field, 'set')
and field_name not in (
'create_uid', 'create_date')):
2013-01-06 22:18:13 +01:00
if values.get(field_name) is None:
cls.raise_user_error('required_field',
error_args=cls._get_error_args(
field_name))
if isinstance(field, fields.Many2One) \
and values.get(field_name):
Model = pool.get(field.model_name)
create_records = Transaction().create_records.get(
field.model_name, set())
delete_records = Transaction().delete_records.get(
field.model_name, set())
if not ((Model.search([
2013-02-27 22:50:31 +01:00
('id', '=',
values[field_name]),
2013-01-06 22:18:13 +01:00
], order=[])
2013-02-27 22:50:31 +01:00
or values[field_name] in
create_records)
and values[field_name] not in
2013-01-06 22:18:13 +01:00
delete_records):
cls.raise_user_error('foreign_model_missing',
error_args=cls._get_error_args(
field_name))
for name, _, error in cls._sql_constraints:
if name in exception[0]:
cls.raise_user_error(error)
2013-03-04 21:30:17 +01:00
for name, error in cls._sql_error_messages.iteritems():
2013-01-06 22:18:13 +01:00
if name in exception[0]:
cls.raise_user_error(error)
raise
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
domain1, domain2 = pool.get('ir.rule').domain_get(cls.__name__,
2010-08-19 22:01:12 +02:00
mode='create')
if domain1:
2013-01-06 22:18:13 +01:00
in_max = Transaction().cursor.IN_MAX
for i in range(0, len(new_ids), in_max):
sub_ids = new_ids[i:i + in_max]
red_sql, red_ids = reduce_ids('id', sub_ids)
2013-01-06 22:18:13 +01:00
cursor.execute('SELECT id FROM "' + cls._table + '" WHERE ' +
red_sql + ' AND (' + domain1 + ')', red_ids + domain2)
if len(cursor.fetchall()) != len(sub_ids):
cls.raise_user_error('access_error', cls.__name__)
2013-02-27 22:50:31 +01:00
create_records = Transaction().create_records.setdefault(cls.__name__,
set()).update(new_ids)
2010-09-30 19:59:14 +02:00
2013-01-06 22:18:13 +01:00
for values, new_id in izip(vlist, new_ids):
for fname, value in values.iteritems():
field = cls._fields[fname]
if getattr(field, 'translate', False):
2013-01-06 22:18:13 +01:00
pool.get('ir.translation').set_ids(
cls.__name__ + ',' + fname, 'model',
Transaction().language, [new_id], value)
if hasattr(field, 'set'):
field.set([new_id], cls, fname, value)
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
if cls._history:
2013-02-27 22:50:31 +01:00
columns = ['"' + str(x) + '"' for x in cls._fields
2013-01-06 22:18:13 +01:00
if not hasattr(cls._fields[x], 'set')]
columns = ','.join(columns)
for i in range(0, len(new_ids), cursor.IN_MAX):
sub_ids = new_ids[i:i + cursor.IN_MAX]
red_sql, red_ids = reduce_ids('id', sub_ids)
2013-02-27 22:50:31 +01:00
cursor.execute('INSERT INTO "' + cls._table + '__history" '
2013-01-06 22:18:13 +01:00
'(' + columns + ') '
'SELECT ' + columns + ' '
'FROM "' + cls._table + '" '
'WHERE ' + red_sql, red_ids)
2013-01-06 22:18:13 +01:00
records = cls.browse(new_ids)
cls._validate(records)
2009-02-02 13:08:25 +01:00
# Check for Modified Preorder Tree Traversal
2012-09-24 22:16:53 +02:00
for k in cls._fields:
field = cls._fields[k]
2013-01-06 22:18:13 +01:00
if (isinstance(field, fields.Many2One)
and field.model_name == cls.__name__
and field.left and field.right):
if len(new_ids) == 1:
cls._update_tree(new_ids[0], k, field.left, field.right)
else:
with Transaction().set_user(0):
cls._rebuild_tree(k, False, 0)
2009-02-02 13:08:25 +01:00
2013-01-06 22:18:13 +01:00
cls.trigger_create(records)
return records
2013-02-27 22:50:31 +01:00
2012-09-24 22:16:53 +02:00
@classmethod
def read(cls, ids, fields_names=None):
2011-07-03 13:20:58 +02:00
pool = Pool()
2012-09-24 22:16:53 +02:00
Rule = pool.get('ir.rule')
Translation = pool.get('ir.translation')
super(ModelSQL, cls).read(ids, fields_names=fields_names)
2010-08-19 22:01:12 +02:00
cursor = Transaction().cursor
2009-02-02 13:08:25 +01:00
if not fields_names:
2013-03-20 22:49:16 +01:00
fields_names = cls._fields.keys()
2009-02-02 13:08:25 +01:00
if not ids:
return []
# construct a clause for the rules :
2012-09-24 22:16:53 +02:00
domain1, domain2 = Rule.domain_get(cls.__name__, mode='read')
2009-02-02 13:08:25 +01:00
fields_related = {}
datetime_fields = []
for field_name in fields_names:
if field_name == '_timestamp':
continue
if '.' in field_name:
field, field_related = field_name.split('.', 1)
fields_related.setdefault(field, [])
fields_related[field].append(field_related)
else:
2013-03-20 22:49:16 +01:00
field = cls._fields[field_name]
if hasattr(field, 'datetime_field') and field.datetime_field:
datetime_fields.append(field.datetime_field)
2013-03-20 22:49:16 +01:00
fields_pre = [x
for x in fields_names + fields_related.keys() + datetime_fields
if (x in cls._fields and not hasattr(cls._fields[x], 'set'))
or (x == '_timestamp')]
2009-02-02 13:08:25 +01:00
res = []
table_query = ''
table_args = []
2012-09-24 22:16:53 +02:00
if cls.table_query():
table_query, table_args = cls.table_query()
2009-02-02 13:08:25 +01:00
table_query = '(' + table_query + ') AS '
in_max = cursor.IN_MAX
history_order = ''
history_clause = ''
history_limit = ''
history_args = []
2012-09-24 22:16:53 +02:00
if (cls._history
2010-08-19 22:01:12 +02:00
and Transaction().context.get('_datetime')
and not table_query):
in_max = 1
2012-09-24 22:16:53 +02:00
table_query = '"' + cls._table + '__history" AS '
history_clause = ' AND (COALESCE(write_date, create_date) <= %s)'
history_order = ' ORDER BY COALESCE(write_date, create_date) DESC'
2009-09-07 15:18:17 +02:00
history_limit = cursor.limit_clause('', 1)
2010-08-19 22:01:12 +02:00
history_args = [Transaction().context['_datetime']]
2012-04-01 23:08:15 +02:00
if len(fields_pre):
2012-09-24 22:16:53 +02:00
fields_pre2 = ['"%s"."%s" AS "%s"' % (cls._table, x, x)
for x in fields_pre if x != '_timestamp']
2009-02-02 13:08:25 +01:00
if '_timestamp' in fields_pre:
2012-09-24 22:16:53 +02:00
if not cls.table_query():
fields_pre2 += ['CAST(EXTRACT(EPOCH FROM '
2012-03-03 12:25:27 +01:00
'(COALESCE("%s".write_date, "%s".create_date))) '
2010-10-11 13:20:09 +02:00
'AS VARCHAR) AS _timestamp' %
2012-09-24 22:16:53 +02:00
(cls._table, cls._table)]
if 'id' not in fields_pre:
2012-09-24 22:16:53 +02:00
fields_pre2 += ['"%s".id AS id' % cls._table]
2009-02-02 13:08:25 +01:00
for i in range(0, len(ids), in_max):
sub_ids = ids[i:i + in_max]
2009-09-08 13:03:57 +02:00
red_sql, red_ids = reduce_ids('id', sub_ids)
2009-02-02 13:08:25 +01:00
if domain1:
cursor.execute('SELECT ' + ','.join(fields_pre2)
2012-09-24 22:16:53 +02:00
+ ' FROM ' + table_query + '\"' + cls._table + '\" '
2012-04-01 23:08:15 +02:00
'WHERE ' + red_sql + history_clause +
' AND (' + domain1 + ') '
+ history_order
+ history_limit,
table_args + red_ids + history_args + domain2)
2009-02-02 13:08:25 +01:00
else:
cursor.execute('SELECT ' + ','.join(fields_pre2)
2012-09-24 22:16:53 +02:00
+ ' FROM ' + table_query + '\"' + cls._table + '\" '
2012-04-01 23:08:15 +02:00
'WHERE ' + red_sql + history_clause
+ history_order
+ history_limit,
table_args + red_ids + history_args)
dictfetchall = cursor.dictfetchall()
if not len(dictfetchall) == len({}.fromkeys(sub_ids)):
if domain1:
2012-04-01 23:08:15 +02:00
cursor.execute('SELECT id '
2012-09-24 22:16:53 +02:00
'FROM ' + table_query + '\"' + cls._table + '\" '
2012-04-01 23:08:15 +02:00
'WHERE ' + red_sql + history_clause
+ history_order
+ history_limit,
table_args + red_ids + history_args)
rowcount = cursor.rowcount
if rowcount == -1 or rowcount is None:
rowcount = len(cursor.fetchall())
if rowcount == len({}.fromkeys(sub_ids)):
2012-09-24 22:16:53 +02:00
cls.raise_user_error('access_error', cls.__name__)
cls.raise_user_error('read_error', cls.__name__)
res.extend(dictfetchall)
2009-02-02 13:08:25 +01:00
else:
res = [{'id': x} for x in ids]
for field in fields_pre:
if field == '_timestamp':
continue
2012-09-24 22:16:53 +02:00
if getattr(cls._fields[field], 'translate', False):
2009-02-02 13:08:25 +01:00
ids = [x['id'] for x in res]
2012-09-24 22:16:53 +02:00
res_trans = Translation.get_ids(cls.__name__ + ',' + field,
2012-04-01 23:08:15 +02:00
'model', Transaction().language, ids)
2009-02-02 13:08:25 +01:00
for i in res:
i[field] = res_trans.get(i['id'], False) or i[field]
ids = [x['id'] for x in res]
2013-03-20 22:49:16 +01:00
# all fields for which there is a get attribute
2013-02-27 22:50:31 +01:00
fields_post = [x for x in
fields_names + fields_related.keys() + datetime_fields
if x in cls._fields and hasattr(cls._fields[x], 'get')]
2009-02-02 13:08:25 +01:00
func_fields = {}
for field in fields_post:
2012-09-24 22:16:53 +02:00
if isinstance(cls._fields[field], fields.Function):
key = (cls._fields[field].getter,
2013-02-27 22:50:31 +01:00
getattr(cls._fields[field], 'datetime_field', None))
2009-02-02 13:08:25 +01:00
func_fields.setdefault(key, [])
func_fields[key].append(field)
continue
2012-09-24 22:16:53 +02:00
if hasattr(cls._fields[field], 'datetime_field') \
and cls._fields[field].datetime_field:
for record in res:
2012-04-01 23:08:15 +02:00
with Transaction().set_context(_datetime=record[
2012-09-24 22:16:53 +02:00
cls._fields[field].datetime_field]):
res2 = cls._fields[field].get([record['id']], cls,
2012-04-01 23:08:15 +02:00
field, values=[record])
record[field] = res2[record['id']]
continue
2009-02-02 13:08:25 +01:00
# get the value of that field for all records/ids
2012-09-24 22:16:53 +02:00
res2 = cls._fields[field].get(ids, cls, field, values=res)
2009-02-02 13:08:25 +01:00
for record in res:
record[field] = res2[record['id']]
2010-03-11 16:42:50 +01:00
for key in func_fields:
field_list = func_fields[key]
2009-02-02 13:08:25 +01:00
field = field_list[0]
2010-03-11 16:42:50 +01:00
_, datetime_field = key
if datetime_field:
for record in res:
2010-08-19 22:01:12 +02:00
with Transaction().set_context(
_datetime=record[datetime_field]):
2012-09-24 22:16:53 +02:00
res2 = cls._fields[field].get([record['id']], cls,
2010-08-19 22:01:12 +02:00
field_list, values=[record])
for field in res2:
record[field] = res2[field][record['id']]
continue
2012-09-24 22:16:53 +02:00
res2 = cls._fields[field].get(ids, cls, field_list, values=res)
2009-02-02 13:08:25 +01:00
for field in res2:
for record in res:
record[field] = res2[field][record['id']]
to_del = set()
fields_related2values = {}
for field in fields_related.keys() + datetime_fields:
if field not in fields_names:
to_del.add(field)
2012-09-24 22:16:53 +02:00
if field not in cls._fields:
continue
if field not in fields_related.keys():
continue
fields_related2values.setdefault(field, {})
2012-09-24 22:16:53 +02:00
if cls._fields[field]._type in ('many2one', 'one2one'):
if hasattr(cls._fields[field], 'model_name'):
obj = pool.get(cls._fields[field].model_name)
2010-12-03 18:01:46 +01:00
else:
2012-09-24 22:16:53 +02:00
obj = cls._fields[field].get_target()
if hasattr(cls._fields[field], 'datetime_field') \
and cls._fields[field].datetime_field:
for record in res:
2012-12-23 22:56:09 +01:00
if record[field] is None:
2009-10-02 13:12:26 +02:00
continue
2012-04-01 23:08:15 +02:00
with Transaction().set_context(_datetime=record[
2012-09-24 22:16:53 +02:00
cls._fields[field].datetime_field]):
record2, = obj.read([record[field]],
2010-08-19 22:01:12 +02:00
fields_related[field])
record_id = record2['id']
del record2['id']
fields_related2values[field].setdefault(record_id, {})
2010-02-18 18:50:35 +01:00
fields_related2values[
field][record_id][record['id']] = record2
else:
2010-08-19 22:01:12 +02:00
for record in obj.read([x[field] for x in res
2013-02-27 22:50:31 +01:00
if x[field]], fields_related[field]):
record_id = record['id']
del record['id']
fields_related2values[field].setdefault(record_id, {})
for record2 in res:
2012-04-01 23:08:15 +02:00
fields_related2values[
field][record_id][record2['id']] = record
2012-09-24 22:16:53 +02:00
elif cls._fields[field]._type == 'reference':
for record in res:
if not record[field]:
continue
model_name, record_id = record[field].split(',', 1)
if not model_name:
continue
record_id = int(record_id)
if record_id < 0:
continue
2011-07-03 13:20:58 +02:00
obj = pool.get(model_name)
2012-09-24 22:16:53 +02:00
record2, = obj.read([record_id], fields_related[field])
del record2['id']
2012-09-24 11:36:39 +02:00
fields_related2values[field][record[field]] = record2
if to_del or fields_related.keys() or datetime_fields:
for record in res:
for field in fields_related.keys():
2012-09-24 22:16:53 +02:00
if field not in cls._fields:
continue
for related in fields_related[field]:
2012-09-24 22:16:53 +02:00
if cls._fields[field]._type in (
2012-04-01 23:08:15 +02:00
'many2one', 'one2one'):
if record[field]:
2012-04-01 23:08:15 +02:00
record[field + '.' + related] = (
fields_related2values[field][
record[field]][record['id']][related])
else:
record[field + '.' + related] = False
2012-09-24 22:16:53 +02:00
elif cls._fields[field]._type == 'reference':
if record[field]:
model_name, record_id = record[field].split(
',', 1)
if not model_name:
continue
record_id = int(record_id)
if record_id < 0:
continue
record[field + '.' + related] = \
2013-02-27 22:50:31 +01:00
fields_related2values[field][
record[field]][related]
for field in to_del:
del record[field]
2009-02-02 13:08:25 +01:00
return res
2012-09-24 22:16:53 +02:00
@classmethod
def write(cls, records, values):
2010-08-19 22:01:12 +02:00
cursor = Transaction().cursor
2011-07-03 13:20:58 +02:00
pool = Pool()
2012-09-24 22:16:53 +02:00
Translation = pool.get('ir.translation')
2012-11-23 17:59:04 +01:00
Config = pool.get('ir.configuration')
2012-09-24 22:16:53 +02:00
ids = map(int, records)
# Call before cursor cache cleaning
2012-09-24 22:16:53 +02:00
trigger_eligibles = cls.trigger_write_get_eligibles(records)
2012-09-24 22:16:53 +02:00
super(ModelSQL, cls).write(records, values)
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
if not records:
2009-02-02 13:08:25 +01:00
return True
2012-09-24 22:16:53 +02:00
if cls.table_query():
2009-02-02 13:08:25 +01:00
return True
values = values.copy()
2012-09-24 22:16:53 +02:00
# _update_tree works if only one record has changed
update_tree = False
for k in cls._fields:
field = cls._fields[k]
if isinstance(field, fields.Many2One) \
and field.model_name == cls.__name__ \
and field.left and field.right:
update_tree = True
if update_tree and len(records) > 1:
for record in records:
cls.write([record], values)
return True
2009-02-02 13:08:25 +01:00
2010-08-19 22:01:12 +02:00
if Transaction().timestamp:
2009-02-02 13:08:25 +01:00
for i in range(0, len(ids), cursor.IN_MAX):
sub_ids = ids[i:i + cursor.IN_MAX]
clause = ('(id = %s AND '
2013-02-27 22:50:31 +01:00
'CAST(EXTRACT(EPOCH FROM '
'COALESCE(write_date, create_date)) AS ' +
FIELDS['numeric'].sql_type(cls.create_date)[1] +
') > %s)')
2009-02-02 13:08:25 +01:00
args = []
for i in sub_ids:
2012-09-24 22:16:53 +02:00
if Transaction().timestamp.get(
cls.__name__ + ',' + str(i)):
2009-02-02 13:08:25 +01:00
args.append(i)
2010-10-11 13:20:09 +02:00
args.append(Decimal(Transaction().timestamp[
2012-09-24 22:16:53 +02:00
cls.__name__ + ',' + str(i)]))
2009-02-02 13:08:25 +01:00
if args:
2013-02-27 22:50:31 +01:00
cursor.execute("SELECT id "
'FROM "' + cls._table + '" '
'WHERE ' + ' OR '.join(
(clause,) * (len(args) // 2)), args)
if cursor.fetchone():
2011-09-05 20:30:26 +02:00
raise ConcurrencyException(
'Records were modified in the meanwhile')
2009-02-02 13:08:25 +01:00
for i in ids:
2012-09-24 22:16:53 +02:00
if Transaction().timestamp.get(cls.__name__ + ',' + str(i)):
del Transaction().timestamp[cls.__name__ + ',' + str(i)]
2009-02-02 13:08:25 +01:00
# Clean values
for key in ('create_uid', 'create_date', 'write_uid', 'write_date',
'id'):
if key in values:
del values[key]
2009-02-02 13:08:25 +01:00
upd0 = []
upd1 = []
upd_todo = []
direct = []
for field in values:
2013-03-20 22:49:16 +01:00
if not hasattr(cls._fields[field], 'set'):
if ((not getattr(cls._fields[field], 'translate', False))
or (Transaction().language == Config.get_language())):
upd0.append(('"' + field + '"', '%s'))
upd1.append(FIELDS[cls._fields[field]._type]
.sql_format(values[field]))
direct.append(field)
2009-02-02 13:08:25 +01:00
else:
2013-03-20 22:49:16 +01:00
upd_todo.append(field)
2009-02-02 13:08:25 +01:00
upd0.append(('write_uid', '%s'))
upd0.append(('write_date', '%s'))
2010-08-19 22:01:12 +02:00
upd1.append(Transaction().user)
upd1.append(datetime.datetime.now())
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
domain1, domain2 = pool.get('ir.rule').domain_get(cls.__name__,
2010-08-19 22:01:12 +02:00
mode='write')
if domain1:
domain1 = ' AND (' + domain1 + ') '
for i in range(0, len(ids), cursor.IN_MAX):
sub_ids = ids[i:i + cursor.IN_MAX]
2009-09-08 13:03:57 +02:00
red_sql, red_ids = reduce_ids('id', sub_ids)
2009-02-02 13:08:25 +01:00
if domain1:
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT id FROM "' + cls._table + '" '
'WHERE ' + red_sql + ' ' + domain1,
red_ids + domain2)
else:
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT id FROM "' + cls._table + '" '
'WHERE ' + red_sql, red_ids)
rowcount = cursor.rowcount
if rowcount == -1 or rowcount is None:
rowcount = len(cursor.fetchall())
if not rowcount == len({}.fromkeys(sub_ids)):
if domain1:
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT id FROM "' + cls._table + '" '
'WHERE ' + red_sql, red_ids)
2009-07-08 14:47:33 +02:00
rowcount = cursor.rowcount
if rowcount == -1 or rowcount is None:
rowcount = len(cursor.fetchall())
if rowcount == len({}.fromkeys(sub_ids)):
2012-09-24 22:16:53 +02:00
cls.raise_user_error('access_error', cls.__name__)
cls.raise_user_error('write_error', cls.__name__)
try:
2012-09-24 22:16:53 +02:00
cursor.execute('UPDATE "' + cls._table + '" '
2012-04-01 23:08:15 +02:00
'SET ' + ','.join([x[0] + ' = ' + x[1] for x in upd0])
+ ' WHERE ' + red_sql, upd1 + red_ids)
except DatabaseIntegrityError, exception:
2010-08-19 22:01:12 +02:00
with contextlib.nested(Transaction().new_cursor(),
Transaction().set_user(0)):
for field_name in values:
2012-09-24 22:16:53 +02:00
if field_name not in cls._fields:
continue
2012-09-24 22:16:53 +02:00
field = cls._fields[field_name]
# Check required fields
if field.required and \
not hasattr(field, 'set') and \
2010-03-18 10:33:59 +01:00
not isinstance(field, (fields.Integer,
fields.Float)) and \
field_name not in ('create_uid',
'create_date'):
if not values[field_name]:
2012-09-24 22:16:53 +02:00
cls.raise_user_error('required_field',
error_args=cls._get_error_args(
2010-08-19 22:01:12 +02:00
field_name))
if isinstance(field, fields.Many2One) \
and values[field_name]:
2012-09-24 22:16:53 +02:00
Model = pool.get(field.model_name)
2010-08-19 22:01:12 +02:00
create_records = Transaction().create_records.get(
field.model_name, set())
delete_records = Transaction().delete_records.get(
field.model_name, set())
2012-09-24 22:16:53 +02:00
if not ((Model.search([
2012-04-01 23:08:15 +02:00
('id', '=',
values[field_name]),
], order=[])
or (values[field_name]
in create_records))
and (values[field_name]
not in delete_records)):
2012-09-24 22:16:53 +02:00
cls.raise_user_error('foreign_model_missing',
error_args=cls._get_error_args(
2012-04-01 23:08:15 +02:00
field_name))
2012-09-24 22:16:53 +02:00
for name, _, error in cls._sql_constraints:
if name in exception[0]:
2012-09-24 22:16:53 +02:00
cls.raise_user_error(error)
2013-03-04 21:30:17 +01:00
for name, error in cls._sql_error_messages.iteritems():
if name in exception[0]:
2012-09-24 22:16:53 +02:00
cls.raise_user_error(error)
raise
2009-02-02 13:08:25 +01:00
for field in direct:
2012-09-24 22:16:53 +02:00
if getattr(cls._fields[field], 'translate', False):
Translation.set_ids(
cls.__name__ + ',' + field, 'model',
2010-08-19 22:01:12 +02:00
Transaction().language, ids, values[field])
2009-02-02 13:08:25 +01:00
2010-03-11 16:42:50 +01:00
# call the 'set' method of fields
2009-02-02 13:08:25 +01:00
for field in upd_todo:
2012-09-24 22:16:53 +02:00
cls._fields[field].set(ids, cls, field, values[field])
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
if cls._history:
columns = ['"' + str(x) + '"' for x in cls._fields
if not hasattr(cls._fields[x], 'set')]
for obj_id in ids:
2013-02-27 22:50:31 +01:00
cursor.execute('INSERT INTO "' + cls._table + '__history" '
'(' + ','.join(columns) + ') '
'SELECT ' + ','.join(columns) + ' ' +
'FROM "' + cls._table + '" '
'WHERE id = %s', (obj_id,))
2012-09-24 22:16:53 +02:00
cls._validate(records)
2009-02-02 13:08:25 +01:00
# Check for Modified Preorder Tree Traversal
2012-09-24 22:16:53 +02:00
for k in cls._fields:
field = cls._fields[k]
2009-02-02 13:08:25 +01:00
if isinstance(field, fields.Many2One) \
2012-09-24 22:16:53 +02:00
and field.model_name == cls.__name__ \
2009-02-02 13:08:25 +01:00
and field.left and field.right:
if field.left in values or field.right in values:
2010-02-18 18:50:35 +01:00
raise Exception('ValidateError',
'You can not update fields: "%s", "%s"' %
(field.left, field.right))
2009-02-02 13:08:25 +01:00
if len(ids) == 1:
2012-09-24 22:16:53 +02:00
cls._update_tree(ids[0], k, field.left, field.right)
2009-02-02 13:08:25 +01:00
else:
2010-08-19 22:01:12 +02:00
with Transaction().set_user(0):
2012-09-24 22:16:53 +02:00
cls._rebuild_tree(k, False, 0)
2012-09-24 22:16:53 +02:00
cls.trigger_write(trigger_eligibles)
2009-02-02 13:08:25 +01:00
return True
2012-09-24 22:16:53 +02:00
@classmethod
def delete(cls, records):
2010-08-19 22:01:12 +02:00
cursor = Transaction().cursor
2011-07-03 13:20:58 +02:00
pool = Pool()
2012-11-22 22:22:13 +01:00
Translation = pool.get('ir.translation')
2012-09-24 22:16:53 +02:00
ids = map(int, records)
2009-02-02 13:08:25 +01:00
if not ids:
return True
2012-09-24 22:16:53 +02:00
if cls.table_query():
2009-02-02 13:08:25 +01:00
return True
2012-09-24 22:16:53 +02:00
if Transaction().delete and Transaction().delete.get(cls.__name__):
ids = ids[:]
2012-09-24 22:16:53 +02:00
for del_id in Transaction().delete[cls.__name__]:
for i in range(ids.count(del_id)):
ids.remove(del_id)
2010-08-19 22:01:12 +02:00
if Transaction().timestamp:
2009-02-02 13:08:25 +01:00
for i in range(0, len(ids), cursor.IN_MAX):
sub_ids = ids[i:i + cursor.IN_MAX]
clause = ('(id = %s AND '
2013-02-27 22:50:31 +01:00
'CAST(EXTRACT(EPOCH FROM '
'COALESCE(write_date, create_date)) AS ' +
FIELDS['numeric'].sql_type(cls.create_date)[1] +
') > %s)')
2009-02-02 13:08:25 +01:00
args = []
for i in sub_ids:
2012-09-24 22:16:53 +02:00
if Transaction().timestamp.get(
cls.__name__ + ',' + str(i)):
2009-02-02 13:08:25 +01:00
args.append(i)
2010-08-19 22:01:12 +02:00
args.append(Transaction().timestamp[
2012-09-24 22:16:53 +02:00
cls.__name__ + ',' + str(i)])
2009-02-02 13:08:25 +01:00
if args:
2012-04-01 23:08:15 +02:00
cursor.execute("SELECT id "
2012-09-24 22:16:53 +02:00
'FROM "' + cls._table + '" '
2012-04-01 23:08:15 +02:00
'WHERE ' + ' OR '.join(
(clause,) * (len(args) / 2)), args)
if cursor.fetchone():
2011-09-05 20:30:26 +02:00
raise ConcurrencyException(
'Records were modified in the meanwhile')
2009-02-02 13:08:25 +01:00
for i in ids:
2012-09-24 22:16:53 +02:00
if Transaction().timestamp.get(cls.__name__ + ',' + str(i)):
del Transaction().timestamp[cls.__name__ + ',' + str(i)]
2009-02-02 13:08:25 +01:00
tree_ids = {}
2012-09-24 22:16:53 +02:00
for k in cls._fields:
field = cls._fields[k]
2009-02-02 13:08:25 +01:00
if isinstance(field, fields.Many2One) \
2012-09-24 22:16:53 +02:00
and field.model_name == cls.__name__ \
2009-02-02 13:08:25 +01:00
and field.left and field.right:
2009-09-08 13:03:57 +02:00
red_sql, red_ids = reduce_ids('"' + k + '"', ids)
2012-09-24 22:16:53 +02:00
cursor.execute('SELECT id FROM "' + cls._table + '" '
2012-04-01 23:08:15 +02:00
'WHERE ' + red_sql, red_ids)
2009-02-02 13:08:25 +01:00
tree_ids[k] = [x[0] for x in cursor.fetchall()]
foreign_keys_tocheck = []
foreign_keys_toupdate = []
foreign_keys_todelete = []
2011-07-03 13:20:58 +02:00
for _, model in pool.iterobject():
2009-06-12 18:42:24 +02:00
if hasattr(model, 'table_query') \
2010-08-19 22:01:12 +02:00
and model.table_query():
2009-06-12 18:42:24 +02:00
continue
2012-09-24 22:16:53 +02:00
if not issubclass(model, ModelStorage):
continue
2012-09-24 22:16:53 +02:00
for field_name, field in model._fields.iteritems():
if isinstance(field, fields.Many2One) \
2012-09-24 22:16:53 +02:00
and field.model_name == cls.__name__:
if field.ondelete == 'CASCADE':
foreign_keys_todelete.append((model, field_name))
elif field.ondelete == 'SET NULL':
if field.required:
foreign_keys_tocheck.append((model, field_name))
else:
foreign_keys_toupdate.append((model, field_name))
else:
foreign_keys_tocheck.append((model, field_name))
2012-09-24 22:16:53 +02:00
Transaction().delete.setdefault(cls.__name__, set()).update(ids)
2012-09-24 22:16:53 +02:00
domain1, domain2 = pool.get('ir.rule').domain_get(cls.__name__,
2010-08-19 22:01:12 +02:00
mode='delete')
2009-02-02 13:08:25 +01:00
if domain1:
domain1 = ' AND (' + domain1 + ') '
2009-02-02 13:08:25 +01:00
for i in range(0, len(ids), cursor.IN_MAX):
sub_ids = ids[i:i + cursor.IN_MAX]
2009-09-08 13:03:57 +02:00
red_sql, red_ids = reduce_ids('id', sub_ids)
2009-02-02 13:08:25 +01:00
if domain1:
2012-09-24 22:16:53 +02:00
cursor.execute('SELECT id FROM "' + cls._table + '" '
2012-04-01 23:08:15 +02:00
'WHERE ' + red_sql + ' ' + domain1,
red_ids + domain2)
rowcount = cursor.rowcount
if rowcount == -1 or rowcount is None:
rowcount = len(cursor.fetchall())
if not rowcount == len({}.fromkeys(sub_ids)):
cls.raise_user_error('access_error',
cls._get_name())
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
cls.trigger_delete(records)
for i in range(0, len(ids), cursor.IN_MAX):
sub_ids = ids[i:i + cursor.IN_MAX]
2012-09-24 22:16:53 +02:00
sub_records = records[i:i + cursor.IN_MAX]
2009-09-08 13:03:57 +02:00
red_sql, red_ids = reduce_ids('id', sub_ids)
2012-09-24 22:16:53 +02:00
Transaction().delete_records.setdefault(cls.__name__,
2010-08-19 22:01:12 +02:00
set()).update(sub_ids)
2012-09-24 22:16:53 +02:00
for Model, field_name in foreign_keys_toupdate:
if (not hasattr(Model, 'search')
or not hasattr(Model, 'write')):
continue
2012-04-01 23:08:15 +02:00
red_sql2, red_ids2 = reduce_ids('"' + field_name + '"',
sub_ids)
2012-09-24 22:16:53 +02:00
cursor.execute('SELECT id FROM "' + Model._table + '" '
2012-04-01 23:08:15 +02:00
'WHERE ' + red_sql2, red_ids2)
2012-09-24 22:16:53 +02:00
models = Model.browse([x[0] for x in cursor.fetchall()])
if models:
Model.write(models, {
2013-03-05 10:33:18 +01:00
field_name: None,
2012-09-24 22:16:53 +02:00
})
2012-09-24 22:16:53 +02:00
for Model, field_name in foreign_keys_todelete:
if (not hasattr(Model, 'search')
or not hasattr(Model, 'delete')):
continue
2012-04-01 23:08:15 +02:00
red_sql2, red_ids2 = reduce_ids('"' + field_name + '"',
sub_ids)
2012-09-24 22:16:53 +02:00
cursor.execute('SELECT id FROM "' + Model._table + '" '
2012-04-01 23:08:15 +02:00
'WHERE ' + red_sql2, red_ids2)
2012-09-24 22:16:53 +02:00
models = Model.browse([x[0] for x in cursor.fetchall()])
if models:
Model.delete(models)
2012-09-24 22:16:53 +02:00
for Model, field_name in foreign_keys_tocheck:
2010-08-19 22:01:12 +02:00
with Transaction().set_user(0):
2012-09-24 22:16:53 +02:00
if Model.search([
(field_name, 'in', sub_ids),
], order=[]):
2010-08-19 22:01:12 +02:00
error_args = []
2012-09-24 22:16:53 +02:00
error_args.append(cls._get_error_args('id')[1])
2010-08-19 22:01:12 +02:00
error_args.extend(list(
2012-09-24 22:16:53 +02:00
Model._get_error_args(field_name)))
cls.raise_user_error('foreign_model_exist',
error_args=tuple(error_args))
2012-09-24 22:16:53 +02:00
super(ModelSQL, cls).delete(sub_records)
try:
2012-09-24 22:16:53 +02:00
cursor.execute('DELETE FROM "' + cls._table + '" '
2012-04-01 23:08:15 +02:00
'WHERE ' + red_sql, red_ids)
2011-10-28 10:18:58 +02:00
except DatabaseIntegrityError, exception:
2010-08-19 22:01:12 +02:00
with Transaction().new_cursor():
2012-09-24 22:16:53 +02:00
for name, _, error in cls._sql_constraints:
if name in exception[0]:
2012-09-24 22:16:53 +02:00
cls.raise_user_error(error)
2013-03-12 11:47:14 +01:00
for name, error in cls._sql_error_messages.iteritems():
if name in exception[0]:
2012-09-24 22:16:53 +02:00
cls.raise_user_error(error)
raise
2009-02-02 13:08:25 +01:00
2012-11-22 22:22:13 +01:00
Translation.delete_ids(cls.__name__, 'model', ids)
2012-09-24 22:16:53 +02:00
if cls._history:
for obj_id in ids:
2013-02-27 22:50:31 +01:00
cursor.execute('INSERT INTO "' + cls._table + '__history" '
'(id, write_uid, write_date) VALUES (%s, %s, %s)',
(obj_id, Transaction().user, datetime.datetime.now()))
2009-02-02 13:08:25 +01:00
for k in tree_ids.keys():
2012-09-24 22:16:53 +02:00
field = cls._fields[k]
2009-02-02 13:08:25 +01:00
if len(tree_ids[k]) == 1:
2012-09-24 22:16:53 +02:00
cls._update_tree(tree_ids[k][0], k, field.left, field.right)
2009-02-02 13:08:25 +01:00
else:
2010-08-19 22:01:12 +02:00
with Transaction().set_user(0):
2012-09-24 22:16:53 +02:00
cls._rebuild_tree(k, False, 0)
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
@classmethod
def search(cls, domain, offset=0, limit=None, order=None, count=False,
2010-08-19 22:01:12 +02:00
query_string=False):
2011-07-03 13:20:58 +02:00
pool = Pool()
2012-09-24 22:16:53 +02:00
Rule = pool.get('ir.rule')
2010-08-19 22:01:12 +02:00
cursor = Transaction().cursor
2009-02-02 13:08:25 +01:00
# Get domain clauses
2012-09-24 22:16:53 +02:00
qu1, qu2, tables, tables_args = cls.search_domain(domain)
2009-02-02 13:08:25 +01:00
# Get order by
order_by = []
if order is None or order is False:
2012-09-24 22:16:53 +02:00
order = cls._order
for field, otype in order:
2009-02-02 13:08:25 +01:00
if otype.upper() not in ('DESC', 'ASC'):
raise Exception('Error', 'Wrong order type (%s)!' % otype)
2012-09-24 22:16:53 +02:00
order_by2, tables2, tables2_args = cls._order_calc(field, otype)
2009-02-02 13:08:25 +01:00
order_by += order_by2
for table in tables2:
if table not in tables:
tables.append(table)
if tables2_args.get(table):
tables_args.extend(tables2_args.get(table))
order_by = ','.join(order_by)
2009-09-07 15:18:17 +02:00
if type(limit) not in (float, int, long, type(None)):
raise Exception('Error', 'Wrong limit type (%s)!' % type(limit))
if type(offset) not in (float, int, long, type(None)):
raise Exception('Error', 'Wrong offset type (%s)!' % type(offset))
2009-02-02 13:08:25 +01:00
# construct a clause for the rules :
2012-09-24 22:16:53 +02:00
domain1, domain2 = Rule.domain_get(cls.__name__, mode='read')
2009-02-02 13:08:25 +01:00
if domain1:
if qu1:
qu1 += ' AND ' + domain1
else:
qu1 = domain1
qu2 += domain2
if count:
2009-09-07 15:18:17 +02:00
cursor.execute(cursor.limit_clause(
2012-09-24 22:16:53 +02:00
'SELECT COUNT("%s".id) FROM ' % cls._table +
2009-09-07 15:18:17 +02:00
' '.join(tables) + (qu1 and ' WHERE ' + qu1 or ''),
limit, offset), tables_args + qu2)
2009-02-02 13:08:25 +01:00
res = cursor.fetchall()
return res[0][0]
# execute the "main" query to fetch the ids we were searching for
2012-09-24 22:16:53 +02:00
select_fields = ['"' + cls._table + '".id AS id']
if cls._history and Transaction().context.get('_datetime') \
and not query_string:
2012-09-24 22:16:53 +02:00
select_fields += ['COALESCE("' + cls._table + '".write_date, "'
+ cls._table + '".create_date) AS _datetime']
if not query_string:
select_fields += [
2012-09-24 22:16:53 +02:00
'"' + cls._table + '"."' + name + '" AS "' + name + '"'
for name, field in cls._fields.iteritems()
2012-04-01 23:08:15 +02:00
if not hasattr(field, 'get')
and name != 'id'
and not getattr(field, 'translate', False)
and field.loading == 'eager']
2012-09-24 22:16:53 +02:00
if not cls.table_query():
select_fields += ['CAST(EXTRACT(EPOCH FROM '
2012-09-24 22:16:53 +02:00
'(COALESCE("' + cls._table + '".write_date, '
'"' + cls._table + '".create_date))) AS VARCHAR'
') AS _timestamp']
2009-09-07 15:18:17 +02:00
query_str = cursor.limit_clause(
2013-02-27 22:50:31 +01:00
'SELECT ' + ','.join(select_fields) + ' FROM ' +
' '.join(tables) + (qu1 and ' WHERE ' + qu1 or '') +
(order_by and ' ORDER BY ' + order_by or ''), limit, offset)
2009-02-02 13:08:25 +01:00
if query_string:
return (query_str, tables_args + qu2)
2010-09-02 17:59:33 +02:00
cursor.execute(query_str, tables_args + qu2)
2012-09-24 22:16:53 +02:00
rows = cursor.dictfetchmany(cursor.IN_MAX)
cache = cursor.get_cache(Transaction().context)
if cls.__name__ not in cache:
cache[cls.__name__] = LRUDict(RECORD_CACHE_SIZE)
2012-09-24 22:16:53 +02:00
delete_records = Transaction().delete_records.setdefault(cls.__name__,
2010-08-19 22:01:12 +02:00
set())
keys = None
2012-09-24 22:16:53 +02:00
for data in islice(rows, 0, cache.size_limit):
if data['id'] in delete_records:
continue
if keys is None:
keys = data.keys()
for k in keys[:]:
if k in ('_timestamp', '_datetime'):
keys.remove(k)
continue
2012-09-24 22:16:53 +02:00
field = cls._fields[k]
if not getattr(field, 'datetime_field', None):
keys.remove(k)
continue
for k in keys:
del data[k]
2012-09-24 22:16:53 +02:00
cache[cls.__name__].setdefault(data['id'], {}).update(data)
2012-09-24 22:16:53 +02:00
if len(rows) >= cursor.IN_MAX:
select_fields2 = [select_fields[0]]
2012-09-24 22:16:53 +02:00
if (cls._history
2010-08-19 22:01:12 +02:00
and Transaction().context.get('_datetime')
and not query_string):
select_fields2 += [select_fields[1]]
cursor.execute(
2013-02-27 22:50:31 +01:00
'SELECT * FROM (' +
cursor.limit_clause(
'SELECT ' + ','.join(select_fields2) + ' FROM ' +
' '.join(tables) + (qu1 and ' WHERE ' + qu1 or '') +
(order_by and ' ORDER BY ' + order_by or ''),
limit, offset) + ') AS "' + cls._table + '"',
tables_args + qu2)
2012-09-24 22:16:53 +02:00
rows = cursor.dictfetchall()
2012-09-24 22:16:53 +02:00
if cls._history and Transaction().context.get('_datetime'):
res = []
ids_date = {}
2012-09-24 22:16:53 +02:00
for data in rows:
if data['id'] in ids_date:
if data['_datetime'] <= ids_date[data['id']]:
continue
if data['id'] in res:
res.remove(data['id'])
res.append(data['id'])
ids_date[data['id']] = data['_datetime']
2012-03-04 16:07:16 +01:00
to_delete = set()
for i in range(0, len(res), cursor.IN_MAX):
sub_ids = res[i:i + cursor.IN_MAX]
reduced_sql, reduced_ids = reduce_ids('id', sub_ids)
cursor.execute(('SELECT id, write_date '
'FROM "%s__history" WHERE %s'
'AND (write_date IS NOT NULL AND create_date IS NULL)'
2012-09-24 22:16:53 +02:00
) % (cls._table, reduced_sql),
2012-03-04 16:07:16 +01:00
reduced_ids)
for deleted_id, delete_date in cursor.fetchall():
if ids_date[deleted_id] < delete_date:
to_delete.add(deleted_id)
2012-09-24 22:16:53 +02:00
return cls.browse(filter(lambda x: x not in to_delete, res))
2012-09-24 22:16:53 +02:00
return cls.browse([x['id'] for x in rows])
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
@classmethod
def search_domain(cls, domain, active_test=True):
2009-02-02 13:08:25 +01:00
'''
2012-09-24 22:16:53 +02:00
Return SQL clause, tables to use and arguments for the domain
Set active_test to add it.
2009-02-02 13:08:25 +01:00
'''
2012-09-24 22:16:53 +02:00
domain = cls._search_domain_active(domain, active_test=active_test)
2009-02-02 13:08:25 +01:00
table_query = ''
tables_args = []
2012-09-24 22:16:53 +02:00
if cls.table_query():
table_query, tables_args = cls.table_query()
2009-02-02 13:08:25 +01:00
table_query = '(' + table_query + ') AS '
2012-09-24 22:16:53 +02:00
if cls._history and Transaction().context.get('_datetime'):
table_query = '"' + cls._table + '__history" AS '
2012-09-24 22:16:53 +02:00
tables = [table_query + '"' + cls._table + '"']
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
qu1, qu2 = cls.__search_domain_oper(domain, tables, tables_args)
if cls._history and Transaction().context.get('_datetime'):
if qu1:
qu1 += ' AND'
2012-09-24 22:16:53 +02:00
qu1 += ' (COALESCE("' + cls._table + '".write_date, "' + \
2013-02-27 22:50:31 +01:00
cls._table + '".create_date) <= %s)'
2010-08-19 22:01:12 +02:00
qu2 += [Transaction().context['_datetime']]
2009-02-02 13:08:25 +01:00
return qu1, qu2, tables, tables_args
2012-09-24 22:16:53 +02:00
@classmethod
def __search_domain_oper(cls, domain, tables, tables_args):
2009-02-02 13:08:25 +01:00
operator = 'AND'
if len(domain) and isinstance(domain[0], basestring):
if domain[0] not in ('AND', 'OR'):
2012-04-01 23:08:15 +02:00
raise Exception('ValidateError', 'Operator "%s" not supported'
% domain[0])
2009-02-02 13:08:25 +01:00
operator = domain[0]
domain = domain[1:]
tuple_args = []
list_args = []
for arg in domain:
#add test for xmlrpc that doesn't handle tuple
2013-02-27 22:50:31 +01:00
if (isinstance(arg, tuple)
or (isinstance(arg, list) and len(arg) > 2
and arg[1] in OPERATORS)):
2009-02-02 13:08:25 +01:00
tuple_args.append(tuple(arg))
elif isinstance(arg, list):
list_args.append(arg)
2012-09-24 22:16:53 +02:00
qu1, qu2 = cls.__search_domain_calc(tuple_args, tables, tables_args)
2009-02-02 13:08:25 +01:00
if len(qu1):
qu1 = (' ' + operator + ' ').join(qu1)
else:
qu1 = ''
for domain2 in list_args:
2012-09-24 22:16:53 +02:00
qu1b, qu2b = cls.__search_domain_oper(domain2, tables,
2010-08-19 22:01:12 +02:00
tables_args)
2009-02-02 13:08:25 +01:00
if not qu1b:
qu1b = '%s'
qu2b = [True]
2009-02-02 13:08:25 +01:00
if qu1 and qu1b:
qu1 += ' ' + operator + ' ' + qu1b
elif qu1b:
qu1 = qu1b
qu2 += qu2b
if qu1:
qu1 = '(' + qu1 + ')'
return qu1, qu2
2012-09-24 22:16:53 +02:00
@classmethod
def __search_domain_calc(cls, domain, tables, tables_args):
2011-07-03 13:20:58 +02:00
pool = Pool()
2009-02-02 13:08:25 +01:00
domain = domain[:]
2010-08-19 22:01:12 +02:00
cursor = Transaction().cursor
2009-02-02 13:08:25 +01:00
for arg in domain:
if arg[1] not in OPERATORS:
2012-04-01 23:08:15 +02:00
raise Exception('ValidateError', 'Argument "%s" not supported'
% arg[1])
2009-02-02 13:08:25 +01:00
i = 0
joins = []
while i < len(domain):
fargs = domain[i][0].split('.', 1)
2013-03-20 22:49:16 +01:00
field = getattr(cls, fargs[0])
table = cls
2009-02-02 13:08:25 +01:00
if len(fargs) > 1:
if field._type in ('many2one', 'reference'):
if field._type == 'many2one':
Target = pool.get(field.model_name)
m2o_search = [(fargs[1],) + tuple(domain[i][1:])]
else:
Target = pool.get(domain[i][3])
m2o_search = [(fargs[1],) + tuple(domain[i][1:3])
+ tuple(domain[i][4:])]
2013-03-20 22:49:16 +01:00
if 'active' in Target._fields:
m2o_search += [('active', 'in', (True, False))]
if hasattr(field, 'search'):
domain.extend([(fargs[0], 'in',
2012-09-24 22:16:53 +02:00
map(int, Target.search(m2o_search,
order=[])))])
domain.pop(i)
else:
in_query = Target.search(m2o_search, order=[],
query_string=True)
if field._type == 'many2one':
domain[i] = (fargs[0], 'inselect', in_query, table)
else:
sql_type = FIELDS[
cls.id._type].sql_type(cls.id)[0]
query = ('SELECT id FROM "' + cls._table + '" '
2013-04-14 23:17:55 +02:00
'WHERE CAST(SUBSTR("' + fargs[0] + '", '
'POSITION(\',\' IN "' + fargs[0] + '")'
+ '+ 1) '
'AS ' + sql_type + ') '
'IN (' + in_query[0] + ') '
'AND "' + fargs[0] + '" ilike %s')
domain[i] = ('id', 'inselect',
(query, in_query[1] + [domain[i][3] + ',%']))
2010-12-03 18:01:46 +01:00
i += 1
continue
elif field._type in ('one2one', 'many2many', 'one2many'):
2010-12-03 18:01:46 +01:00
if hasattr(field, 'model_name'):
2012-09-24 22:16:53 +02:00
Target = pool.get(field.model_name)
2010-12-03 18:01:46 +01:00
else:
2012-09-24 22:16:53 +02:00
Target = field.get_target()
if hasattr(field, 'relation_name'):
2012-09-24 22:16:53 +02:00
Relation = pool.get(field.relation_name)
origin, target = field.origin, field.target
else:
2012-09-24 22:16:53 +02:00
Relation = Target
origin, target = field.field, 'id'
2013-03-20 22:49:16 +01:00
rev_field = Relation._fields[origin]
if rev_field._type == 'reference':
sql_type = FIELDS[
2012-09-24 22:16:53 +02:00
cls.id._type].sql_type(cls.id)[0]
where = ' AND "' + origin + '" LIKE %s'
where_args = [cls.__name__ + ',%']
2013-04-14 23:17:55 +02:00
origin = ('CAST(SUBSTR("%s", '
'POSITION(\',\' IN "%s") + 1) AS %s)'
% (origin, origin, sql_type))
else:
origin = '"%s"' % origin
where = ''
where_args = []
2010-12-03 18:01:46 +01:00
if hasattr(field, 'search'):
2012-09-24 22:16:53 +02:00
domain.extend([(fargs[0], 'in',
map(int, Target.search([
(fargs[1], domain[i][1],
domain[i][2]),
], order=[])))])
2010-12-03 18:01:46 +01:00
domain.pop(i)
else:
2012-09-24 22:16:53 +02:00
query1, query2 = Target.search([
2010-12-03 18:01:46 +01:00
(fargs[1], domain[i][1], domain[i][2]),
], order=[], query_string=True)
query1 = ('SELECT %s FROM "%s" WHERE "%s" IN (%s)' %
2012-09-24 22:16:53 +02:00
(origin, Relation._table, target, query1))
query1 += where
query2 += where_args
2010-12-03 18:01:46 +01:00
domain[i] = ('id', 'inselect', (query1, query2))
i += 1
2009-02-02 13:08:25 +01:00
continue
else:
2013-02-27 22:50:31 +01:00
raise Exception('ValidateError',
'Clause on field "%s" doesn\'t work on "%s"'
% (domain[i][0], cls.__name__))
2009-02-03 18:58:25 +01:00
if hasattr(field, 'search'):
clause = domain.pop(i)
2010-08-19 22:01:12 +02:00
domain.extend(field.search(table, clause[0], clause))
2009-02-02 13:08:25 +01:00
elif field._type == 'one2many':
2012-09-24 22:16:53 +02:00
Field = pool.get(field.model_name)
2009-02-02 13:08:25 +01:00
table_query = ''
table_args = []
2012-09-24 22:16:53 +02:00
if Field.table_query():
table_query, table_args = Field.table_query()
2009-02-02 13:08:25 +01:00
table_query = '(' + table_query + ') AS '
2013-03-20 22:49:16 +01:00
rev_field = Field._fields[field.field]
if rev_field._type == 'reference':
2012-09-24 22:16:53 +02:00
sql_type = FIELDS[cls.id._type].sql_type(cls.id)[0]
2013-04-14 23:17:55 +02:00
select = ('CAST(SUBSTR("%s", '
'POSITION(\',\' IN "%s") + 1) AS %s)'
% (field.field, field.field, sql_type))
where = ' AND "' + field.field + '" LIKE %s'
where_args = [cls.__name__ + ',%']
else:
select = '"' + field.field + '"'
where = ''
where_args = []
2009-02-02 13:08:25 +01:00
if isinstance(domain[i][2], bool) or domain[i][2] is None:
2013-02-27 22:50:31 +01:00
query1 = ('SELECT ' + select + ' '
'FROM ' + table_query + '"' + Field._table + '" '
'WHERE "' + field.field + '" IS NOT NULL' + where)
query2 = table_args + where_args
2009-02-02 13:08:25 +01:00
clause = 'inselect'
if not domain[i][2]:
2009-02-02 13:08:25 +01:00
clause = 'notinselect'
domain[i] = ('id', clause, (query1, query2))
else:
if isinstance(domain[i][2], basestring):
target_field = 'rec_name'
2009-02-02 13:08:25 +01:00
else:
target_field = 'id'
2012-09-24 22:16:53 +02:00
query1, query2 = Field.search([
(target_field, domain[i][1], domain[i][2]),
], order=[], query_string=True)
query1 = ('SELECT ' + select + ' '
'FROM ' + table_query +
2012-09-24 22:16:53 +02:00
'"' + Field._table + '" '
'WHERE id IN (' + query1 + ')' + where)
query2 = table_args + query2 + where_args
domain[i] = ('id', 'inselect', (query1, query2))
2009-02-02 13:08:25 +01:00
i += 1
2010-12-03 18:01:46 +01:00
elif field._type in ('many2many', 'one2one'):
2009-02-02 13:08:25 +01:00
# XXX must find a solution for long id list
if hasattr(field, 'model_name'):
2012-09-24 22:16:53 +02:00
Target = pool.get(field.model_name)
else:
2012-09-24 22:16:53 +02:00
Target = field.get_target()
2009-02-02 13:08:25 +01:00
if domain[i][1] in ('child_of', 'not child_of'):
if isinstance(domain[i][2], basestring):
2012-09-24 22:16:53 +02:00
ids2 = map(int, Target.search([
('rec_name', 'ilike', domain[i][2]),
], order=[]))
2013-05-04 11:44:15 +02:00
elif not isinstance(domain[i][2], list):
2009-02-02 13:08:25 +01:00
ids2 = [domain[i][2]]
else:
ids2 = domain[i][2]
def _rec_get(ids, table, parent):
if not ids:
return []
2012-09-24 22:16:53 +02:00
ids2 = map(int, table.search([
(parent, 'in', ids),
(parent, '!=', None),
], order=[]))
2009-02-02 13:08:25 +01:00
return ids + _rec_get(ids2, table, parent)
2012-09-24 22:16:53 +02:00
if Target.__name__ != table.__name__:
2009-02-02 13:08:25 +01:00
if len(domain[i]) != 4:
2012-04-01 23:08:15 +02:00
raise Exception('Error', 'Programming error: '
'child_of on field "%s" is not allowed!'
% domain[i][0])
2012-09-24 22:16:53 +02:00
ids2 = map(int, Target.search([
(domain[i][3], 'child_of', ids2),
], order=[]))
Relation = pool.get(field.relation_name)
2009-09-08 13:03:57 +02:00
red_sql, red_ids = reduce_ids('"' + field.target + '"',
ids2)
2013-02-27 22:50:31 +01:00
query1 = ('SELECT "' + field.origin + '" '
'FROM "' + Relation._table + '" '
'WHERE ' + red_sql + ' '
'AND "' + field.origin + '" IS NOT NULL')
2009-09-08 13:03:57 +02:00
query2 = red_ids
2009-02-02 13:08:25 +01:00
if domain[i][1] == 'child_of':
domain[i] = ('id', 'inselect', (query1, query2))
else:
domain[i] = ('id', 'notinselect', (query1, query2))
else:
if domain[i][1] == 'child_of':
domain[i] = ('id', 'in', ids2 + _rec_get(ids2,
table, domain[i][0]))
else:
domain[i] = ('id', 'not in', ids2 + _rec_get(ids2,
table, domain[i][0]))
else:
2012-09-24 22:16:53 +02:00
Relation = pool.get(field.relation_name)
table_query = ''
table_args = []
2012-09-24 22:16:53 +02:00
if Relation.table_query():
table_query, table_args = Relation.table_query()
table_query = '(' + table_query + ') AS '
2013-03-20 22:49:16 +01:00
origin_field = Relation._fields[field.origin]
if origin_field._type == 'reference':
2012-09-24 22:16:53 +02:00
sql_type = FIELDS[cls.id._type].sql_type(cls.id)[0]
2013-04-14 23:17:55 +02:00
select = ('CAST(SUBSTR("%s", '
'POSITION(\',\' IN "%s") + 1) AS %s)'
% (field.origin, field.origin, sql_type))
where = ' AND "' + field.origin + '" LIKE %s'
where_args = [cls.__name__ + ',%']
else:
select = '"' + field.origin + '"'
where = ''
where_args = []
2012-05-05 09:32:24 +02:00
if isinstance(domain[i][2], bool) or domain[i][2] is None:
2013-02-27 22:50:31 +01:00
query1 = ('SELECT ' + select + ' '
'FROM ' + table_query + ' '
'"' + Relation._table + '" '
'WHERE "' + field.origin + '" IS NOT NULL' + where)
query2 = table_args + where_args
2009-02-02 13:08:25 +01:00
clause = 'inselect'
if not domain[i][2]:
2009-02-02 13:08:25 +01:00
clause = 'notinselect'
domain[i] = ('id', clause, (query1, query2))
else:
if isinstance(domain[i][2], basestring):
target_field = 'rec_name'
else:
target_field = 'id'
2012-09-24 22:16:53 +02:00
query1, query2 = Target.search([
(target_field, domain[i][1], domain[i][2]),
], order=[], query_string=True)
query1 = ('SELECT ' + select + ' '
'FROM ' + table_query +
2012-09-24 22:16:53 +02:00
'"' + Relation._table + '" '
'WHERE "' + field.target + '" IN (' + query1 + ')'
+ where)
query2 = table_args + query2 + where_args
2009-02-02 13:08:25 +01:00
domain[i] = ('id', 'inselect', (query1, query2))
i += 1
elif field._type == 'many2one':
# XXX must find a solution for long id list
if domain[i][1] in ('child_of', 'not child_of'):
if isinstance(domain[i][2], basestring):
2012-09-24 22:16:53 +02:00
Field = pool.get(field.model_name)
ids2 = map(int, Field.search([
('rec_name', 'like', domain[i][2]),
], order=[]))
2013-05-04 11:44:15 +02:00
elif not isinstance(domain[i][2], list):
2009-02-02 13:08:25 +01:00
ids2 = [domain[i][2]]
else:
ids2 = domain[i][2]
def _rec_get(ids, table, parent):
if not ids:
return []
2012-09-24 22:16:53 +02:00
ids2 = map(int, table.search([
(parent, 'in', ids),
(parent, '!=', None),
]))
2009-02-02 13:08:25 +01:00
return ids + _rec_get(ids2, table, parent)
2012-09-24 22:16:53 +02:00
if field.model_name != table.__name__:
2009-02-02 13:08:25 +01:00
if len(domain[i]) != 4:
2012-04-01 23:08:15 +02:00
raise Exception('Error', 'Programming error: '
'child_of on field "%s" is not allowed!'
% domain[i][0])
2012-09-24 22:16:53 +02:00
ids2 = map(int, pool.get(field.model_name).search([
(domain[i][3], 'child_of', ids2),
], order=[]))
2009-02-02 13:08:25 +01:00
if domain[i][1] == 'child_of':
domain[i] = (domain[i][0], 'in', ids2, table)
else:
domain[i] = (domain[i][0], 'not in', ids2, table)
else:
if field.left and field.right and ids2:
2009-09-08 13:03:57 +02:00
red_sql, red_ids = reduce_ids('id', ids2)
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT "' + field.left + '", '
'"' + field.right + '" ' +
'FROM "' + cls._table + '" ' +
'WHERE ' + red_sql, red_ids)
clause = '(1=0) '
2009-02-02 13:08:25 +01:00
for left, right in cursor.fetchall():
clause += 'OR '
2013-02-27 22:50:31 +01:00
clause += ('( "' + field.left + '" >= ' +
str(left) + ' ' +
'AND "' + field.right + '" <= ' +
str(right) + ')')
2009-02-02 13:08:25 +01:00
2013-02-27 22:50:31 +01:00
query = ('SELECT id FROM "' + cls._table + '" ' +
'WHERE ' + clause)
2009-02-02 13:08:25 +01:00
if domain[i][1] == 'child_of':
domain[i] = ('id', 'inselect', (query, []))
else:
domain[i] = ('id', 'notinselect', (query, []))
else:
if domain[i][1] == 'child_of':
domain[i] = ('id', 'in', ids2 + _rec_get(
ids2, table, domain[i][0]), table)
else:
domain[i] = ('id', 'not in', ids2 + _rec_get(
ids2, table, domain[i][0]), table)
else:
if isinstance(domain[i][2], basestring):
2012-09-24 22:16:53 +02:00
Field = pool.get(field.model_name)
m2o_search = [('rec_name', domain[i][1], domain[i][2])]
2013-03-20 22:49:16 +01:00
if 'active' in Field._fields:
m2o_search += [('active', 'in', (True, False))]
2012-09-24 22:16:53 +02:00
res_ids = map(int, Field.search(m2o_search, order=[]))
domain[i] = (domain[i][0], 'in', res_ids, table)
2009-02-02 13:08:25 +01:00
else:
domain[i] += (table,)
i += 1
else:
if getattr(field, 'translate', False):
2012-09-24 22:16:53 +02:00
if cls.__name__ == 'ir.model':
2013-02-27 22:50:31 +01:00
table_join = ('LEFT JOIN "ir_translation" '
'ON (ir_translation.name = '
'ir_model.model||\',%s\' '
2013-04-17 17:44:34 +02:00
'AND ir_translation.res_id IS NULL '
2013-02-27 22:50:31 +01:00
'AND ir_translation.lang = %%s '
'AND ir_translation.type = \'model\' '
'AND ir_translation.fuzzy = %%s)'
% domain[i][0])
2012-09-24 22:16:53 +02:00
elif cls.__name__ == 'ir.model.field':
2009-02-02 13:08:25 +01:00
if domain[i][0] == 'field_description':
ttype = 'field'
else:
ttype = 'help'
2013-02-27 22:50:31 +01:00
table_join = ('LEFT JOIN "ir_model" '
'ON ir_model.id = ir_model_field.model '
'LEFT JOIN "ir_translation" '
'ON (ir_translation.name = '
'ir_model.model||\',\'||%s.name '
2013-04-17 17:44:34 +02:00
'AND ir_translation.res_id IS NULL '
2013-02-27 22:50:31 +01:00
'AND ir_translation.lang = %%s '
'AND ir_translation.type = \'%s\' '
'AND ir_translation.fuzzy = %%s)'
% (table._table, ttype))
2009-02-02 13:08:25 +01:00
else:
2013-02-27 22:50:31 +01:00
table_join = ('LEFT JOIN "ir_translation" '
'ON (ir_translation.res_id = %s.id '
'AND ir_translation.name = \'%s,%s\' '
'AND ir_translation.lang = %%s '
'AND ir_translation.type = \'model\' '
'AND ir_translation.fuzzy = %%s)'
% (table._table, table.__name__, domain[i][0]))
table_join_args = [Transaction().language, False]
2009-02-02 13:08:25 +01:00
table_query = ''
table_args = []
2010-08-19 22:01:12 +02:00
if table.table_query():
table_query, table_args = table.table_query()
2012-04-01 23:08:15 +02:00
table_query = '(' + table_query + ') AS '
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
Translation = pool.get('ir.translation')
2009-02-02 13:08:25 +01:00
2010-08-19 22:01:12 +02:00
qu1, qu2, tables, table_args = \
2013-02-27 22:50:31 +01:00
Translation.search_domain([
('value', domain[i][1], domain[i][2]),
2010-08-19 22:01:12 +02:00
])
qu1 = qu1.replace('"ir_translation"."value"',
2013-02-27 22:50:31 +01:00
'COALESCE(NULLIF("ir_translation"."value", \'\'), '
'"%s"."%s")' % (table._table, domain[i][0]))
query1 = ('SELECT "' + table._table + '".id '
'FROM ' + table_query + '"' + table._table + '" '
+ table_join + ' WHERE ' + qu1)
query2 = table_args + table_join_args + qu2
2009-02-02 13:08:25 +01:00
domain[i] = ('id', 'inselect', (query1, query2), table)
else:
domain[i] += (table,)
i += 1
domain.extend(joins)
qu1, qu2 = [], []
for arg in domain:
2013-03-20 22:49:16 +01:00
table = cls
if len(arg) > 3:
2009-02-02 13:08:25 +01:00
table = arg[3]
2013-03-20 22:49:16 +01:00
column = getattr(table, arg[0])
2009-02-02 13:08:25 +01:00
if arg[1] in ('inselect', 'notinselect'):
clause = 'IN'
if arg[1] == 'notinselect':
clause = 'NOT IN'
2010-02-18 18:50:35 +01:00
qu1.append('("%s"."%s" %s (%s))' % (table._table, arg[0],
clause, arg[2][0]))
2009-02-02 13:08:25 +01:00
qu2 += arg[2][1]
elif arg[1] in ('in', 'not in'):
if len(arg[2]) > 0:
todel = []
2012-05-16 15:48:00 +02:00
if column._type != 'boolean':
2009-05-13 19:16:48 +02:00
for xitem in range(len(arg[2])):
2012-04-12 17:51:50 +02:00
if (arg[2][xitem] is False
or arg[2][xitem] is None):
2009-05-13 19:16:48 +02:00
todel.append(xitem)
2009-02-02 13:08:25 +01:00
arg2 = arg[2][:]
for xitem in todel[::-1]:
del arg2[xitem]
2012-05-16 15:48:00 +02:00
arg2 = [FIELDS[column._type].sql_format(x)
for x in arg2]
2009-02-02 13:08:25 +01:00
if len(arg2):
if reduce(lambda x, y: (x
and isinstance(y, (int, long))
and not isinstance(y, bool)),
2009-09-08 13:03:57 +02:00
arg2, True):
2013-02-27 22:50:31 +01:00
red_sql, red_ids = reduce_ids('"%s"."%s"'
% (table._table, arg[0]), arg2)
2009-09-08 13:03:57 +02:00
if arg[1] == 'not in':
red_sql = '(NOT(' + red_sql + '))'
qu1.append(red_sql)
qu2 += red_ids
else:
2013-02-27 22:50:31 +01:00
qu1.append(('("%s"."%s" ' + arg[1] + ' (%s))')
% (table._table, arg[0], ','.join(
2009-09-08 13:03:57 +02:00
('%s',) * len(arg2))))
qu2 += arg2
2009-02-02 13:08:25 +01:00
if todel:
2012-05-16 15:48:00 +02:00
if column._type == 'boolean':
2009-02-02 13:08:25 +01:00
if arg[1] == 'in':
2013-02-27 22:50:31 +01:00
qu1[-1] = ('(' + qu1[-1] + ' OR '
'"%s"."%s" = %%s)'
% (table._table, arg[0]))
2009-09-08 13:03:57 +02:00
qu2.append(False)
2009-02-02 13:08:25 +01:00
else:
2013-02-27 22:50:31 +01:00
qu1[-1] = ('(' + qu1[-1] + ' AND '
'"%s"."%s" != %%s)'
% (table._table, arg[0]))
2009-09-08 13:03:57 +02:00
qu2.append(False)
2009-02-02 13:08:25 +01:00
else:
if arg[1] == 'in':
2013-02-27 22:50:31 +01:00
qu1[-1] = ('(' + qu1[-1] + ' OR '
'"%s"."%s" IS NULL)'
% (table._table, arg[0]))
2009-02-02 13:08:25 +01:00
else:
2013-02-27 22:50:31 +01:00
qu1[-1] = ('(' + qu1[-1] + ' AND '
'"%s"."%s" IS NOT NULL)'
% (table._table, arg[0]))
2009-02-02 13:08:25 +01:00
elif todel:
2012-05-16 15:48:00 +02:00
if column._type == 'boolean':
2009-02-02 13:08:25 +01:00
if arg[1] == 'in':
2013-02-27 22:50:31 +01:00
qu1.append('("%s"."%s" = %%s)'
% (table._table, arg[0]))
qu2.append(False)
2009-02-02 13:08:25 +01:00
else:
2013-02-27 22:50:31 +01:00
qu1.append('("%s"."%s" != %%s)'
% (table._table, arg[0]))
qu2.append(False)
2009-02-02 13:08:25 +01:00
else:
if arg[1] == 'in':
2013-02-27 22:50:31 +01:00
qu1.append('("%s"."%s" IS NULL)'
% (table._table, arg[0]))
2009-02-02 13:08:25 +01:00
else:
2013-02-27 22:50:31 +01:00
qu1.append('("%s"."%s" IS NOT NULL)'
% (table._table, arg[0]))
2009-02-02 13:08:25 +01:00
else:
if arg[1] == 'in':
qu1.append(' %s')
qu2.append(False)
2009-02-02 13:08:25 +01:00
else:
qu1.append(' %s')
qu2.append(True)
2009-02-02 13:08:25 +01:00
else:
if (arg[2] is False or arg[2] is None) and (arg[1] == '='):
2012-05-16 15:48:00 +02:00
if column._type == 'boolean':
qu1.append('(("%s"."%s" = %%s) OR ("%s"."%s" IS NULL))'
% (table._table, arg[0], table._table, arg[0]))
qu2.append(False)
2009-02-02 13:08:25 +01:00
else:
2013-02-27 22:50:31 +01:00
qu1.append('("%s"."%s" IS NULL)'
% (table._table, arg[0]))
elif (arg[2] is False or arg[2] is None) and (arg[1] == '!='):
if column._type == 'boolean':
qu1.append('(("%s"."%s" != %%s) '
'AND ("%s"."%s" IS NOT NULL))'
% (table._table, arg[0], table._table, arg[0]))
qu2.append(False)
else:
2013-02-27 22:50:31 +01:00
qu1.append('("%s"."%s" IS NOT NULL)'
% (table._table, arg[0]))
2009-02-02 13:08:25 +01:00
else:
if arg[0] == 'id':
2013-02-27 22:50:31 +01:00
qu1.append('("%s"."%s" %s %%s)'
% (table._table, arg[0], arg[1]))
qu2.append(FIELDS[column._type]
.sql_format(arg[2]))
2009-02-02 13:08:25 +01:00
else:
add_null = False
if arg[1] in ('like', 'ilike'):
2009-02-02 13:08:25 +01:00
if not arg[2]:
qu2.append('%')
add_null = True
else:
2012-03-05 11:45:51 +01:00
qu2.append(FIELDS[
2012-05-16 15:48:00 +02:00
column._type
2012-03-05 11:45:51 +01:00
].sql_format(arg[2]))
elif arg[1] in ('not like', 'not ilike'):
if not arg[2]:
qu2.append('')
else:
2012-03-05 11:45:51 +01:00
qu2.append(FIELDS[
2012-05-16 15:48:00 +02:00
column._type
2012-03-05 11:45:51 +01:00
].sql_format(arg[2]))
add_null = True
2009-02-02 13:08:25 +01:00
else:
2012-05-16 15:48:00 +02:00
qu2.append(FIELDS[
column._type
].sql_format(arg[2]))
qu1.append('("%s"."%s" %s %%s)' % (table._table,
arg[0], arg[1]))
2009-02-02 13:08:25 +01:00
if add_null:
2013-02-27 22:50:31 +01:00
qu1[-1] = ('(' + qu1[-1] + ' OR '
'"' + table._table + '"."' + arg[0] + '"'
' IS NULL)')
2009-02-02 13:08:25 +01:00
return qu1, qu2
2012-09-24 22:16:53 +02:00
@classmethod
def _order_calc(cls, field, otype):
2011-07-03 13:20:58 +02:00
pool = Pool()
2009-02-02 13:08:25 +01:00
order_by = []
tables = []
tables_args = {}
field_name = None
table_name = None
link_field = None
2012-09-24 22:16:53 +02:00
if field in cls._fields:
table_name = cls._table
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
if not hasattr(cls._fields[field], 'set'):
2009-02-02 13:08:25 +01:00
field_name = field
2012-09-24 22:16:53 +02:00
if cls._fields[field].order_field:
field_name = cls._fields[field].order_field
2009-02-02 13:08:25 +01:00
2012-09-24 22:16:53 +02:00
if isinstance(cls._fields[field], fields.Many2One):
obj = pool.get(cls._fields[field].model_name)
2009-02-02 13:08:25 +01:00
table_name = obj._table
link_field = field
field_name = None
2012-09-24 22:16:53 +02:00
if obj._rec_name in obj._fields:
2009-02-02 13:08:25 +01:00
field_name = obj._rec_name
2012-09-24 22:16:53 +02:00
if obj._order_name in obj._fields:
2009-02-02 13:08:25 +01:00
field_name = obj._order_name
if not field_name:
field_name = 'id'
order_by, tables, tables_args = obj._order_calc(field_name,
otype)
table_join = ('LEFT JOIN "' + table_name + '" AS '
'"' + table_name + '.' + link_field + '" ON '
'"%s.%s".id = "%s"."%s"'
% (table_name, link_field, cls._table, link_field))
for i in range(len(order_by)):
if table_name in order_by[i]:
order_by[i] = order_by[i].replace(table_name,
table_name + '.' + link_field)
for i in range(len(tables)):
if table_name in tables[i]:
args = tables_args.pop(tables[i], [])
tables[i] = tables[i].replace(table_name,
table_name + '.' + link_field)
tables_args[tables[i]] = args
if table_join not in tables:
tables.insert(0, table_join)
return order_by, tables, tables_args
2009-02-02 13:08:25 +01:00
2013-02-27 22:50:31 +01:00
if (field_name in cls._fields
and getattr(cls._fields[field_name], 'translate', False)):
translation_table = ('ir_translation_%s_%s'
% (table_name, field_name))
2012-09-24 22:16:53 +02:00
if cls.__name__ == 'ir.model':
2013-02-27 22:50:31 +01:00
table_join = ('LEFT JOIN "ir_translation" '
'AS "%s" ON '
'("%s".name = "ir_model".model||\',%s\' '
2013-04-17 17:44:34 +02:00
'AND "%s".res_id IS NULL '
2013-02-27 22:50:31 +01:00
'AND "%s".lang = %%s '
'AND "%s".type = \'model\' '
'AND "%s".fuzzy = %%s)'
% (translation_table, translation_table, field_name,
translation_table, translation_table,
translation_table, translation_table))
2012-09-24 22:16:53 +02:00
elif cls.__name__ == 'ir.model.field':
2009-02-02 13:08:25 +01:00
if field_name == 'field_description':
ttype = 'field'
else:
ttype = 'help'
2013-02-27 22:50:31 +01:00
table_join = ('LEFT JOIN "ir_model" ON '
'ir_model.id = ir_model_field.model')
2009-02-02 13:08:25 +01:00
if table_join not in tables:
tables.append(table_join)
2013-02-27 22:50:31 +01:00
table_join = ('LEFT JOIN "ir_translation" '
'AS "%s" ON '
'("%s".name = "ir_model".model||\',\'||%s.name '
2013-04-17 17:44:34 +02:00
'AND "%s".res_id IS NULL '
2013-02-27 22:50:31 +01:00
'AND "%s".lang = %%s '
'AND "%s".type = \'%s\' '
'AND "%s".fuzzy = %%s)'
% (translation_table, translation_table, table_name,
translation_table, translation_table,
translation_table, ttype, translation_table))
2009-02-02 13:08:25 +01:00
else:
2013-02-27 22:50:31 +01:00
table_join = ('LEFT JOIN "ir_translation" '
'AS "%s" ON '
'("%s".res_id = "%s".id '
'AND "%s".name = \'%s,%s\' '
'AND "%s".lang = %%s '
'AND "%s".type = \'model\' '
'AND "%s".fuzzy = %%s)'
% (translation_table, translation_table, table_name,
translation_table, cls.__name__, field_name,
translation_table, translation_table,
translation_table))
2009-02-02 13:08:25 +01:00
if table_join not in tables:
tables.append(table_join)
tables_args[table_join] = [Transaction().language, False]
2013-02-27 22:50:31 +01:00
order_by.append('COALESCE(NULLIF('
+ '"' + translation_table + '".value, \'\'), '
+ '"' + table_name + '".' + field_name + ') ' + otype)
2009-02-02 13:08:25 +01:00
return order_by, tables, tables_args
2013-02-27 22:50:31 +01:00
if (field_name in cls._fields
and cls._fields[field_name]._type == 'selection'
and cls._fields[field_name].order_field is None):
2012-09-24 22:16:53 +02:00
selections = cls.fields_get([field_name]
2013-02-27 22:50:31 +01:00
)[field_name]['selection']
2009-02-02 13:08:25 +01:00
if not isinstance(selections, (tuple, list)):
2012-09-24 22:16:53 +02:00
selections = getattr(cls,
cls._fields[field_name].selection)()
2009-02-02 13:08:25 +01:00
order = 'CASE ' + table_name + '.' + field_name
for selection in selections:
order += ' WHEN \'%s\' THEN \'%s\'' % selection
order += ' ELSE ' + table_name + '.' + field_name + ' END'
order_by.append(order + ' ' + otype)
return order_by, tables, tables_args
if field_name:
if '%(table)s' in field_name or '%(order)s' in field_name:
order_by.append(field_name % {
'table': '"%s"' % table_name,
2009-02-02 13:08:25 +01:00
'order': otype,
})
else:
2012-05-12 16:50:11 +02:00
order_by.append('"%s"."%s" %s'
% (table_name, field_name, otype))
2009-02-02 13:08:25 +01:00
return order_by, tables, tables_args
2011-06-15 11:39:20 +02:00
raise Exception('Error', 'Wrong field name (%s) for %s in order!' %
2012-09-24 22:16:53 +02:00
(field, cls.__name__))
2012-09-24 22:16:53 +02:00
@classmethod
def _rebuild_tree(cls, parent, parent_id, left):
'''
Rebuild left, right value for the tree.
'''
2010-08-19 22:01:12 +02:00
cursor = Transaction().cursor
right = left + 1
2010-08-19 22:01:12 +02:00
with Transaction().set_user(0):
2012-09-24 22:16:53 +02:00
childs = cls.search([
(parent, '=', parent_id),
])
2012-09-24 22:16:53 +02:00
for child in childs:
right = cls._rebuild_tree(parent, child.id, right)
2012-09-24 22:16:53 +02:00
field = cls._fields[parent]
if parent_id:
2013-02-27 22:50:31 +01:00
cursor.execute('UPDATE "' + cls._table + '" '
'SET "' + field.left + '" = %s, '
'"' + field.right + '" = %s '
'WHERE id = %s', (left, right, parent_id))
return right + 1
2012-09-24 22:16:53 +02:00
@classmethod
def _update_tree(cls, object_id, field_name, left, right):
'''
Update left, right values for the tree.
Remarks:
- the value (right - left - 1) / 2 will not give
the number of children node
- the order of the tree respects the default _order
'''
2010-08-19 22:01:12 +02:00
cursor = Transaction().cursor
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT "' + left + '", "' + right + '" '
'FROM "' + cls._table + '" '
'WHERE id = %s', (object_id,))
fetchone = cursor.fetchone()
if not fetchone:
return
old_left, old_right = fetchone
if old_left == old_right:
2013-02-27 22:50:31 +01:00
cursor.execute('UPDATE "' + cls._table + '" '
'SET "' + right + '" = "' + right + '" + 1 '
'WHERE id = %s', (object_id,))
old_right += 1
parent_right = 1
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT "' + field_name + '" '
'FROM "' + cls._table + '" '
'WHERE id = %s', (object_id,))
parent_id = cursor.fetchone()[0] or False
if parent_id:
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT "' + right + '" '
'FROM "' + cls._table + '" '
'WHERE id = %s', (parent_id,))
parent_right = cursor.fetchone()[0]
else:
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT MAX("' + right + '") '
'FROM "' + cls._table + '" '
'WHERE "' + field_name + '" IS NULL')
fetchone = cursor.fetchone()
if fetchone:
parent_right = fetchone[0] + 1
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT id FROM "' + cls._table + '" '
'WHERE "' + left + '" >= %s AND "' + right + '" <= %s',
(old_left, old_right))
child_ids = [x[0] for x in cursor.fetchall()]
if len(child_ids) > cursor.IN_MAX:
2010-08-19 22:01:12 +02:00
with Transaction().set_user(0):
2012-09-24 22:16:53 +02:00
return cls._rebuild_tree(field_name, False, 0)
2009-09-08 13:03:57 +02:00
red_child_sql, red_child_ids = reduce_ids('id', child_ids)
# ids for left update
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT id FROM "' + cls._table + '" '
'WHERE "' + left + '" >= %s '
'AND NOT ' + red_child_sql,
[parent_right] + red_child_ids)
left_ids = [x[0] for x in cursor.fetchall()]
# ids for right update
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT id FROM "' + cls._table + '" '
'WHERE "' + right + '" >= %s '
'AND NOT ' + red_child_sql,
[parent_right] + red_child_ids)
right_ids = [x[0] for x in cursor.fetchall()]
if left_ids:
for i in range(0, len(left_ids), cursor.IN_MAX):
sub_ids = left_ids[i:i + cursor.IN_MAX]
2009-09-08 13:03:57 +02:00
red_sub_sql, red_sub_ids = reduce_ids('id', sub_ids)
2013-02-27 22:50:31 +01:00
cursor.execute('UPDATE "' + cls._table + '" '
'SET "' + left + '" = "' + left + '" + '
+ str(old_right - old_left + 1) + ' '
'WHERE ' + red_sub_sql, red_sub_ids)
if right_ids:
for i in range(0, len(right_ids), cursor.IN_MAX):
sub_ids = right_ids[i:i + cursor.IN_MAX]
2009-09-08 13:03:57 +02:00
red_sub_sql, red_sub_ids = reduce_ids('id', sub_ids)
2013-02-27 22:50:31 +01:00
cursor.execute('UPDATE "' + cls._table + '" '
'SET "' + right + '" = "' + right + '" + '
+ str(old_right - old_left + 1) + ' '
'WHERE ' + red_sub_sql, red_sub_ids)
2013-02-27 22:50:31 +01:00
cursor.execute('UPDATE "' + cls._table + '" '
'SET "' + left + '" = "' + left + '" + '
+ str(parent_right - old_left) + ', '
'"' + right + '" = "' + right + '" + '
+ str(parent_right - old_left) + ' '
'WHERE ' + red_child_sql, red_child_ids)
2009-06-04 09:14:33 +02:00
# Use root user to by-pass rules
2010-08-19 22:01:12 +02:00
with contextlib.nested(Transaction().set_user(0),
Transaction().set_context(active_test=False)):
2012-09-24 22:16:53 +02:00
brother_ids = map(int, cls.search([
(field_name, '=', parent_id),
]))
if brother_ids[-1] != object_id:
next_id = brother_ids[brother_ids.index(object_id) + 1]
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT "' + left + '" '
'FROM "' + cls._table + '" '
'WHERE id = %s', (next_id,))
2010-02-18 18:50:35 +01:00
next_left = cursor.fetchone()[0]
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT "' + left + '" '
'FROM "' + cls._table + '" '
'WHERE id = %s', (object_id,))
2010-02-18 18:50:35 +01:00
current_left = cursor.fetchone()[0]
2013-02-27 22:50:31 +01:00
cursor.execute('UPDATE "' + cls._table + '" '
'SET "' + left + '" = "' + left + '" + '
+ str(old_right - old_left + 1) + ', '
'"' + right + '" = "' + right + '" + '
+ str(old_right - old_left + 1) + ' '
'WHERE "' + left + '" >= %s AND "' + right + '" <= %s',
(next_left, current_left))
2013-02-27 22:50:31 +01:00
cursor.execute('UPDATE "' + cls._table + '" '
'SET "' + left + '" = "' + left + '" - '
+ str(current_left - next_left) + ', '
'"' + right + '" = "' + right + '" - '
+ str(current_left - next_left) + ' '
'WHERE ' + red_child_sql, red_child_ids)
2012-09-24 22:16:53 +02:00
@classmethod
def validate(cls, records):
super(ModelSQL, cls).validate(records)
2010-08-19 22:01:12 +02:00
cursor = Transaction().cursor
if cursor.has_constraint():
return
# Works only for a single transaction
2012-09-24 22:16:53 +02:00
ids = map(int, records)
for _, sql, error in cls._sql_constraints:
2010-02-18 18:50:35 +01:00
match = _RE_UNIQUE.match(sql)
if match:
sql = match.group(1)
columns = sql.split(',')
2013-02-27 22:50:31 +01:00
sql_clause = ' AND '.join('%s = %%s'
% i for i in columns)
sql_clause = '(id != %s AND ' + sql_clause + ')'
in_max = cursor.IN_MAX / (len(columns) + 1)
for i in range(0, len(ids), in_max):
sub_ids = ids[i:i + in_max]
2009-09-08 13:03:57 +02:00
red_sql, red_ids = reduce_ids('id', sub_ids)
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT id,' + sql + ' '
'FROM "' + cls._table + '" '
'WHERE ' + red_sql, red_ids)
fetchall = cursor.fetchall()
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT id '
'FROM "' + cls._table + '" '
'WHERE ' +
' OR '.join((sql_clause,) * len(fetchall)),
reduce(lambda x, y: x + list(y), fetchall, []))
if cursor.fetchone():
2012-09-24 22:16:53 +02:00
cls.raise_user_error(error)
continue
2010-02-18 18:50:35 +01:00
match = _RE_CHECK.match(sql)
if match:
sql = match.group(1)
for i in range(0, len(ids), cursor.IN_MAX):
sub_ids = ids[i:i + cursor.IN_MAX]
2009-09-08 13:03:57 +02:00
red_sql, red_ids = reduce_ids('id', sub_ids)
2013-02-27 22:50:31 +01:00
cursor.execute('SELECT id '
'FROM "' + cls._table + '" '
'WHERE NOT (' + sql + ') '
'AND ' + red_sql, red_ids)
if cursor.fetchone():
2012-09-24 22:16:53 +02:00
cls.raise_user_error(error)
continue