def _insert_namespace_properties(self, uuid, name, properties): self._validate_namespace_properties(name, properties) assert (uuid is not None and getattr(properties, "uuid", uuid) == uuid) # Split the properties into a list of (database) field names and a list of values. This assumes the database # field that corresponds to a given property has the same name. If the backend uses different field names, the # required translation can be performed here. Values can also be translated if necessary. properties_dict = vars(properties) fields, parameters = dictkeys(properties_dict), dictvalues( properties_dict) # Ensure the uuid field is present (for namespaces other than the core namespace this is used as the foreign # key). if "uuid" not in properties: fields.append("uuid") parameters.append(uuid) # Build and execute INSERT query. query = "INSERT INTO %s (%s) VALUES (%s)" % ( self._table_name(name), ", ".join(fields), ", ".join( [self._placeholder()] * len(fields))) cursor = self._connection.cursor() try: cursor.execute(query, parameters) finally: cursor.close()
def _update_namespace_properties(self, uuid, name, properties): self._validate_namespace_properties(name, properties, partial=True) assert uuid is not None and getattr(properties, "uuid", uuid) == uuid # Split the properties into a list of (database) field names and a list of values. This assumes the database # field that corresponds to a given property has the same name. If the backend uses different field names, the # required translation can be performed here. Values can also be translated if necessary. properties_dict = vars(properties) fields, parameters = dictkeys(properties_dict), dictvalues( properties_dict) if not fields: return # nothing to do # Remove the uuid field if present. This field needs to be included in the WHERE clause of the UPDATE query, # not in the SET clause. try: uuid_index = fields.index("uuid") except ValueError: pass else: del fields[uuid_index] del parameters[uuid_index] # Append the uuid (value) at the end of the list of parameters (will be used in the WHERE clause). parameters.append(uuid) parameters = [ json.dumps(p) if isinstance(p, dict) else p for p in parameters ] # Build and execute UPDATE query. set_clause = ", ".join( ["%s = %s" % (field, self._placeholder()) for field in fields]) query = "UPDATE %s SET %s WHERE uuid = %s" % ( self._table_name(name), set_clause, self._placeholder()) cursor = self._connection.cursor() try: cursor.execute(query, parameters) assert cursor.rowcount <= 1 if cursor.rowcount != 1: raise Error( "could not update properties for namespace: %s for product: %s" % (name, uuid)) finally: cursor.close()