Source

Portfolio / trike / src / loader / element / element.py

Full commit
class Element(object):
    def __init__(self):
        self.version = '0.1'

    def save(self, attributes, db, conn, table, xmlfile_id):
        '''Make sure we have an xmlfile id associated with the request.'''
        if xmlfile_id is None:
            raise Exception("You need to indicate which xml file this element \
                             belongs to before you can save it.")

        '''We expect a dict of attributes matched to columns.'''
        if type(attributes) is not dict:
            raise Exception("Saving an element requires a dictionary of \
                             attributes.")  

        ## Gemerate the insert statement for the element 
        '''
            We rely on a particular format for the dictionary:
                {element_table :
                    {column : value},
                    {column : value},
                    ...
                }
        '''

        from _mysql import escape_string
        query = "insert into " + table + " set xml_id = '" + str(xmlfile_id) + "',"

        max_keys = len(attributes.keys())
        count = 0
        for key in attributes.keys():
            count = count + 1
            value = attributes[key]
            if value is None or "":
                value = ""
                
            ## NOTE: We need to accomodate for database conversion of attributes
            if key == "id":
                key = "_id"

            ## NOTE: default is a reserved word so we have to adjust the column
            ##       name to _default
            if key == "default":
                key = "_default"

            ## NOTE: restrict is a reserved word so we have to adjust the column
            ##       name to _restrict
            if key == "restrict":
                key = "_restrict"

            ## BUG: Attempt to replace extraneous single quotes
            #value = value.replace("\'","")

            if count == max_keys:
                query = query + key + "='" + escape_string(value) + "';"
            else:
                query = query + key + "='" + escape_string(value) + "',"
            
        try:
            db.execute(query)
            conn.commit( )
        except Exception as queryerror:
            print "ERROR: Could not save element."
            print query
            print queryerror