Files
tryton/trytond/ir/sequence.py
T

388 lines
13 KiB
Python
Raw Normal View History

2014-12-02 12:54:01 +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.
2008-05-19 10:43:59 +02:00
from string import Template
2010-09-02 17:31:51 +02:00
import time
2013-01-06 22:18:13 +01:00
from itertools import izip
2013-09-06 22:32:37 +02:00
from sql import Flavor
from ..model import ModelView, ModelSQL, fields, Check
2011-12-14 17:00:13 +01:00
from ..tools import datetime_strftime
from ..pyson import Eval, And
2011-12-14 17:00:13 +01:00
from ..transaction import Transaction
from ..pool import Pool
2013-09-06 22:32:37 +02:00
from .. import backend
2012-09-24 22:16:53 +02:00
__all__ = [
'SequenceType', 'Sequence', 'SequenceStrict',
]
sql_sequence = backend.name() == 'postgresql'
2007-12-10 01:04:13 +01:00
class SequenceType(ModelSQL, ModelView):
2007-12-10 01:04:13 +01:00
"Sequence type"
2012-09-24 22:16:53 +02:00
__name__ = 'ir.sequence.type'
name = fields.Char('Sequence Name', required=True, translate=True)
code = fields.Char('Sequence Code', required=True)
2007-12-10 01:04:13 +01:00
class Sequence(ModelSQL, ModelView):
2007-12-10 01:04:13 +01:00
"Sequence"
2012-09-24 22:16:53 +02:00
__name__ = 'ir.sequence'
_strict = False
name = fields.Char('Sequence Name', required=True, translate=True)
2010-09-02 17:31:51 +02:00
code = fields.Selection('code_get', 'Sequence Code', required=True,
2011-08-21 11:19:06 +02:00
states={
'readonly': Eval('context', {}).contains('code'),
})
active = fields.Boolean('Active')
prefix = fields.Char('Prefix')
suffix = fields.Char('Suffix')
2010-09-02 17:31:51 +02:00
type = fields.Selection([
('incremental', 'Incremental'),
('decimal timestamp', 'Decimal Timestamp'),
('hexadecimal timestamp', 'Hexadecimal Timestamp'),
], 'Type')
number_next_internal = fields.Integer('Next Number',
2011-08-21 11:19:06 +02:00
states={
'invisible': ~Eval('type').in_(['incremental']),
'required': And(Eval('type').in_(['incremental']),
not sql_sequence),
2010-09-02 17:31:51 +02:00
}, depends=['type'])
number_next = fields.Function(number_next_internal, 'get_number_next',
'set_number_next')
2010-09-02 17:31:51 +02:00
number_increment = fields.Integer('Increment Number',
2011-08-21 11:19:06 +02:00
states={
'invisible': ~Eval('type').in_(['incremental']),
'required': Eval('type').in_(['incremental']),
2010-09-02 17:31:51 +02:00
}, depends=['type'])
padding = fields.Integer('Number padding',
2011-08-21 11:19:06 +02:00
states={
'invisible': ~Eval('type').in_(['incremental']),
'required': Eval('type').in_(['incremental']),
2010-09-02 17:31:51 +02:00
}, depends=['type'])
timestamp_rounding = fields.Float('Timestamp Rounding', required=True,
2011-08-21 11:19:06 +02:00
states={
'invisible': ~Eval('type').in_(
['decimal timestamp', 'hexadecimal timestamp']),
2010-09-02 17:31:51 +02:00
}, depends=['type'])
timestamp_offset = fields.Float('Timestamp Offset', required=True,
2011-08-21 11:19:06 +02:00
states={
'invisible': ~Eval('type').in_(
['decimal timestamp', 'hexadecimal timestamp']),
2010-09-02 17:31:51 +02:00
}, depends=['type'])
last_timestamp = fields.Integer('Last Timestamp',
2011-08-21 11:19:06 +02:00
states={
'invisible': ~Eval('type').in_(
['decimal timestamp', 'hexadecimal timestamp']),
'required': Eval('type').in_(
['decimal timestamp', 'hexadecimal timestamp']),
2010-09-02 17:31:51 +02:00
}, depends=['type'])
2012-09-24 22:16:53 +02:00
@classmethod
def __setup__(cls):
super(Sequence, cls).__setup__()
table = cls.__table__()
2012-09-24 22:16:53 +02:00
cls._sql_constraints += [
('check_timestamp_rounding',
Check(table, table.timestamp_rounding > 0),
'Timestamp rounding should be greater than 0'),
]
2012-09-24 22:16:53 +02:00
cls._error_messages.update({
'missing': 'Missing sequence.',
'invalid_prefix': ('Invalid prefix "%(prefix)s" on sequence '
'"%(sequence)s".'),
'invalid_suffix': ('Invalid suffix "%(suffix)s" on sequence '
'"%(sequence)s".'),
'future_last_timestamp': ('Last Timestamp cannot be in the '
'future on sequence "%s".'),
})
2008-05-19 10:43:59 +02:00
2012-09-24 22:16:53 +02:00
@classmethod
def __register__(cls, module_name):
2013-09-06 22:32:37 +02:00
TableHandler = backend.get('TableHandler')
table = TableHandler(cls, module_name)
# Migration from 2.0 rename number_next into number_next_internal
table.column_rename('number_next', 'number_next_internal')
2012-09-24 22:16:53 +02:00
super(Sequence, cls).__register__(module_name)
# Migration from 2.0 create sql_sequence
2012-09-24 22:16:53 +02:00
if sql_sequence and not cls._strict:
sequences = cls.search([])
for sequence in sequences:
if sequence.type != 'incremental':
continue
if not TableHandler.sequence_exist(
2012-09-24 22:16:53 +02:00
sequence._sql_sequence_name):
sequence.create_sql_sequence(sequence.number_next_internal)
2012-09-24 22:16:53 +02:00
@staticmethod
def default_active():
2010-08-19 22:01:12 +02:00
return True
2012-09-24 22:16:53 +02:00
@staticmethod
def default_type():
2010-09-02 17:31:51 +02:00
return 'incremental'
2012-09-24 22:16:53 +02:00
@staticmethod
def default_number_increment():
return 1
2012-09-24 22:16:53 +02:00
@staticmethod
def default_number_next():
return 1
2012-09-24 22:16:53 +02:00
@staticmethod
def default_padding():
return 0
2007-12-10 01:04:13 +01:00
2012-09-24 22:16:53 +02:00
@staticmethod
def default_timestamp_rounding():
2010-09-02 17:31:51 +02:00
return 1.0
2012-09-24 22:16:53 +02:00
@staticmethod
def default_timestamp_offset():
2012-04-01 23:08:15 +02:00
return 946681200.0 # Offset for 2000-01-01
2010-09-02 17:31:51 +02:00
2012-09-24 22:16:53 +02:00
@staticmethod
def default_last_timestamp():
2010-09-02 17:31:51 +02:00
return 0.0
2012-09-24 22:16:53 +02:00
@staticmethod
def default_code():
2012-03-27 10:41:40 +02:00
return Transaction().context.get('code')
2012-09-24 22:16:53 +02:00
def get_number_next(self, name):
if self.type != 'incremental':
return
cursor = Transaction().connection.cursor()
2012-09-24 22:16:53 +02:00
sql_name = self._sql_sequence_name
if sql_sequence and not self._strict:
cursor.execute('SELECT '
'CASE WHEN NOT is_called THEN last_value '
'ELSE last_value + increment_by '
'END FROM "%s"' % sql_name)
return cursor.fetchone()[0]
else:
return self.number_next_internal
2012-09-24 22:16:53 +02:00
@classmethod
def set_number_next(cls, sequences, name, value):
super(Sequence, cls).write(sequences, {
'number_next_internal': value,
})
2015-03-09 19:40:41 +01:00
@classmethod
def view_attributes(cls):
return [
('//group[@id="incremental"]', 'states', {
'invisible': ~Eval('type').in_(['incremental']),
}),
('//group[@id="timestamp"]', 'states', {
'invisible': ~Eval('type').in_(
['decimal timestamp', 'hexadecimal timestamp']),
}),
]
2012-09-24 22:16:53 +02:00
@classmethod
2013-01-06 22:18:13 +01:00
def create(cls, vlist):
sequences = super(Sequence, cls).create(vlist)
for sequence, values in izip(sequences, vlist):
if sql_sequence and not cls._strict:
sequence.update_sql_sequence(values.get('number_next',
cls.default_number_next()))
return sequences
2012-09-24 22:16:53 +02:00
@classmethod
2013-12-19 14:44:01 +01:00
def write(cls, sequences, values, *args):
super(Sequence, cls).write(sequences, values, *args)
2012-09-24 22:16:53 +02:00
if sql_sequence and not cls._strict:
2013-12-19 14:44:01 +01:00
actions = iter((sequences, values) + args)
for sequences, values in zip(actions, actions):
for sequence in sequences:
sequence.update_sql_sequence(values.get('number_next'))
2012-09-24 22:16:53 +02:00
@classmethod
def delete(cls, sequences):
if sql_sequence and not cls._strict:
for sequence in sequences:
2012-09-24 22:16:53 +02:00
sequence.delete_sql_sequence()
return super(Sequence, cls).delete(sequences)
2012-09-24 22:16:53 +02:00
@classmethod
def code_get(cls):
2011-07-03 13:20:58 +02:00
pool = Pool()
2012-09-24 22:16:53 +02:00
SequenceType = pool.get('ir.sequence.type')
sequence_types = SequenceType.search([])
return [(x.code, x.name) for x in sequence_types]
@classmethod
def validate(cls, sequences):
super(Sequence, cls).validate(sequences)
cls.check_prefix_suffix(sequences)
cls.check_last_timestamp(sequences)
2012-09-24 22:16:53 +02:00
@classmethod
def check_prefix_suffix(cls, sequences):
2008-05-19 10:43:59 +02:00
"Check prefix and suffix"
2012-09-24 22:16:53 +02:00
for sequence in sequences:
for fix, error_message in ((sequence.prefix, 'invalid_prefix'),
(sequence.suffix, 'invalid_suffix')):
try:
cls._process(sequence.prefix)
cls._process(sequence.suffix)
except Exception:
cls.raise_user_error(error_message, {
'prefix': fix,
'sequence': sequence.rec_name,
})
2008-05-19 10:43:59 +02:00
2012-09-24 22:16:53 +02:00
@classmethod
def check_last_timestamp(cls, sequences):
2010-09-02 17:31:51 +02:00
"Check last_timestamp"
2012-09-24 22:16:53 +02:00
for sequence in sequences:
next_timestamp = cls._timestamp(sequence)
2010-09-02 17:31:51 +02:00
if sequence.last_timestamp > next_timestamp:
cls.raise_user_error('future_last_timestamp', (
sequence.rec_name,))
2010-09-02 17:31:51 +02:00
2012-09-24 22:16:53 +02:00
@property
def _sql_sequence_name(self):
'Return SQL sequence name'
2012-09-24 22:16:53 +02:00
return '%s_%s' % (self._table, self.id)
2012-09-24 22:16:53 +02:00
def create_sql_sequence(self, number_next=None):
'Create the SQL sequence'
cursor = Transaction().connection.cursor()
2013-09-06 22:32:37 +02:00
param = Flavor.get().param
2012-09-24 22:16:53 +02:00
if self.type != 'incremental':
return
if number_next is None:
2012-09-24 22:16:53 +02:00
number_next = self.number_next
cursor.execute('CREATE SEQUENCE "' + self._sql_sequence_name
2013-09-06 22:32:37 +02:00
+ '" INCREMENT BY ' + param + ' START WITH ' + param,
2012-09-24 22:16:53 +02:00
(self.number_increment, number_next))
2012-09-24 22:16:53 +02:00
def update_sql_sequence(self, number_next=None):
'Update the SQL sequence'
2013-09-06 22:32:37 +02:00
TableHandler = backend.get('TableHandler')
cursor = Transaction().connection.cursor()
2013-09-06 22:32:37 +02:00
param = Flavor.get().param
exist = TableHandler.sequence_exist(self._sql_sequence_name)
2012-09-24 22:16:53 +02:00
if self.type != 'incremental':
if exist:
2012-09-24 22:16:53 +02:00
self.delete_sql_sequence()
return
if not exist:
2012-09-24 22:16:53 +02:00
self.create_sql_sequence(number_next)
return
if number_next is None:
2012-09-24 22:16:53 +02:00
number_next = self.number_next
cursor.execute('ALTER SEQUENCE "' + self._sql_sequence_name
2013-09-06 22:32:37 +02:00
+ '" INCREMENT BY ' + param + ' RESTART WITH ' + param,
2012-09-24 22:16:53 +02:00
(self.number_increment, number_next))
2012-09-24 22:16:53 +02:00
def delete_sql_sequence(self):
'Delete the SQL sequence'
cursor = Transaction().connection.cursor()
2012-09-24 22:16:53 +02:00
if self.type != 'incremental':
return
cursor.execute('DROP SEQUENCE "%s"'
2012-09-24 22:16:53 +02:00
% self._sql_sequence_name)
2012-09-24 22:16:53 +02:00
@staticmethod
def _process(string, date=None):
2011-07-03 13:20:58 +02:00
pool = Pool()
2012-09-24 22:16:53 +02:00
Date = pool.get('ir.date')
if not date:
2012-09-24 22:16:53 +02:00
date = Date.today()
year = datetime_strftime(date, '%Y')
month = datetime_strftime(date, '%m')
day = datetime_strftime(date, '%d')
2008-05-19 10:43:59 +02:00
return Template(string or '').substitute(
year=year,
month=month,
day=day,
2008-05-19 10:43:59 +02:00
)
2007-12-10 01:04:13 +01:00
2012-09-24 22:16:53 +02:00
@staticmethod
def _timestamp(sequence):
2010-09-02 17:31:51 +02:00
return int((time.time() - sequence.timestamp_offset)
/ sequence.timestamp_rounding)
2012-09-24 22:16:53 +02:00
@classmethod
def _get_sequence(cls, sequence):
2010-09-02 17:31:51 +02:00
if sequence.type == 'incremental':
2012-09-24 22:16:53 +02:00
if sql_sequence and not cls._strict:
cursor = Transaction().connection.cursor()
cursor.execute('SELECT nextval(\'"%s"\')'
2012-09-24 22:16:53 +02:00
% sequence._sql_sequence_name)
number_next, = cursor.fetchone()
else:
2014-12-02 12:54:01 +01:00
# Pre-fetch number_next
number_next = sequence.number_next_internal
2010-09-02 17:31:51 +02:00
2014-09-17 21:43:53 +02:00
cls.write([sequence], {
'number_next_internal': (number_next
+ sequence.number_increment),
})
2010-09-02 17:31:51 +02:00
return '%%0%sd' % sequence.padding % number_next
elif sequence.type in ('decimal timestamp', 'hexadecimal timestamp'):
timestamp = sequence.last_timestamp
while timestamp == sequence.last_timestamp:
2012-09-24 22:16:53 +02:00
timestamp = cls._timestamp(sequence)
2014-09-17 21:43:53 +02:00
cls.write([sequence], {
'last_timestamp': timestamp,
})
2010-09-02 17:31:51 +02:00
if sequence.type == 'decimal timestamp':
return '%d' % timestamp
else:
return hex(timestamp)[2:].upper()
return ''
2012-09-24 22:16:53 +02:00
@classmethod
def get_id(cls, domain):
'''
Return sequence value for the domain
'''
2012-09-24 22:16:53 +02:00
if isinstance(domain, cls):
domain = domain.id
if isinstance(domain, (int, long)):
domain = [('id', '=', domain)]
2010-01-19 12:23:19 +01:00
# bypass rules on sequences
2014-09-17 21:43:53 +02:00
with Transaction().set_context(user=False, _check_access=False):
2010-08-19 22:01:12 +02:00
with Transaction().set_user(0):
2012-09-24 22:16:53 +02:00
try:
sequence, = cls.search(domain, limit=1)
except TypeError:
cls.raise_user_error('missing')
2014-09-17 21:43:53 +02:00
date = Transaction().context.get('date')
return '%s%s%s' % (
cls._process(sequence.prefix, date=date),
cls._get_sequence(sequence),
cls._process(sequence.suffix, date=date),
)
2007-12-10 01:04:13 +01:00
2012-09-24 22:16:53 +02:00
@classmethod
def get(cls, code):
return cls.get_id([('code', '=', code)])
class SequenceStrict(Sequence):
"Sequence Strict"
2012-09-24 22:16:53 +02:00
__name__ = 'ir.sequence.strict'
_table = 'ir_sequence_strict' # Needed to override Sequence._table
_strict = True
2012-09-24 22:16:53 +02:00
@classmethod
def get_id(cls, clause):
transaction = Transaction()
transaction.database.lock(transaction.connection, cls._table)
2012-09-24 22:16:53 +02:00
return super(SequenceStrict, cls).get_id(clause)