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

Class cBusinessDBObject

source code

object --+
         |
        cBusinessDBObject
Known Subclasses:

Represents business objects in the database.

        Rules:
        - instances ARE ASSUMED TO EXIST in the database
        - PK construction (aPK_obj): DOES verify its existence on instantiation
                                     (fetching data fails)
        - Row construction (row): allowed by using a dict of pairs
                                       field name: field value (PERFORMANCE improvement)
        - does NOT verify FK target existence
        - does NOT create new entries in the database
        - does NOT lazy-fetch fields on access

        Class scope SQL commands and variables:

        <_cmd_fetch_payload>
                - must return exactly one row
                - where clause argument values are expected
                  in self.pk_obj (taken from __init__(aPK_obj))
                - must return xmin of all rows that _cmds_store_payload
                  will be updating, so views must support the xmin columns
                  of their underlying tables

        <_cmds_store_payload>
                - one or multiple "update ... set ... where xmin_* = ..." statements
                  which actually update the database from the data in self._payload,
                - the last query must refetch at least the XMIN values needed to detect
                  concurrent updates, their field names had better be the same as
                  in _cmd_fetch_payload,
                - when subclasses tend to live a while after save_payload() was
                  called and they support computed fields (say, _(some_column)
                  you need to return *all* columns (see cEncounter)

        <_updatable_fields>
                - a list of fields available for update via object['field']


        A template for new child classes:

*********** start of template ***********

#------------------------------------------------------------
from Gnumed.pycommon import gmBusinessDBObject
from Gnumed.pycommon import gmPG2

#============================================================
# short description
#------------------------------------------------------------
# use plural form, search-replace get_XXX
_SQL_get_XXX = u"""
        SELECT *, (xmin AS xmin_XXX)
        FROM XXX.v_XXX
        WHERE %s
"""

class cXxxXxx(gmBusinessDBObject.cBusinessDBObject):
        """Represents ..."""

        _cmd_fetch_payload = _SQL_get_XXX % u"pk_XXX = %s"
        _cmds_store_payload = [
                u"""
                        -- typically the underlying table name
                        UPDATE xxx.xxx SET
                                -- typically "table_col = %(view_col)s"
                                xxx = %(xxx)s,
                                xxx = gm.nullify_empty_string(%(xxx)s)
                        WHERE
                                pk = %(pk_XXX)s
                                        AND
                                xmin = %(xmin_XXX)s
                        RETURNING
                                pk as pk_XXX,
                                xmin as xmin_XXX
                """
        ]
        # view columns that can be updated:
        _updatable_fields = [
                u'xxx',
                u'xxx'
        ]
        #--------------------------------------------------------
        def format(self):
                return u'%s' % self

#------------------------------------------------------------
def get_XXX(order_by=None):
        if order_by is None:
                order_by = u'true'
        else:
                order_by = u'true ORDER BY %s' % order_by

        cmd = _SQL_get_XXX % order_by
        rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd}], get_col_idx = True)
        return [ cXxxXxx(row = {'data': r, 'idx': idx, 'pk_field': 'xxx'}) for r in rows ]
#------------------------------------------------------------
def create_xxx(xxx=None, xxx=None):

        args = {
                u'xxx': xxx,
                u'xxx': xxx
        }
        cmd = u"""
                INSERT INTO xxx.xxx (
                        xxx,
                        xxx,
                        xxx
                ) VALUES (
                        %(xxx)s,
                        %(xxx)s,
                        gm.nullify_empty_string(%(xxx)s)
                )
                RETURNING pk
        """
        rows, idx = gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}], return_data = True, get_col_idx = False)

        return cXxxXxx(aPK_obj = rows[0]['pk'])
#------------------------------------------------------------
def delete_xxx(xxx=None):
        args = {'pk': xxx}
        cmd = u"DELETE FROM xxx.xxx WHERE pk = %(pk)s"
        gmPG2.run_rw_queries(queries = [{'cmd': cmd, 'args': args}])
        return True
#------------------------------------------------------------

*********** end of template ***********

        

Instance Methods
 
__del__(self) source code
 
__getitem__(self, attribute) source code
 
__init__(self, aPK_obj=None, row=None)
Init business object.
source code
 
__setitem__(self, attribute, value) source code
 
__str__(self)
str(x)
source code
 
fields_as_dict(self, date_format='%c', none_string=u'', escape_style=None, bool_strings=None) source code
 
format(self) source code
 
get_fields(self) source code
 
get_patient(self) source code
 
get_updatable_fields(self) source code
 
is_modified(self) source code
 
refetch_payload(self, ignore_changes=False)
Fetch field values from backend.
source code
 
same_payload(self, another_object=None) source code
 
save(self, conn=None) source code
 
save_payload(self, conn=None)
Store updated values (if any) in database.
source code

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __subclasshook__

Properties

Inherited from object: __class__

Method Details

__init__(self, aPK_obj=None, row=None)
(Constructor)

source code 
Init business object.

Call from child classes:

        super(cChildClass, self).__init__(aPK_obj = aPK_obj, row = row)

Overrides: object.__init__

__str__(self)
(Informal representation operator)

source code 

str(x)

Overrides: object.__str__
(inherited documentation)

save_payload(self, conn=None)

source code 
Store updated values (if any) in database.

Optionally accepts a pre-existing connection
- returns a tuple (<True|False>, <data>)
- True: success
- False: an error occurred
        * data is (error, message)
        * for error meanings see gmPG2.run_rw_queries()