Package Gnumed :: Package pycommon :: Module gmBusinessDBObject |
[frames] | no frames]

# Source Code for Module Gnumed.pycommon.gmBusinessDBObject

      1  __doc__ = """GNUmed database object business class.
      2
      3  Overview
      4  --------
      5  This class wraps a source relation (table, view) which
      6  represents an entity that makes immediate business sense
      7  such as a vaccination or a medical document. In many if
      8  not most cases this source relation is a denormalizing
      9  view. The data in that view will in most cases, however,
     10  originate from several normalized tables. One instance
     11  of this class represents one row of said source relation.
     12
     13  Note, however, that this class does not *always* simply
     14  wrap a single table or view. It can also encompass several
     15  relations (views, tables, sequences etc) that taken together
     16  form an object meaningful to *business* logic.
     17
     18  Initialization
     19  --------------
     20  There are two ways to initialize an instance with values.
     21  One way is to pass a "primary key equivalent" object into
     22  __init__(). Refetch_payload() will then pull the data from
     23  the backend. Another way would be to fetch the data outside
     24  the instance and pass it in via the <row> argument. In that
     25  case the instance will not initially connect to the databse
     26  which may offer a great boost to performance.
     27
     28  Values API
     29  ----------
     30  Field values are cached for later access. They can be accessed
     31  by a dictionary API, eg:
     32
     33          old_value = object['field']
     34          object['field'] = new_value
     35
     36  The field names correspond to the respective column names
     37  in the "main" source relation. Accessing non-existant field
     38  names will raise an error, so does trying to set fields not
     39  listed in self.__class__._updatable_fields. To actually
     40  store updated values in the database one must explicitly
     41  call save_payload().
     42
     43  The class will in many cases be enhanced by accessors to
     44  related data that is not directly part of the business
     45  object itself but are closely related, such as codes
     46  linked to a clinical narrative entry (eg a diagnosis). Such
     47  accessors in most cases start with get_*. Related setters
     48  start with set_*. The values can be accessed via the
     49  object['field'] syntax, too, but they will be cached
     50  independantly.
     51
     52  Concurrency handling
     53  --------------------
     54  GNUmed connections always run transactions in isolation level
     55  "serializable". This prevents transactions happening at the
     56  *very same time* to overwrite each other's data. All but one
     57  of them will abort with a concurrency error (eg if a
     58  transaction runs a select-for-update later than another one
     59  it will hang until the first transaction ends. Then it will
     60  succeed or fail depending on what the first transaction
     61  did). This is standard transactional behaviour.
     62
     63  However, another transaction may have updated our row
     64  between the time we first fetched the data and the time we
     65  start the update transaction. This is noticed by getting the
     66  XMIN system column for the row when initially fetching the
     67  data and using that value as a where condition value when
     68  updating the row later. If the row had been updated (xmin
     69  changed) or deleted (primary key disappeared) in the
     70  meantime the update will touch zero rows (as no row with
     71  both PK and XMIN matching is found) even if the query itself
     72  syntactically succeeds.
     73
     74  When detecting a change in a row due to XMIN being different
     75  one needs to be careful how to represent that to the user.
     76  The row may simply have changed but it also might have been
     77  deleted and a completely new and unrelated row which happens
     78  to have the same primary key might have been created ! This
     79  row might relate to a totally different context (eg. patient,
     80  episode, encounter).
     81
     82  One can offer all the data to the user:
     83
     84  self.payload_most_recently_fetched
     85  - contains the data at the last successful refetch
     86
     87  self.payload_most_recently_attempted_to_store
     88  - contains the modified payload just before the last
     89    failure of save_payload() - IOW what is currently
     90    in the database
     91
     92  self._payload
     93  - contains the currently active payload which may or
     94    may not contain changes
     95
     96  For discussion on this see the thread starting at:
     97
     98          http://archives.postgresql.org/pgsql-general/2004-10/msg01352.php
     99
    100  and here
    101
    102          http://groups.google.com/group/pgsql.general/browse_thread/thread/e3566ba76173d0bf/6cf3c243a86d9233
    103          (google for "XMIN semantic at peril")
    104
    105  Problem cases with XMIN:
    106
    107  1) not unlikely
    108  - a very old row is read with XMIN
    109  - vacuum comes along and sets XMIN to FrozenTransactionId
    110    - now XMIN changed but the row actually didn't !
    111  - an update with "... where xmin = old_xmin ..." fails
    112    although there is no need to fail
    113
    114  2) quite unlikely
    115  - a row is read with XMIN
    116  - a long time passes
    117  - the original XMIN gets frozen to FrozenTransactionId
    118  - another writer comes along and changes the row
    119  - incidentally the exact same old row gets the old XMIN *again*
    120    - now XMIN is (again) the same but the data changed !
    121  - a later update fails to detect the concurrent change !!
    122
    123  TODO:
    124  The solution is to use our own column for optimistic locking
    125  which gets updated by an AFTER UPDATE trigger.
    126  """
    127  #============================================================
    128  __author__ = "K.Hilbert <Karsten.Hilbert@gmx.net>"
    129  __license__ = "GPL v2 or later"
    130
    131
    132  import sys
    133  import inspect
    134  import logging
    135  import datetime
    136
    137
    138  if __name__ == '__main__':
    139          sys.path.insert(0, '../../')
    140  from Gnumed.pycommon import gmExceptions
    141  from Gnumed.pycommon import gmPG2
    142  from Gnumed.pycommon.gmDateTime import pydt_strftime
    143  from Gnumed.pycommon.gmTools import tex_escape_string
    144  from Gnumed.pycommon.gmTools import xetex_escape_string
    145  from Gnumed.pycommon.gmTools import compare_dict_likes
    146  from Gnumed.pycommon.gmTools import format_dict_like
    147  from Gnumed.pycommon.gmTools import dicts2table
    148  from Gnumed.pycommon.gmTools import u_left_arrow
    149
    150
    151  _log = logging.getLogger('gm.db')
    152
    153  #============================================================
    154 -class cBusinessDBObject(object):
    155          """Represents business objects in the database.
    156
    157          Rules:
    158          - instances ARE ASSUMED TO EXIST in the database
    159          - PK construction (aPK_obj): DOES verify its existence on instantiation
    160                                       (fetching data fails)
    161          - Row construction (row): allowed by using a dict of pairs
    162                                         field name: field value (PERFORMANCE improvement)
    163          - does NOT verify FK target existence
    164          - does NOT create new entries in the database
    165          - does NOT lazy-fetch fields on access
    166
    167          Class scope SQL commands and variables:
    168
    169          <_cmd_fetch_payload>
    170                  - must return exactly one row
    171                  - WHERE clause argument values are expected in
    172                    self.pk_obj (taken from __init__(aPK_obj))
    173                  - must return xmin of all rows that _cmds_store_payload
    174                    will be updating, so views must support the xmin columns
    175                    of their underlying tables
    176
    177          <_cmds_store_payload>
    178                  - one or multiple "update ... set ... where xmin_* = ... and pk* = ..."
    179                    statements which actually update the database from the data in self._payload,
    180                  - the last query must refetch at least the XMIN values needed to detect
    181                    concurrent updates, their field names had better be the same as
    182                    in _cmd_fetch_payload,
    183                  - the last query CAN return other fields which is particularly
    184                    useful when those other fields are computed in the backend
    185                    and may thus change upon save but will not have been set by
    186                    the client code explicitely - this is only really of concern
    187                    if the saved subclass is to be reused after saving rather
    188                    than re-instantiated
    189                  - when subclasses tend to live a while after save_payload() was
    190                    called and they support computed fields (say, _(some_column)
    191                    you need to return *all* columns (see cEncounter)
    192
    193          <_updatable_fields>
    194                  - a list of fields available for update via object['field']
    195
    196
    197          A template for new child classes:
    198
    199  *********** start of template ***********
    200
    201  #------------------------------------------------------------
    202  from Gnumed.pycommon import gmBusinessDBObject
    203  from Gnumed.pycommon import gmPG2
    204
    205  #============================================================
    206  # short description
    207  #------------------------------------------------------------
    208  # search/replace "" " -> 3 "s
    209  #
    210  # search-replace get_XXX, use plural form
    211  _SQL_get_XXX = u"" "
    212          SELECT *, (xmin AS xmin_XXX)
    213          FROM XXX.v_XXX
    214          WHERE %s
    215  "" "
    216
    217  class cXxxXxx(gmBusinessDBObject.cBusinessDBObject):
    218          "" "Represents ..."" "
    219
    220          _cmd_fetch_payload = _SQL_get_XXX % u"pk_XXX = %s"
    221          _cmds_store_payload = [
    222                  u"" "
    223                          -- typically the underlying table name
    224                          UPDATE xxx.xxx SET
    225                                  -- typically "table_col = %(view_col)s"
    226                                  xxx = %(xxx)s,
    227                                  xxx = gm.nullify_empty_string(%(xxx)s)
    228                          WHERE
    229                                  pk = %(pk_XXX)s
    230                                          AND
    231                                  xmin = %(xmin_XXX)s
    232                          RETURNING
    233                                  xmin AS xmin_XXX
    234                                  -- also return columns which are calculated in the view used by
    235                                  -- the initial SELECT such that they will further on contain their
    236                                  -- updated value:
    237                                  --, ...
    238                                  --, ...
    239                  "" "
    240          ]
    241          # view columns that can be updated:
    242          _updatable_fields = [
    243                  u'xxx',
    244                  u'xxx'
    245          ]
    246          #--------------------------------------------------------
    247  #       def format(self):
    248  #               return u'%s' % self
    249
    250  #------------------------------------------------------------
    251  def get_XXX(order_by=None):
    252          if order_by is None:
    253                  order_by = u'true'
    254          else:
    255                  order_by = u'true ORDER BY %s' % order_by
    256
    257          cmd = _SQL_get_XXX % order_by
    258          rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd}], get_col_idx = True)
    259          return [ cXxxXxx(row = {'data': r, 'idx': idx, 'pk_field': 'pk_XXX'}) for r in rows ]
    260  #------------------------------------------------------------
    261  def create_xxx(xxx=None, xxx=None):
    262
    263          args = {
    264                  u'xxx': xxx,
    265                  u'xxx': xxx
    266          }
    267          cmd = u"" "
    268                  INSERT INTO xxx.xxx (
    269                          xxx,
    270                          xxx,
    271                          xxx
    272                  ) VALUES (
    273                          %(xxx)s,
    274                          %(xxx)s,
    275                          gm.nullify_empty_string(%(xxx)s)
    276                  )
    277                  RETURNING pk
    278                  --RETURNING *
    279          "" "
    280          rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}], return_data = True, get_col_idx = False)
    281          #rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}], return_data = True, get_col_idx = True)
    282
    283          return cXxxXxx(aPK_obj = rows[0]['pk'])
    284          #return cXxxXxx(row = {'data': r, 'idx': idx, 'pk_field': 'pk_XXX'})
    285
    286  #------------------------------------------------------------
    287  def delete_xxx(pk_XXX=None):
    288          args = {'pk': pk_XXX}
    289          cmd = u"DELETE FROM xxx.xxx WHERE pk = %(pk)s"
    290          gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
    291          return True
    292  #------------------------------------------------------------
    293
    294  #------------------------------------------------------------
    295  # widget code
    296  #------------------------------------------------------------
    297  def edit_xxx(parent=None, xxx=None, single_entry=False, presets=None):
    298
    299  #------------------------------------------------------------
    300  def delete_xxx()
    301
    302  #------------------------------------------------------------
    303  def manage_xxx()
    304
    305  #------------------------------------------------------------
    306  # remember to add in clinical item generic workflows
    307
    308
    309  *********** end of template ***********
    310
    311          """
    312          #--------------------------------------------------------
    313 -        def __init__(self, aPK_obj=None, row=None, link_obj=None):
    314                  """Init business object.
    315
    316                  Call from child classes:
    317
    318                          super(cChildClass, self).__init__(aPK_obj = aPK_obj, row = row, link_obj = link_obj)
    319                  """
    320                  # initialize those "too early" because checking descendants might
    321                  # fail which will then call __str__ in stack trace logging if --debug
    322                  # was given which in turn needs those instance variables
    323                  self.pk_obj = '<uninitialized>'
    324                  self._idx = {}
    325                  self._payload = []              # the cache for backend object values (mainly table fields)
    326                  self._ext_cache = {}    # the cache for extended method's results
    327                  self._is_modified = False
    328
    329                  # check descendants
    330                  self.__class__._cmd_fetch_payload
    331                  self.__class__._cmds_store_payload
    332                  self.__class__._updatable_fields
    333
    334                  if aPK_obj is not None:
    335                          self.__init_from_pk(aPK_obj = aPK_obj, link_obj = link_obj)
    336                  else:
    337                          self._init_from_row_data(row = row)
    338
    339                  self._is_modified = False
    340
    341          #--------------------------------------------------------
    342 -        def __init_from_pk(self, aPK_obj=None, link_obj=None):
    343                  """Creates a new clinical item instance by its PK.
    344
    345                  aPK_obj can be:
    346                          - a simple value
    347                            * the primary key WHERE condition must be
    348                                  a simple column
    349                          - a dictionary of values
    350                            * the primary key where condition must be a
    351                                  subselect consuming the dict and producing
    352                                  the single-value primary key
    353                  """
    354                  self.pk_obj = aPK_obj
    355                  result = self.refetch_payload(link_obj = link_obj)
    356                  if result is True:
    357                          self.payload_most_recently_fetched = {}
    358                          for field in self._idx.keys():
    359                                  self.payload_most_recently_fetched[field] = self._payload[self._idx[field]]
    360                          return True
    361
    362                  if result is False:
    363                          raise gmExceptions.ConstructorError("[%s:%s]: error loading instance" % (self.__class__.__name__, self.pk_obj))
    364
    365          #--------------------------------------------------------
    366 -        def _init_from_row_data(self, row=None):
    367                  """Creates a new clinical item instance given its fields.
    368
    369                  row must be a dict with the fields:
    370                          - idx: a dict mapping field names to position
    371                          - data: the field values in a list (as returned by
    372                            cursor.fetchone() in the DB-API)
    373                          - pk_field: the name of the primary key field
    374                          OR
    375                          - pk_obj: a dictionary suitable for passed to cursor.execute
    376                            and holding the primary key values, used for composite PKs
    377
    378                  row = {
    379                          'data': rows[0],
    380                          'idx': idx,
    381                          'pk_field': 'pk_XXX (the PK column name)',
    382                          'pk_obj': {'pk_col1': pk_col1_val, 'pk_col2': pk_col2_val}
    383                  }
    384                  rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = True)
    385                  objects = [ cChildClass(row = {'data': r, 'idx': idx, 'pk_field': 'the PK column name'}) for r in rows ]
    386                  """
    387                  assert ('data' in row), "[%s:??]: 'data' missing from <row> argument: %s" % (self.__class__.__name__, row)
    388                  assert ('idx' in row), "[%s:??]: 'idx' missing from <row> argument: %s" % (self.__class__.__name__, row)
    389                  assert (len(row['idx']) == len(row['data'])), "[%s:??]: 'idx'<->'data' field count mismatch: %s" % (self.__class__.__name__, row)
    390                  faulty_pk = (('pk_field' not in row) and ('pk_obj' not in row))
    391                  assert not faulty_pk, "[%s:??]: either 'pk_field' or 'pk_obj' must exist in <row> argument: %s" % (self.__class__.__name__, row)
    392
    393                  self._idx = row['idx']
    394                  self._payload = row['data']
    395                  if 'pk_field' in row:
    396                          self.pk_obj = row['data'][row['idx'][row['pk_field']]]
    397                  else:
    398                          self.pk_obj = row['pk_obj']
    399
    400                  self.payload_most_recently_fetched = {}
    401                  for field in self._idx.keys():
    402                          self.payload_most_recently_fetched[field] = self._payload[self._idx[field]]
    403
    404          #--------------------------------------------------------
    405 -        def __del__(self):
    406                  if '_is_modified' in self.__dict__:
    407                          if self._is_modified:
    408                                  _log.critical('[%s:%s]: loosing payload changes' % (self.__class__.__name__, self.pk_obj))
    409                                  _log.debug('most recently fetched: %s' % self.payload_most_recently_fetched)
    410                                  _log.debug('modified: %s' % self._payload)
    411
    412          #--------------------------------------------------------
    413 -        def __str__(self):
    414                  lines = []
    415                  try:
    416                          for attr in self._idx.keys():
    417                                  if self._payload[self._idx[attr]] is None:
    418                                          lines.append('%s: NULL' % attr)
    419                                  else:
    420                                          lines.append('%s: %s [%s]' % (
    421                                                  attr,
    422                                                  self._payload[self._idx[attr]],
    423                                                  type(self._payload[self._idx[attr]])
    424                                          ))
    425                          return '[%s:%s]:\n%s' % (self.__class__.__name__, self.pk_obj, '\n'.join(lines))
    426                  except:
    427                          return 'likely nascent [%s @ %s], cannot show payload and primary key' %(self.__class__.__name__, id(self))
    428
    429          #--------------------------------------------------------
    430 -        def __getitem__(self, attribute):
    431                  # use try: except: as it is faster and we want this as fast as possible
    432
    433                  # 1) backend payload cache
    434                  try:
    435                          return self._payload[self._idx[attribute]]
    436                  except KeyError:
    437                          pass
    438
    439                  # 2) extension method results ...
    440                  getter = getattr(self, 'get_%s' % attribute, None)
    441                  if not callable(getter):
    442                          _log.warning('[%s]: no attribute [%s]' % (self.__class__.__name__, attribute))
    443                          _log.warning('[%s]: valid attributes: %s' % (self.__class__.__name__, str(self._idx.keys())))
    444                          _log.warning('[%s]: no getter method [get_%s]' % (self.__class__.__name__, attribute))
    445                          methods = [ m for m in inspect.getmembers(self, inspect.ismethod) if m[0].startswith('get_') ]
    446                          _log.warning('[%s]: valid getter methods: %s' % (self.__class__.__name__, str(methods)))
    447                          raise KeyError('[%s]: cannot read from key [%s]' % (self.__class__.__name__, attribute))
    448
    449                  self._ext_cache[attribute] = getter()
    450                  return self._ext_cache[attribute]
    451          #--------------------------------------------------------
    452 -        def __setitem__(self, attribute, value):
    453
    454                  # 1) backend payload cache
    455                  if attribute in self.__class__._updatable_fields:
    456                          try:
    457                                  if self._payload[self._idx[attribute]] != value:
    458                                          self._payload[self._idx[attribute]] = value
    459                                          self._is_modified = True
    460                                  return
    461                          except KeyError:
    462                                  _log.warning('[%s]: cannot set attribute <%s> despite marked settable' % (self.__class__.__name__, attribute))
    463                                  _log.warning('[%s]: supposedly settable attributes: %s' % (self.__class__.__name__, str(self.__class__._updatable_fields)))
    464                                  raise KeyError('[%s]: cannot write to key [%s]' % (self.__class__.__name__, attribute))
    465
    466                  # 2) setters providing extensions
    467                  if hasattr(self, 'set_%s' % attribute):
    468                          setter = getattr(self, "set_%s" % attribute)
    469                          if not callable(setter):
    470                                  raise AttributeError('[%s] setter [set_%s] not callable' % (self.__class__.__name__, attribute))
    471                          try:
    472                                  del self._ext_cache[attribute]
    473                          except KeyError:
    474                                  pass
    475                          if type(value) == tuple:
    476                                  if setter(*value):
    477                                          self._is_modified = True
    478                                          return
    479                                  raise AttributeError('[%s]: setter [%s] failed for [%s]' % (self.__class__.__name__, setter, value))
    480                          if setter(value):
    481                                  self._is_modified = True
    482                                  return
    483
    484                  # 3) don't know what to do with <attribute>
    485                  _log.error('[%s]: cannot find attribute <%s> or setter method [set_%s]' % (self.__class__.__name__, attribute, attribute))
    486                  _log.warning('[%s]: settable attributes: %s' % (self.__class__.__name__, str(self.__class__._updatable_fields)))
    487                  methods = [ m for m in inspect.getmembers(self, inspect.ismethod) if m[0].startswith('set_') ]
    488                  _log.warning('[%s]: valid setter methods: %s' % (self.__class__.__name__, str(methods)))
    489                  raise AttributeError('[%s]: cannot set [%s]' % (self.__class__.__name__, attribute))
    490
    491          #--------------------------------------------------------
    492          # external API
    493          #--------------------------------------------------------
    494 -        def same_payload(self, another_object=None):
    495                  raise NotImplementedError('comparison between [%s] and [%s] not implemented' % (self, another_object))
    496
    497          #--------------------------------------------------------
    498 -        def is_modified(self):
    499                  return self._is_modified
    500
    501          #--------------------------------------------------------
    502 -        def get_fields(self):
    503                  try:
    504                          return self._idx.keys()
    505                  except AttributeError:
    506                          return 'nascent [%s @ %s], cannot return keys' %(self.__class__.__name__, id(self))
    507
    508          #--------------------------------------------------------
    509 -        def get_updatable_fields(self):
    510                  return self.__class__._updatable_fields
    511
    512          #--------------------------------------------------------
    513 -        def fields_as_dict(self, date_format='%Y %b %d  %H:%M', none_string='', escape_style=None, bool_strings=None):
    514                  if bool_strings is None:
    515                          bools = {True: 'True', False: 'False'}
    516                  else:
    517                          bools = {True: bool_strings[0], False: bool_strings[1]}
    518                  data = {}
    519                  for field in self._idx.keys():
    520                          # FIXME: harden against BYTEA fields
    521                          #if type(self._payload[self._idx[field]]) == ...
    522                          #       data[field] = _('<%s bytes of binary data>') % len(self._payload[self._idx[field]])
    523                          #       continue
    524                          val = self._payload[self._idx[field]]
    525                          if val is None:
    526                                  data[field] = none_string
    527                                  continue
    528                          if isinstance(val, bool):
    529                                  data[field] = bools[val]
    530                                  continue
    531
    532                          if isinstance(val, datetime.datetime):
    533                                  if date_format is None:
    534                                          data[field] = val
    535                                          continue
    536                                  data[field] = pydt_strftime(val, format = date_format)
    537                                  if escape_style in ['latex', 'tex']:
    538                                          data[field] = tex_escape_string(data[field])
    539                                  elif escape_style in ['xetex', 'xelatex']:
    540                                          data[field] = xetex_escape_string(data[field])
    541                                  continue
    542
    543                          try:
    544                                  data[field] = str(val, encoding = 'utf8', errors = 'replace')
    545                          except TypeError:
    546                                  try:
    547                                          data[field] = str(val)
    548                                  except (UnicodeDecodeError, TypeError):
    549                                          val = '%s' % str(val)
    550                                          data[field] = val.decode('utf8', 'replace')
    551                          if escape_style in ['latex', 'tex']:
    552                                  data[field] = tex_escape_string(data[field])
    553                          elif escape_style in ['xetex', 'xelatex']:
    554                                  data[field] = xetex_escape_string(data[field])
    555
    556                  return data
    557
    558          #--------------------------------------------------------
    559 -        def get_patient(self):
    560                  _log.error('[%s:%s]: forgot to override get_patient()' % (self.__class__.__name__, self.pk_obj))
    561                  return None
    562
    563          #--------------------------------------------------------
    564 -        def _get_staff_id(self):
    565                  try:
    566                          return self._payload[self._idx['pk_staff']]
    567                  except KeyError:
    568                          _log.debug('[%s]: .pk_staff should be added to the view', self.__class__.__name__)
    569                  try:
    570                          return self._payload[self._idx['pk_provider']]
    571                  except KeyError:
    572                          pass
    573                  mod_by = None
    574                  try:
    575                          mod_by = self._payload[self._idx['modified_by_raw']]
    576                  except KeyError:
    577                          _log.debug('[%s]: .modified_by_raw should be added to the view', self.__class__.__name__)
    578                  if mod_by is not None:
    579                          # find by DB account
    580                          args = {'db_u': mod_by}
    581                          cmd = "SELECT pk FROM dem.staff WHERE db_user = %(db_u)s"
    582                          rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
    583                          if len(rows) > 0:
    584                                  # logically, they are all the same provider, because they share the DB account
    585                                  return rows[0][0]
    586
    587                  mod_by = self._payload[self._idx['modified_by']]
    588                  # is .modified_by a "<DB-account>" ?
    589                  if mod_by.startswith('<') and mod_by.endswith('>'):
    590                          # find by DB account
    591                          args = {'db_u': mod_by.lstrip('<').rstrip('>')}
    592                          cmd = "SELECT pk FROM dem.staff WHERE db_user = %(db_u)s"
    593                          rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
    594                          if len(rows) > 0:
    595                                  # logically, they are all the same provider, because they share the DB account
    596                                  return rows[0][0]
    597
    598                  # .modified_by is probably dem.staff.short_alias
    599                  args = {'alias': mod_by}
    600                  cmd = "SELECT pk FROM dem.staff WHERE short_alias = %(alias)s"
    601                  rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': args}], get_col_idx = False)
    602                  if len(rows) > 0:
    603                          # logically, they are all the same provider, because they share the DB account
    604                          return rows[0][0]
    605
    606                  _log.error('[%s]: cannot retrieve staff ID for [%s]', self.__class__.__name__, mod_by)
    607                  return None
    608
    609          staff_id = property(_get_staff_id)
    610
    611          #--------------------------------------------------------
    612 -        def format(self, *args, **kwargs):
    613                  return format_dict_like (
    614                          self.fields_as_dict(none_string = '<?>'),
    615                          tabular = True,
    616                          value_delimiters = None
    617                  ).split('\n')
    618
    619          #--------------------------------------------------------
    620 -        def _get_revision_history(self, query, args, title):
    621                  rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': query, 'args': args}], get_col_idx = True)
    622
    623                  lines = []
    624                  if rows == 0:
    625                          lines.append('%s (no versions)' % title)
    626                  else:
    627                          lines.append('%s (%s versions)' % (title, rows[0]['row_version'] + 1))
    628                          headers = [ 'rev %s (%s)' % (r['row_version'], pydt_strftime(r['audit__action_when'], format = '%Y %b %d %H:%M', none_str = 'live row')) for r in rows ]
    629                          lines.extend (dicts2table (
    630                                  rows,
    631                                  left_margin = 1,
    632                                  eol = None,
    633                                  keys2ignore = ['audit__action_when', 'row_version', 'pk_audit'],
    634                                  show_only_changes = True,
    635                                  headers = headers,
    636                                  date_format = '%Y %b %d %H:%M',
    637                                  equality_value = u_left_arrow
    638                          ))
    639                  return lines
    640
    641          #--------------------------------------------------------
    642 -        def refetch_payload(self, ignore_changes=False, link_obj=None):
    643                  """Fetch field values from backend."""
    644                  if self._is_modified:
    645                          compare_dict_likes(self.original_payload, self.fields_as_dict(date_format = None, none_string = None), 'original payload', 'modified payload')
    646                          if ignore_changes:
    647                                  _log.critical('[%s:%s]: loosing payload changes' % (self.__class__.__name__, self.pk_obj))
    648                                  #_log.debug('most recently fetched: %s' % self.payload_most_recently_fetched)
    649                                  #_log.debug('modified: %s' % self._payload)
    650                          else:
    651                                  _log.critical('[%s:%s]: cannot reload, payload changed' % (self.__class__.__name__, self.pk_obj))
    652                                  return False
    653
    654                  if isinstance(self.pk_obj, dict):
    655                          args = self.pk_obj
    656                  else:
    657                          args = [self.pk_obj]
    658                  rows, self._idx = gmPG2.run_ro_queries (
    659                          link_obj = link_obj,
    660                          queries = [{'cmd': self.__class__._cmd_fetch_payload, 'args': args}],
    661                          get_col_idx = True
    662                  )
    663                  if len(rows) == 0:
    664                          _log.error('[%s:%s]: no such instance' % (self.__class__.__name__, self.pk_obj))
    665                          return False
    666                  if len(rows) > 1:
    667                          raise AssertionError('[%s:%s]: %s instances !' % (self.__class__.__name__, self.pk_obj, len(rows)))
    668                  self._payload = rows[0]
    669                  return True
    670
    671          #--------------------------------------------------------
    672 -        def __noop(self):
    673                  pass
    674
    675          #--------------------------------------------------------
    676 -        def save(self, conn=None):
    677                  return self.save_payload(conn = conn)
    678
    679          #--------------------------------------------------------
    680 -        def save_payload(self, conn=None):
    681                  """Store updated values (if any) in database.
    682
    683                  Optionally accepts a pre-existing connection
    684                  - returns a tuple (<True|False>, <data>)
    685                  - True: success
    686                  - False: an error occurred
    687                          * data is (error, message)
    688                          * for error meanings see gmPG2.run_rw_queries()
    689                  """
    690                  if not self._is_modified:
    691                          return (True, None)
    692
    693                  args = {}
    694                  for field in self._idx.keys():
    695                          args[field] = self._payload[self._idx[field]]
    696                  self.payload_most_recently_attempted_to_store = args
    697
    698                  close_conn = self.__noop
    699                  if conn is None:
    700                          conn = gmPG2.get_connection(readonly=False)
    701                          close_conn = conn.close
    702
    703                  queries = []
    704                  for query in self.__class__._cmds_store_payload:
    705                          queries.append({'cmd': query, 'args': args})
    706                  rows, idx = gmPG2.run_rw_queries (
    707                          link_obj = conn,
    708                          queries = queries,
    709                          return_data = True,
    710                          get_col_idx = True
    711                  )
    712
    713                  # success ?
    714                  if len(rows) == 0:
    715                          # nothing updated - this can happen if:
    716                          # - someone else updated the row so XMIN does not match anymore
    717                          # - the PK went away (rows were deleted from under us)
    718                          # - another WHERE condition of the UPDATE did not produce any rows to update
    719                          # - savepoints are used since subtransactions may relevantly change the xmin/xmax ...
    720                          return (False, ('cannot update row', _('[%s:%s]: row not updated (nothing returned), row in use ?') % (self.__class__.__name__, self.pk_obj)))
    721
    722                  # update cached values from should-be-first-and-only
    723                  # result row of last query,
    724                  # update all fields returned such that computed
    725                  # columns see their new values (given they are
    726                  # returned by the query)
    727                  row = rows[0]
    728                  for key in idx:
    729                          try:
    730                                  self._payload[self._idx[key]] = row[idx[key]]
    731                          except KeyError:
    732                                  conn.rollback()
    733                                  close_conn()
    734                                  _log.error('[%s:%s]: cannot update instance, XMIN refetch key mismatch on [%s]' % (self.__class__.__name__, self.pk_obj, key))
    735                                  _log.error('payload keys: %s' % str(self._idx))
    736                                  _log.error('XMIN refetch keys: %s' % str(idx))
    737                                  _log.error(args)
    738                                  raise
    739
    740                  # only at conn.commit() time will data actually
    741                  # get committed (and thusly trigger based notifications
    742                  # be sent out), so reset the local modification flag
    743                  # right before that
    744                  self._is_modified = False
    745                  conn.commit()
    746                  close_conn()
    747
    748                  # update to new "original" payload
    749                  self.payload_most_recently_fetched = {}
    750                  for field in self._idx.keys():
    751                          self.payload_most_recently_fetched[field] = self._payload[self._idx[field]]
    752
    753                  return (True, None)
    754
    755  #============================================================
    756  if __name__ == '__main__':
    757
    758          if len(sys.argv) < 2:
    759                  sys.exit()
    760
    761          if sys.argv[1] != 'test':
    762                  sys.exit()
    763
    764          #--------------------------------------------------------
    765 -        class cTestObj(cBusinessDBObject):
    766                  _cmd_fetch_payload = None
    767                  _cmds_store_payload = None
    768                  _updatable_fields = []
    769                  #----------------------------------------------------
    770 -                def get_something(self):
    771                          pass
    772                  #----------------------------------------------------
    773 -                def set_something(self):
    774                          pass
    775          #--------------------------------------------------------
    776          from Gnumed.pycommon import gmI18N
    777          gmI18N.activate_locale()
    778          gmI18N.install_domain()
    779
    780          data = {
    781                  'pk_field': 'bogus_pk',
    782                  'idx': {'bogus_pk': 0, 'bogus_field': 1, 'bogus_date': 2},
    783                  'data': [-1, 'bogus_data', datetime.datetime.now()]
    784                  #'data': {'bogus_pk': -1, 'bogus_field': 'bogus_data', 'bogus_date': datetime.datetime.now()}
    785          }
    786          obj = cTestObj(row=data)
    787          print(obj.format())
    788          #print(obj['wrong_field'])
    789          #obj['wrong_field'] = 1
    790          print(obj.fields_as_dict())
    791
    792  #============================================================
    793