def _insert_into_db(self, data): em = EntityManager() db = em.get_db() # create placeholders for the data columns, values = self._get_sql_data(data) assert len(columns) == len(values) column_string = "" value_string = "" for c, v in zip(columns, values): value_string += v + ", " column_string += c + ", " value_string = value_string[:-2] #remove trailing comma column_string = column_string[:-2] #remove trailing comma sql = "INSERT INTO `{}`({}) VALUES({});".format( self.table_name, column_string, value_string) logging.debug("Using db: %s", db.database) cursor = db.cursor() logging.debug("EXECUTING SQL: %s", sql) logging.debug("DATA FROM MODEL: %s", data) cursor.execute(sql, data) db.commit() if cursor.rowcount > 0: # set the id, now the class exists! self._key = cursor.lastrowid return True else: raise Exception("Unable to insert in db")
def db(self): """ Turns out singletons can't get accessed on init of a class So simple hack, creating a property that accesses the singleton and getting the wanted property """ em = EntityManager() db = em.get_db() return db
def _get_sql_data(self, data): """ returns tuple with (columns, values) """ em = EntityManager() db = em.get_db() config = Config() charset = config.db.charset if "charset" in config.db.keys( ) else "utf8" converter = MySQLConverter(charset) def none_to_null(val): if val is None: return "NULL" return val def quote(val): if isinstance(val, NUMERIC_TYPES): return str(val) return "'" + val + "'" def quote_col(val): return "`" + val + "`" _escape_value = compose(none_to_null, quote, converter.escape) _escape_column = compose( none_to_null, quote_col, converter.escape) #column quting is different than normal quotes if self.key_name not in data.keys( ) and self.key is not None: #add the key to the data data[self.key_name] = self.key columns = list() values = list() for k, v in data.items(): values.append(_escape_value(v)) columns.append(_escape_column(k)) return (columns, values)