Save entity attributes to database
506847
public function save()
    {
        $objectHash = spl_object_hash($this);
        if (array_key_exists($objectHash, self::$saved)) {
            return true;
        }

        self::$saved[$objectHash] = true;

        $data = [];
        $validation = [];
        $one2many = AttributeType::ONE2MANY;
        $many2many = AttributeType::MANY2MANY;
        /* @var $attr AbstractAttribute */
        foreach ($this->getAttributes() as $key => $attr) {
            if ($attr->isRequired() && !$attr->hasValue()) {
                $ex = new ValidationException(ValidationException::VALIDATION_FAILED);
                $ex->addError($key, ValidationException::REQUIRED);
                $validation[$key] = $ex;
                continue;
            }

            if (!count($validation) && !$this->isInstanceOf($attr, $one2many) && !$this->isInstanceOf($attr, $many2many)) {
                if ($attr->getStoreToDb()) {
                    $data[$key] = $attr->getDbValue();
                }
            }
        }

        // Throw EntityException with invalid attributes
        if (count($validation)) {
            $attributes = [];
            foreach ($validation as $attr => $error) {
                foreach ($error as $key => $value) {
                    $attributes[$key] = $value;
                }
            }
            $ex = new EntityException(EntityException::VALIDATION_FAILED, [get_class($this), count($validation)]);
            $ex->setInvalidAttributes($attributes);
            throw $ex;
        }

        /**
         * Insert or update
         */
        $mongo = $this->entity()->getDatabase();
        if (!$this->exists()) {
            $data['_id'] = $mongo->isId($data['id']) ? $mongo->id($data['id']) : $mongo->id();
            $data['id'] = (string)$data['_id'];
            $mongo->insertOne(static::$collection, $data);
            $this->id = $data['id'];
        } else {
            $where = ['_id' => $mongo->id($this->id)];
            $mongo->update(static::$collection, $where, ['$set' => $data], ['upsert' => true]);
        }

        /**
         * Now save One2Many values
         */
        foreach ($this->getAttributes() as $attr) {
            /* @var $attr One2ManyAttribute */
            if ($this->isInstanceOf($attr, AttributeType::ONE2MANY) && $attr->isLoaded()) {
                foreach ($attr->getValue() as $item) {
                    $item->getAttribute($attr->getRelatedAttribute())->setValue($this);
                    $item->save();
                }
                /**
                 * The value of one2many attribute must be set to null to trigger data reload on next access.
                 * This is necessary when we have circular references, and parent record does not get it's many2one ID saved
                 * until all child referenced objects are saved. Only then can we get proper links between referenced classes.
                 */
                $attr->setValue(null, true);
            }
        }

        /**
         * Now save Many2Many values
         */
        foreach ($this->getAttributes() as $attr) {
            /* @var $attr Many2ManyAttribute */
            if ($this->isInstanceOf($attr, AttributeType::MANY2MANY)) {
                $attr->save();
            }
        }

        // Now that this entity is saved, remove it from save log
        unset(self::$saved[$objectHash]);

        return true;
    }
833845
public function save()
    {
        $collectionName = $this->intermediateCollection;

        $existingIds = [];
        $firstEntityId = $this->getParentEntity()->id;
        foreach ($this->getValue() as $item) {
            if ($item instanceof AbstractEntity && !$item->exists()) {
                $item->save();
            }

            if ($item instanceof AbstractEntity) {
                $secondEntityId = $item->id;
            } else {
                $secondEntityId = $item;
            }

            $existingIds[] = $secondEntityId;

            $data = [
                $this->thisField => $firstEntityId,
                $this->refField  => $secondEntityId
            ];

            try {
                Entity::getInstance()->getDatabase()->insertOne($collectionName, $this->arr($data)->sortKey()->val());
            } catch (BulkWriteException $e) {
                // Unique index was hit and an exception is thrown - that's ok, means the values are already inserted
                continue;
            }
        }

        /**
         * Remove old links
         */
        $removeQuery = [
            $this->thisField => $firstEntityId,
            $this->refField  => [
                '$nin' => $existingIds
            ]
        ];
        Entity::getInstance()->getDatabase()->delete($collectionName, $removeQuery);

        /**
         * The value of many2many attribute must be set to 'null' to trigger data reload on next access.
         * If this is not done, we may not have proper links between the 2 entities and it may seem as if data was missing.
         */
        $this->setValue(null);
    }
88376
public function save() {

		if (empty(static::$table))
			$table = strtolower(substr(static::table(), strpos(static::table(), '\\')+1));
		else
			$table = static::$table;

		if (isset($this->_data[$table]) && count($this->_data[$table]) <= 0 ) {
			$post = $_POST;
			while(list($field, $value) = each($post)) {
				// Next if is Primary Keys
				// if (!empty($this->_id) && array_key_exists($field, $this->_id))
					// continue;
				
				$this->_data[$table][$field] = addslashes($value);
				$this->$field = $value;
			}
		}

		if ($table != '') {
			// Untuk menambah record
			if ($this->add == TRUE) {
				$before = $this->before();
				if (is_array($before) && count($before) > 1) {
					if (isset($before['insert'])) {
						$insert = $before['insert'];
						while(list($field, $value) = each($insert))
							$this->_data[$table][$field] = $value;
					}
				}
				$ret = self::$db->$table->insert($this->_data[$table]);
				$after = $this->after();
				if (is_array($after) && count($after) > 1) {
					if (isset($after['insert']) && is_callable($after['insert'])) {
						$insert = $after['insert'];
						$insert($this->_data[$table]);
					}
				}
			}
			// Untuk mengupdate record
			else {
				$before = $this->before();
				if (is_array($before) && count($before) > 1) {
					if (isset($before['update'])) {
						$update = $before['update'];
						while(list($field, $value) = each($update))
							$this->_data[$table][$field] = $value;
					}
				}
				$ret = self::$db->$table->update($this->_id, $this->_data[$table]);
				$after = $this->after();
				if (is_array($after) && count($after) > 1) {
					if (isset($after['update']) && is_callable($after['update'])) {
						$update = $after['update'];
						$update(array('pk'=>$this->_id, 'data'=>$this->_data[$table]));
					}
				}
			}
			
			$this->_data[$table] = array();
		}

		
		return $ret;
	}
260324
def _WriteAttributes(self):
    """"""
    # If the object is not opened for writing we do not need to flush it to the
    # data_store.
    if "w" not in self.mode:
      return

    if self.urn is None:
      raise ValueError("Storing of anonymous AFF4 objects not supported.")

    to_set = {}
    for attribute_name, value_array in iteritems(self.new_attributes):
      to_set_list = to_set.setdefault(attribute_name, [])
      for value in value_array:
        to_set_list.append((value.SerializeToDataStore(), value.age))

    if self._dirty:
      # We determine this object has a new version only if any of the versioned
      # attributes have changed. Non-versioned attributes do not represent a new
      # object version. The type of an object is versioned and represents a
      # version point in the life of the object.
      if self._new_version:
        to_set[self.Schema.TYPE] = [
            (utils.SmartUnicode(self.__class__.__name__),
             rdfvalue.RDFDatetime.Now())
        ]

      # We only update indexes if the schema does not forbid it and we are not
      # sure that the object already exists.
      add_child_index = self.Schema.ADD_CHILD_INDEX
      if self.object_exists:
        add_child_index = False

      # Write the attributes to the Factory cache.
      FACTORY.SetAttributes(
          self.urn,
          to_set,
          self._to_delete,
          add_child_index=add_child_index,
          mutation_pool=self.mutation_pool)
90075
def get_base_attributes(entity):
    
    attributes = {}
    cls = entity.__class__
    for attr, _ in inspect.getmembers(cls, lambda o: not isinstance(o, property) and not inspect.isroutine(o)):
        if not attr.startswith("_"):
            attributes[attr] = getattr(entity, attr)
    return attributes
150137
public function saveKeyValues(Entity $entity, array $keys)
    {
        $event = $this->_table->dispatchEvent('Model.beforeSaveKeyValues', compact('entity'));

        if ($event->isStopped()) {
            return $event->result;
        }

        if (!empty($event->result)) {
            $entity = $event->result;
        }

        $fields = $this->config('fields');

        if ($entity->has($fields['key']) && $entity->has($fields['value'])) {
            return true;
        }

        $mappedIds = $this->_getFieldToIdMapping($keys);

        $entities = [];
        foreach ($entity->toArray() as $key => $value) {
            if ($this->_table->hasField($key)) {
                continue;
            }

            $serialized = false;
            if (in_array($key, $this->config('serializeFields'))) {
                $value = serialize($value);
                $serialized = true;
            }

            /** @var Setting $kvEntity */
            $kvEntity = $this->_table->newEntity([
                'scope' => $this->config('scope'),
                $this->config('fields.key') => $key,
                $this->config('fields.value') => $value,
                'serialized' => $serialized
            ]);

            if (($existingId = Hash::get($mappedIds, $key)) !== null) {
                $kvEntity->id = $existingId;
            }

            $entities[] = $kvEntity;
        }

        $result = $this->_table->connection()->transactional(function () use ($entities) {
            foreach ($entities as $e) {
                $this->_table->save($e);
            }
        });

        return ($result !== false);
    }
877381
public void insertAttributeValueEntity(String attributeName, CmsEntityWrapper value, int index) {

        m_entity.insertAttributeValue(attributeName, value.getEntity(), index);
    }
62427
def save_to_db(model_text_id, parsed_values):
        """"""
        Model = apps.get_model(model_text_id)

        # normalise values and separate to m2m, simple
        simple_fields = {}
        many2many_fields = {}
        for field, value in parsed_values.items():
            if (Model._meta.get_field(
                    field).get_internal_type() == 'ManyToManyField'):
                many2many_fields[field] = value
            elif (Model._meta.get_field(
                    field).get_internal_type() == 'DateTimeField'):
                simple_fields[field] = time_parser.parse(value)

            else:
                simple_fields[field] = value

        # ToDo: add unique identify parameter to field
        # ToDo: allow unique identify m2m field
        model, created = Model.objects.get_or_create(**simple_fields)

        for field, value in many2many_fields.items():
            setattr(model, field, value)
        model.save()

        return model
298501
async def save(self, db=None):
        '''
        
        '''
        self._db = db or self.db
        data = self.prepare_data()
        # validate object
        self.validate()
        # connect to DB to save the model
        for i in self.connection_retries():
            try:
                created = False if '_id' in data else True
                result = await self.db[self.get_collection_name()].insert_one(data)
                self._id = result.inserted_id
                # emit post save
                asyncio.ensure_future(post_save.send(
                    sender=self.__class__,
                    db=self.db,
                    instance=self,
                    created=created)
                )
                break
            except ConnectionFailure as ex:
                exceed = await self.check_reconnect_tries_and_wait(i, 'save')
                if exceed:
                    raise ex
70403
public void insertAttributeValue(String attributeName, CmsEntity value, int index) {

        if (m_entityAttributes.containsKey(attributeName)) {
            m_entityAttributes.get(attributeName).add(index, value);
        } else {
            setAttributeValue(attributeName, value);
        }
        registerChangeHandler(value);
        fireChange();
    }
127765
private void updateColumn(EntityType entityType, Attribute attr, Attribute updatedAttr) {
    // nullable changes
    if (!Objects.equals(attr.isNillable(), updatedAttr.isNillable())) {
      updateNillable(entityType, attr, updatedAttr);
    }

    // unique changes
    if (!Objects.equals(attr.isUnique(), updatedAttr.isUnique())) {
      updateUnique(entityType, attr, updatedAttr);
    }

    // readonly changes
    if (!Objects.equals(attr.isReadOnly(), updatedAttr.isReadOnly())) {
      updateReadonly(entityType, attr, updatedAttr);
    }

    // data type changes
    if (!Objects.equals(attr.getDataType(), updatedAttr.getDataType())) {
      if (updatedAttr.isReadOnly()) {
        dropTableTriggers(entityType);
      }
      updateDataType(entityType, attr, updatedAttr);
      if (updatedAttr.isReadOnly()) {
        createTableTriggers(entityType);
      }
    }

    // ref entity changes
    if (attr.hasRefEntity()
        && updatedAttr.hasRefEntity()
        && !attr.getRefEntity().getId().equals(updatedAttr.getRefEntity().getId())) {
      updateRefEntity(entityType, attr, updatedAttr);
    }

    // enum option changes
    if (!Objects.equals(attr.getEnumOptions(), updatedAttr.getEnumOptions())) {
      updateEnumOptions(entityType, attr, updatedAttr);
    }
  }
335437
def store(self, df, attribute_columns):
        

        # ID start values depend on currently stored entities/attributes!
        entity_id_start = models.Entity.get_max_id(self.session) + 1
        attribute_id_start = models.Attribute.get_max_id(self.session) + 1

        # append ID and type columns
        df['id'] = range(entity_id_start, entity_id_start + len(df))
        df['type'] = self.type

        # store entities
        df[['id', 'type']].to_sql(name=models.Entity.__tablename__,
                                  con=self.client.engine,
                                  if_exists='append',
                                  index=False)

        # store attributes
        for col in attribute_columns:
            # ID column of df is the entity ID of the attribute
            attr_df = df[[col, 'id']].rename(columns={'id': 'entity_id',
                                                      col: 'value'})
            attr_df['name'] = col

            # add entity ID column, need to respect already existing entities
            attr_df['id'] = range(attribute_id_start, attribute_id_start + len(df))
            attribute_id_start += len(df)

            # store
            attr_df.to_sql(name=models.Attribute.__tablename__,
                           con=self.client.engine,
                           if_exists='append',
                           index=False)
581654
public void put_class_attribute_property(Database database, String classname, DbAttribute attr)
            throws DevFailed {
        DbAttribute[] da = new DbAttribute[1];
        da[0] = attr;
        put_class_attribute_property(database, classname, da);
    }
683180
def save(self, obj):
        """"""
        if not obj.id:
            obj.id = uuid()

        index_names = obj.__class__.index_names() or []
        index_dict = obj.indexes() or {}
        index_name_values = [
            (key, index_dict.get(key, ''))
            for key in index_names
        ]

        write_rec(
            obj.__class__.get_table_name(),
            obj.id,
            obj.to_data(),
            index_name_values
        )
540587
public function save()
    {
        $em = Application::getFacadeApplication()->make(EntityManagerInterface::class);
        $em->persist($this);
        $em->flush();
    }
574250
def _saveDB(self):
        """"""
        # We're a "fresh" copy now
        self._updated = time.time()
        if self._new:
            operation = 'INSERT'
        else:
            operation = 'UPDATE'
        (sql, fields) = self._prepareSQL(operation)
        values = []
        for field in fields:
            value = getattr(self, field)
            if isinstance(value, Forgetter):
                # It's another object, we store only the ID
                if value._new:
                    # It's a new object too, it must be saved!
                    value.save()
                try:
                    (value,) = value._getID()
                except:
                    raise "Can't reference multiple-primary-key: %s" % value
            values.append(value)
        cursor = self.cursor()
        cursor.execute(sql, values)
        # cursor.commit()

        if not self._validID():
            if not len(self._getID()) == 1:
                raise "Can't retrieve auto-inserted ID for multiple-primary-key"
            # Here's the mysql magic to get the new ID
            self._setID(cursor.insert_id())
        cursor.close()
        self._new = False
824057
@Override
  public <T> void save(Object objectToSave, Class<T> entityClass) {
    save(objectToSave, Util.determineCollectionName(entityClass));
  }