Example #1
0
    def save(self):
        if self.data.has_key('uid') and self.data['uid']:
            return self._update()
        # validate the data in the object
        # Note this only runs if self.VALIDATION is set
        self.validate()
        # is there a defined unique_key? if so check only for those fields
        if 'UNIQUE_KEY' in dir(self):
            values = []
            for k, v in self.data.items():
                if k in self.UNIQUE_KEY:
                    # don't pass null values
                    if v != None:
                        values.append(
                            str(k) + "='" + dbConnect.escape(str(v)) + "'")
                    else:
                        values.append(str(k) + "=NULL")
        else:
            # is there an exact duplcate of this record
            # by exact we mean everything but a creation_date
            # already in the table?
            values = []
            for k, v in self.data.items():
                if k != 'uid':
                    if k != 'creation_date':
                        # don't pass null values
                        if v != None:
                            values.append(
                                str(k) + "='" + dbConnect.escape(str(v)) + "'")
                        else:
                            values.append(str(k) + "=NULL")
        sql = "SELECT uid FROM %s WHERE %s ORDER BY uid DESC LIMIT 1" % (
            self.db_table(), ' and '.join(values))
        records = dbConnect.query_connection(self.db_connection_name(), sql)
        for row in records:
            self.data['uid'] = row['uid']
            return

        # if not, create the record
        self._create()
        return
Example #2
0
 def _create(self):
     attrs = []
     values = []
     for k, v in self.data.items():
         if k != 'uid':
             attrs.append(str(k))
             if v == 'now()':
                 now = dateutil.mysql_now()
                 values.append("'" + dbConnect.escape(str(now)) + "'")
             elif v != None:
                 values.append("'" + dbConnect.escape(str(v)) + "'")
             else:
                 values.append("NULL")
     sql = "INSERT INTO %s (%s) VALUES (%s)" % (
         self.db_table(), ','.join(attrs), ','.join(values))
     log.info("_CREATE: %s" % (sql))
     cursor = dbConnect.query_connection(self.db_connection_name(), sql)
     # if id is passed in then assume we aren't dealing with auto-increment
     uid = cursor.lastrowid
     self.data['uid'] = uid
     self._is_new = False
Example #3
0
 def _update(self):
     valid = self.validate()
     values = []
     for k, v in self.data.items():
         if k != 'uid':
             # don't pass null values
             if v != None:
                 values.append(
                     str(k) + "='" + dbConnect.escape(str(v)) + "'")
             else:
                 values.append(str(k) + "=NULL")
     sql = "UPDATE %s SET %s WHERE uid='%s'" % (
         self.db_table(), ','.join(values), self.data['uid'])
     log.info(sql)
     dbConnect.query_connection(self.db_connection_name(), sql)
Example #4
0
 def update(self, **kwargs):
     if not self.data.has_key('uid') or not self.data['uid']:
         raise ORMException, "Record cannot be updated: missing uid"
     values = []
     for k, v in kwargs.iteritems():
         if k != 'uid':
             # don't pass null values
             if v != None:
                 values.append(
                     str(k) + "='" + dbConnect.escape(str(v)) + "'")
             else:
                 values.append(str(k) + "=NULL")
     sql = "UPDATE %s SET %s WHERE uid='%s'" % (
         self.db_table(), ','.join(values), self.data['uid'])
     log.info(sql)
     dbConnect.query_connection(self.db_connection_name(), sql)
Example #5
0
    def find(cls, **kwargs):
        """
		Any class that extends this must not use the following attributes
		order_by, limit, offset as these are key words reserved for DB lookups
		"""
        if kwargs:
            where_conditions = []
            limit = ''
            orderby = ''
            offset = ''
            case_sense = ''
            for k in kwargs:
                if k == 'limit':
                    if kwargs[k] == 'last':
                        limit = "LIMIT 1"
                        orderby = "ORDER BY uid desc"
                    else:
                        limit = "LIMIT " + str(kwargs[k])
                elif k == 'case_sensitive':
                    case_sense = 'COLLATE latin1_bin'
                elif k == 'offset':
                    offset = "OFFSET " + str(kwargs[k])
                elif k == 'order_by' and not orderby:
                    order_by_list = []
                    # convert string to list so that we don't have to repeat ourselves
                    if isinstance(kwargs[k], str):
                        fields = [kwargs[k]]
                    else:
                        fields = kwargs[k]
                    for order_by_val in fields:
                        sort_order = "ASC"
                        if order_by_val.find('-') == 0:
                            sort_order = "DESC"
                            order_by_val = order_by_val.lstrip('-')
                        order_by_list.append("%s %s" %
                                             (order_by_val, sort_order))
                    orderby = "ORDER BY %s" % (", ".join(order_by_list))
                else:
                    if isinstance(kwargs[k], list) and len(kwargs[k]):
                        vals = []
                        for v in kwargs[k]:
                            vals.append("'" + dbConnect.escape(str(v)) + "'")
                        where_conditions.append(k + " IN (" + ",".join(vals) +
                                                ")")
                    elif kwargs[k] == 'NULL':
                        where_conditions.append(
                            k + " is " + dbConnect.escape(str(kwargs[k])))
                    elif kwargs[k] != None:
                        where_conditions.append(
                            k + "='" + dbConnect.escape(str(kwargs[k])) + "'")
            where = ''
            if len(where_conditions):
                where = "WHERE %s" % (" AND ".join(where_conditions))
            where = "%s %s %s %s %s" % (where, orderby, limit, offset,
                                        case_sense)
        else:
            where = ''

        sql = " ".join(["SELECT * FROM", cls.db_table(), where])
        log.info(sql)
        return cls._execute_select(sql)