Blame view

product/ERP5/Tool/IdTool.py 15.7 KB
Jean-Paul Smets committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
#                    Sebastien Robin <seb@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

Danièle Vanbaelinghem committed
29 30 31
import warnings
import zope.interface

Jérome Perrin committed
32
from Acquisition import aq_base
Jean-Paul Smets committed
33
from AccessControl import ClassSecurityInfo
34
from Products.ERP5Type.Globals import InitializeClass, DTMLFile, PersistentMapping
Yoshinori Okuji committed
35
from Products.ERP5Type.Tool.BaseTool import BaseTool
Danièle Vanbaelinghem committed
36 37 38
from Products.ERP5Type.Cache import caching_instance_method
from Products.ERP5Type import Permissions, interfaces
from zLOG import LOG, WARNING, INFO, ERROR
Jean-Paul Smets committed
39 40
from Products.ERP5 import _dtmldir

Vincent Pelletier committed
41
from BTrees.Length import Length
Jean-Paul Smets committed
42

Danièle Vanbaelinghem committed
43 44
_marker = object()

Yoshinori Okuji committed
45
class IdTool(BaseTool):
Vincent Pelletier committed
46 47 48
  """
    This tools handles the generation of IDs.
  """
Danièle Vanbaelinghem committed
49
  zope.interface.implements(interfaces.IIdTool)
Vincent Pelletier committed
50 51 52 53 54 55 56 57 58
  id = 'portal_ids'
  meta_type = 'ERP5 Id Tool'
  portal_type = 'Id Tool'

  # Declarative Security
  security = ClassSecurityInfo()

  security.declareProtected( Permissions.ManagePortal, 'manage_overview' )
  manage_overview = DTMLFile( 'explainIdTool', _dtmldir )
Jean-Paul Smets committed
59

Danièle Vanbaelinghem committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
  def newContent(self, *args, **kw):
    """
      the newContent is overriden to not use generateNewId
    """
    if not kw.has_key(id):
      new_id = self._generateNextId()
      if new_id is not None:
        kw['id'] = new_id
      else:
        raise ValueError('Failed to gererate id')
    return BaseTool.newContent(self, *args, **kw)

  def _get_id(self, id):
    """
      _get_id is overrided to not use generateNewId
      It is used for example when an object is cloned
    """
    if self._getOb(id, None) is None :
      return id
    return self._generateNextId()

  @caching_instance_method(id='IdTool._getLatestIdGenerator',
    cache_factory='erp5_content_long')
  def _getLatestIdGenerator(self, reference):
    """
      Tries to find the id_generator with the latest version
      from the current object.
      Use the low-level to create a site without catalog
    """
    assert reference
    id_last_generator = None
    version_last_generator = 0
Vincent Pelletier committed
92
    for generator in self.objectValues():
Danièle Vanbaelinghem committed
93 94 95 96
      if generator.getReference() == reference:
        version = generator.getVersion()
        if version > version_last_generator:
          id_last_generator = generator.getId()
Vincent Pelletier committed
97
          version_last_generator = version
Danièle Vanbaelinghem committed
98
    if id_last_generator is None:
Vincent Pelletier committed
99
      raise KeyError(repr(reference))
Danièle Vanbaelinghem committed
100 101 102 103 104 105
    return id_last_generator

  def _getLatestGeneratorValue(self, id_generator):
    """
      Return the last generator with the reference
    """
Vincent Pelletier committed
106
    return self._getOb(self._getLatestIdGenerator(id_generator))
Danièle Vanbaelinghem committed
107 108 109 110

  security.declareProtected(Permissions.AccessContentsInformation,
                            'generateNewId')
  def generateNewId(self, id_group=None, default=None, method=_marker,
Vincent Pelletier committed
111
                    id_generator=None, poison=False):
Danièle Vanbaelinghem committed
112 113 114 115
    """
      Generate the next id in the sequence of ids of a particular group
    """
    if id_group in (None, 'None'):
Jérome Perrin committed
116
      raise ValueError, '%s is not a valid id_group' % (repr(id_group), )
Danièle Vanbaelinghem committed
117 118 119
    # for compatibilty with sql data, must not use id_group as a list
    if not isinstance(id_group, str):
      id_group = repr(id_group)
Jérome Perrin committed
120 121
      warnings.warn('id_group must be a string, other types '
                    'are deprecated.', DeprecationWarning)
Danièle Vanbaelinghem committed
122 123 124
    if id_generator is None:
      id_generator = 'document'
    if method is not _marker:
Jérome Perrin committed
125
      warnings.warn("Use of 'method' argument is deprecated", DeprecationWarning)
Danièle Vanbaelinghem committed
126 127 128 129
    try:
      #use _getLatestGeneratorValue here for that the technical level
      #must not call the method
      last_generator = self._getLatestGeneratorValue(id_generator)
Vincent Pelletier committed
130 131 132 133 134
      new_id = last_generator.generateNewId(
        id_group=id_group,
        default=default,
        poison=poison,
      )
Danièle Vanbaelinghem committed
135 136
    except KeyError:
      # XXX backward compatiblity
Julien Muchembled committed
137
      if self.getTypeInfo():
Danièle Vanbaelinghem committed
138 139 140 141 142
        LOG('generateNewId', ERROR, 'while generating id')
        raise
      else:
        # Compatibility code below, in case the last version of erp5_core
        # is not installed yet
Jérome Perrin committed
143 144 145
        warnings.warn("You are using an old version of erp5_core to generate"
                      "ids.\nPlease update erp5_core business template to "
                      "use new id generators", DeprecationWarning)
Danièle Vanbaelinghem committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
        dict_ids = getattr(aq_base(self), 'dict_ids', None)
        if dict_ids is None:
          dict_ids = self.dict_ids = PersistentMapping()
        new_id = None
        # Getting the last id
        if default is None:
          default = 0
        marker = []
        new_id = dict_ids.get(id_group, marker)
        if method is _marker:
          if new_id is marker:
            new_id = default
          else:
            new_id = new_id + 1
        else:
          if new_id is marker:
            new_id = default
          new_id = method(new_id)
        # Store the new value
        dict_ids[id_group] = new_id
    return new_id

  security.declareProtected(Permissions.AccessContentsInformation,
                            'generateNewIdList')
  def generateNewIdList(self, id_group=None, id_count=1, default=None,
Vincent Pelletier committed
171
                        store=_marker, id_generator=None, poison=False):
Danièle Vanbaelinghem committed
172 173 174 175
    """
      Generate a list of next ids in the sequence of ids of a particular group
    """
    if id_group in (None, 'None'):
Jérome Perrin committed
176
      raise ValueError, '%s is not a valid id_group' % (repr(id_group), )
Danièle Vanbaelinghem committed
177 178 179
    # for compatibilty with sql data, must not use id_group as a list
    if not isinstance(id_group, str):
      id_group = repr(id_group)
Jérome Perrin committed
180 181
      warnings.warn('id_group must be a string, other types '
                    'are deprecated.', DeprecationWarning)
Danièle Vanbaelinghem committed
182 183 184
    if id_generator is None:
      id_generator = 'uid'
    if store is not _marker:
Jérome Perrin committed
185 186
      warnings.warn("Use of 'store' argument is deprecated.",
                    DeprecationWarning)
Danièle Vanbaelinghem committed
187 188 189 190 191
    try:
      #use _getLatestGeneratorValue here for that the technical level
      #must not call the method
      last_generator = self._getLatestGeneratorValue(id_generator)
      new_id_list = last_generator.generateNewIdList(id_group=id_group,
Vincent Pelletier committed
192
                         id_count=id_count, default=default, poison=poison)
Sebastien Robin committed
193
    except (KeyError, ValueError):
Danièle Vanbaelinghem committed
194
      # XXX backward compatiblity
Julien Muchembled committed
195
      if self.getTypeInfo():
Danièle Vanbaelinghem committed
196 197 198 199 200
        LOG('generateNewIdList', ERROR, 'while generating id')
        raise
      else:
        # Compatibility code below, in case the last version of erp5_core
        # is not installed yet
Jérome Perrin committed
201 202 203
        warnings.warn("You are using an old version of erp5_core to generate"
                      "ids.\nPlease update erp5_core business template to "
                      "use new id generators", DeprecationWarning)
Danièle Vanbaelinghem committed
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
        new_id = None
        if default is None:
          default = 1
        # XXX It's temporary, a New API will be implemented soon
        #     the code will be change
        portal = self.getPortalObject()
        query = getattr(portal, 'IdTool_zGenerateId', None)
        commit = getattr(portal, 'IdTool_zCommit', None)

        if query is None or commit is None:
          portal_catalog = getattr(self, 'portal_catalog').getSQLCatalog()
          query = getattr(portal_catalog, 'z_portal_ids_generate_id')
          commit = getattr(portal_catalog, 'z_portal_ids_commit')
        if None in (query, commit):
          raise AttributeError, 'Error while generating Id: ' \
            'idTool_zGenerateId and/or idTool_zCommit could not ' \
            'be found.'
        try:
          result = query(id_group=id_group, id_count=id_count, default=default)
        finally:
          commit()
        new_id = result[0]['LAST_INSERT_ID()']
        if store:
          if getattr(aq_base(self), 'dict_length_ids', None) is None:
            # Length objects are stored in a persistent mapping: there is one
            # Length object per id_group.
            self.dict_length_ids = PersistentMapping()
          if self.dict_length_ids.get(id_group) is None:
            self.dict_length_ids[id_group] = Length(new_id)
          self.dict_length_ids[id_group].set(new_id)
        new_id_list = range(new_id - id_count, new_id)
    return new_id_list

237
  security.declareProtected(Permissions.ModifyPortalContent,
Danièle Vanbaelinghem committed
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
                            'initializeGenerator')
  def initializeGenerator(self, id_generator=None, all=False):
    """
    Initialize generators. This is mostly used when a new ERP5 site
    is created. Some generators will need to do some initialization like
    creating SQL Database, prepare some data in ZODB, etc
    """
    if not all:
      #Use _getLatestGeneratorValue here for that the technical level
      #must not call the method
      last_generator = self._getLatestGeneratorValue(id_generator)
      last_generator.initializeGenerator()
    else:
      # recovery all the generators and initialize them
      for generator in self.objectValues(\
                       portal_type='Application Id Generator'):
        generator.initializeGenerator()

256
  security.declareProtected(Permissions.ModifyPortalContent,
Danièle Vanbaelinghem committed
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
                            'clearGenerator')
  def clearGenerator(self, id_generator=None, all=False):
    """
    Clear generators data. This can be usefull when working on a
    development instance or in some other rare cases. This will
    loose data and must be use with caution

    This can be incompatible with some particular generator implementation,
    in this case a particular error will be raised (to be determined and
    added here)
    """
    if not all:
      #Use _getLatestGeneratorValue here for that the technical level
      #must not call the method
      last_generator = self._getLatestGeneratorValue(id_generator)
      last_generator.clearGenerator()

    else:
      if len(self.objectValues()) == 0:
        # compatibility with old API
        self.getPortalObject().IdTool_zDropTable()
        self.getPortalObject().IdTool_zCreateTable()
      for generator in self.objectValues(\
                       portal_type='Application Id Generator'):
        generator.clearGenerator()

  ## XXX Old API deprecated
  #backward compatibility
Kazuhiko Shiozaki committed
285 286
  security.declareProtected(Permissions.AccessContentsInformation,
                           'generateNewLengthIdList')
Danièle Vanbaelinghem committed
287 288 289 290 291 292 293 294
  generateNewLengthIdList = generateNewIdList

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getLastLengthGeneratedId')
  def getLastLengthGeneratedId(self, id_group, default=None):
    """
    Get the last length id generated
    """
Jérome Perrin committed
295 296
    warnings.warn('getLastLengthGeneratedId is deprecated',
                   DeprecationWarning)
Danièle Vanbaelinghem committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    # check in persistent mapping if exists
    if getattr(aq_base(self), 'dict_length_ids', None) is not None:
      last_id = self.dict_length_ids.get(id_group)
      if last_id is not None:
        return last_id.value - 1
    # otherwise check in mysql
    # XXX It's temporary, a New API will be implemented soon
    #     the code will be change
    portal = self.getPortalObject()
    query = getattr(portal, 'IdTool_zGetLastId', None)
    if query is None:
      portal_catalog = getattr(self, 'portal_catalog').getSQLCatalog()
      query = getattr(portal_catalog, 'z_portal_ids_get_last_id')
    if query is None:
      raise AttributeError, 'Error while getting last Id: ' \
            'IdTool_zGetLastId could not ' \
            'be found.'
    result = query(id_group=id_group)
    if len(result):
316 317 318 319
      try:
        return result[0]['last_id']
      except KeyError:
        return result[0]['LAST_INSERT_ID()']
Danièle Vanbaelinghem committed
320 321
    return default

Sebastien Robin committed
322 323
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getLastGeneratedId')
Vincent Pelletier committed
324
  def getLastGeneratedId(self, id_group=None, default=None):
Sebastien Robin committed
325 326 327
    """
    Get the last id generated
    """
Jérome Perrin committed
328
    warnings.warn('getLastGeneratedId is deprecated', DeprecationWarning)
Jérome Perrin committed
329
    if getattr(aq_base(self), 'dict_ids', None) is None:
Sebastien Robin committed
330 331
      self.dict_ids = PersistentMapping()
    last_id = None
Vincent Pelletier committed
332
    if id_group is not None and id_group != 'None':
Sebastien Robin committed
333 334
      last_id = self.dict_ids.get(id_group, default)
    return last_id
Danièle Vanbaelinghem committed
335

Jérome Perrin committed
336
  security.declareProtected(Permissions.ModifyPortalContent,
Sebastien Robin committed
337
                            'setLastGeneratedId')
Vincent Pelletier committed
338
  def setLastGeneratedId(self, new_id, id_group=None):
Sebastien Robin committed
339 340 341 342
    """
    Set a new last id. This is usefull in order to reset
    a sequence of ids.
    """
Jérome Perrin committed
343
    if getattr(aq_base(self), 'dict_ids', None) is None:
Sebastien Robin committed
344
      self.dict_ids = PersistentMapping()
Vincent Pelletier committed
345
    if id_group is not None and id_group != 'None':
Vincent Pelletier committed
346
      self.dict_ids[id_group] = new_id
Vincent Pelletier committed
347

Danièle Vanbaelinghem committed
348 349
  security.declareProtected(Permissions.AccessContentsInformation,
                           'generateNewLengthId')
Jérome Perrin committed
350
  def generateNewLengthId(self, id_group=None, default=None, store=_marker):
Jérome Perrin committed
351
     """Generates an Id using a conflict free id generator. Deprecated.
Danièle Vanbaelinghem committed
352
     """
Jérome Perrin committed
353 354 355
     warnings.warn('generateNewLengthId is deprecated.\n'
                   'Use generateNewIdList with a sql id_generator',
                   DeprecationWarning)
Jérome Perrin committed
356 357 358 359 360
     if store is not _marker:
       return self.generateNewIdList(id_group=id_group,
                        id_count=1, default=default, store=store)[0]
     return self.generateNewIdList(id_group=id_group,
                        id_count=1, default=default)[0]
Jean-Paul Smets committed
361

Vincent Pelletier committed
362
  security.declareProtected(Permissions.AccessContentsInformation,
Jérome Perrin committed
363
                            'getDictLengthIdsItems')
Vincent Pelletier committed
364 365 366 367 368 369 370 371 372 373
  def getDictLengthIdsItems(self):
    """
      Return a copy of dict_length_ids.
      This is a workaround to access the persistent mapping content from ZSQL
      method to be able to insert initial tuples in the database at creation.
    """
    if getattr(self, 'dict_length_ids', None) is None:
      self.dict_length_ids = PersistentMapping()
    return self.dict_length_ids.items()

Vincent Pelletier committed
374 375 376 377 378
  security.declarePrivate('dumpDictLengthIdsItems')
  def dumpDictLengthIdsItems(self):
    """
      Store persistently data from SQL table portal_ids.
    """
Danièle Vanbaelinghem committed
379 380
    portal_catalog = getattr(self, 'portal_catalog').getSQLCatalog()
    query = getattr(portal_catalog, 'z_portal_ids_dump')
Jérome Perrin committed
381
    dict_length_ids = getattr(aq_base(self), 'dict_length_ids', None)
Vincent Pelletier committed
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    if dict_length_ids is None:
      dict_length_ids = self.dict_length_ids = PersistentMapping()
    for line in query().dictionaries():
      id_group = line['id_group']
      last_id = line['last_id']
      stored_last_id = self.dict_length_ids.get(id_group)
      if stored_last_id is None:
        self.dict_length_ids[id_group] = Length(last_id)
      else:
        stored_last_id_value = stored_last_id()
        if stored_last_id_value < last_id:
          stored_last_id.set(last_id)
        else:
          if stored_last_id_value > last_id:
            LOG('IdTool', WARNING, 'ZODB value (%r) for group %r is higher ' \
                'than SQL value (%r). Keeping ZODB value untouched.' % \
                (stored_last_id, id_group, last_id))

Jean-Paul Smets committed
400
InitializeClass(IdTool)