Easy save(insert or update) for db models
431980
def save(self):
        
        try:
            if self.exists() is False:
                self.db.session.add(self)
            # self.db.session.merge(self)
            self.db.session.commit()
        except (Exception, BaseException) as error:
            if current_app.config['DEBUG']:
                raise error
            return None
653783
def save(self):
        """"""
        check_bind(self)

        creating = self.id is None
        if creating and not self.__class__._has_schema_method("create"):
            raise MethodNotSupported("{} do not support creating.".format(self.__class__.__name__))
        if not creating and not self.__class__._has_schema_method("update"):
            raise MethodNotSupported("{} do not support updating.".format(self.__class__.__name__))

        try:
            self._resource.save()
        except HTTPError as e:
            if e.response.status_code == 400:
                err_json = e.response.json().get("errors", [])
                msg = pretty_print_error(err_json)
                raise ServerError(msg)
            elif e.response.status_code == 404:
                action = "creating" if creating else "updating"
                raise MethodNotSupported(
                    "{} do not support {}.".format(self.__class__.__name__, action)
                )
            elif e.response.status_code == 409:
                raise ServerError("This {} object already exists".format(self.__class__.__name__))
            else:
                raise e
632990
def create_or_update(ctx, model, xmlid, values):
    
    if isinstance(model, basestring):
        model = ctx.env[model]

    record = ctx.env.ref(xmlid, raise_if_not_found=False)
    if record:
        record.update(values)
    else:
        record = model.create(values)
        add_xmlid(ctx, record, xmlid)
    return record
1083853
def save(self, commit=True):
        

        db.session.add(self)
        if commit:
            db.session.commit()
        return self
604730
def save(self, key, data):
        
        self._db[key] = json.dumps(data)
        self._db.sync()
594397
def update_insert_values(bel_resource: Mapping, mapping: Mapping[str, Tuple[str, str]], values: Dict[str, str]) -> None:
    """"""
    for database_column, (section, key) in mapping.items():
        if section in bel_resource and key in bel_resource[section]:
            values[database_column] = bel_resource[section][key]
1273442
public function postSave()
    {

        // check if the model already exists
        if ((!isset($this->revisionEnabled) || $this->revisionEnabled) && $this->updating) {
            // if it does, it means we're updating

            $changes_to_record = $this->changedRevisionableFields();

            $revisions = array();

            foreach ($changes_to_record as $key => $change) {
                $revisions[] = array(
                    'revisionable_type'     => $this->getMorphClass(),
                    'revisionable_id'       => $this->getKey(),
                    'key'                   => $key,
                    'old_value'             => array_get($this->originalData, $key),
                    'new_value'             => $this->updatedData[$key],
                    'user_id'               => $this->getSystemUserId(),
                    'created_at'            => new \DateTime(),
                    'updated_at'            => new \DateTime(),
                );
            }

            if (count($revisions) > 0) {
                $revision = static::newModel();
                \DB::table($revision->getTable())->insert($revisions);
            }
        }
    }
273462
def pre_save(sender, instance, raw, using, update_fields, **kwargs):
    """"""
    if raw:
        # Return if loading Fixtures
        return

    try:
        with transaction.atomic():
            if not should_audit(instance):
                return False
            try:
                object_json_repr = serializers.serialize("json", [instance])
            except Exception:
                # We need a better way for this to work. ManyToMany will fail on pre_save on create
                return None

            if instance.pk is None:
                created = True
            else:
                created = False

            # created or updated?
            if not created:
                old_model = sender.objects.get(pk=instance.pk)
                delta = model_delta(old_model, instance)
                changed_fields = json.dumps(delta)
                event_type = CRUDEvent.UPDATE

            # user
            try:
                user = get_current_user()
                # validate that the user still exists
                user = get_user_model().objects.get(pk=user.pk)
            except:
                user = None

            if isinstance(user, AnonymousUser):
                user = None

            # callbacks
            kwargs['request'] = get_current_request()  # make request available for callbacks
            create_crud_event = all(
                callback(instance, object_json_repr, created, raw, using, update_fields, **kwargs)
                for callback in CRUD_DIFFERENCE_CALLBACKS if callable(callback))
            # create crud event only if all callbacks returned True
            if create_crud_event and not created:
                c_t = ContentType.objects.get_for_model(instance)
                sid = transaction.savepoint()
                try:
                    with transaction.atomic():
                        crud_event = CRUDEvent.objects.create(
                            event_type=event_type,
                            object_repr=str(instance),
                            object_json_repr=object_json_repr,
                            changed_fields=changed_fields,
                            content_type_id=c_t.id,
                            object_id=instance.pk,
                            user_id=getattr(user, 'id', None),
                            datetime=timezone.now(),
                            user_pk_as_string=str(user.pk) if user else user
                        )
                except Exception as e:
                    logger.exception(
                        "easy audit had a pre-save exception on CRUDEvent creation. instance: {}, instance pk: {}".format(
                            instance, instance.pk))
                    transaction.savepoint_rollback(sid)
    except Exception:
        logger.exception('easy audit had a pre-save exception.')
343240
protected function saveModelForTable()
    {
        $table = $this;
        $dates = [];
        $fields = $table->getFields();
        // TODO Work with the namespace again. The FQN does not work since switching to the generator.s
        $modelContent = (new ModelContent($table->getModelName()))->setTable($table->getName());

        if (array_key_exists($field = 'deleted_at', $fields)) {
            unset($fields[$field]);

            $dates[] = $field;
            $modelContent->setTraits(['\Illuminate\Database\Eloquent\SoftDeletes']);
        } // if

        if (array_key_exists($field = 'created_at', $fields)) {
            unset($fields[$field]);

            $dates[] = $field;
        } // if

        if (array_key_exists($field = 'updated_at', $fields)) {
            unset($fields[$field]);

            $dates[] = $field;
        } // if

        if ($dates) {
            $modelContent->setDates($dates);
        } // if

        unset($fields['id']);
        $modelContent->setFillable(array_diff(array_keys($fields), $table->getBlacklist()));
        $modelContent->setCasts($table->getCastedFields());

        if ($genericCalls = $table->getGenericCalls()) {
            foreach ($genericCalls as $call) {
                if ($call instanceof ForeignKey) {
                    $modelContent->addForeignKey($call);
                } // if
            } // foreach
        } // if

        if ($sources = $table->getRelationSources()) {
            foreach ($sources as $call) {
                if ($call instanceof ForeignKey) {
                    $modelContent->addForeignKey($call);
                } // if
            } // foreach
        } // if

        $modelContent->save();

        return $this;
    }
549544
def create_or_update(cls, object_version, key, value):
        """"""
        assert len(key) < 256
        assert len(value) < 256
        obj = cls.get(object_version, key)
        if obj:
            obj.value = value
            db.session.merge(obj)
        else:
            obj = cls.create(object_version, key, value)
        return obj
1299866
public function saveToDB() {
		BLog::addToLog('[Items.Item.' . $this->tableName . ']: saveToDB()');
		if ($this->isNew) {
			return $this->dbInsert();
		} else {
			return $this->dbupdate();
		}
	}
1047127
def update_object_in_db(self,
                            obj: Any,
                            table: str,
                            fieldlist: Sequence[str]) -> None:
        """"""
        self.ensure_db_open()
        pkvalue = getattr(obj, fieldlist[0])
        valuelist = []
        # Non-PK fields first
        for f in fieldlist[1:]:
            valuelist.append(getattr(obj, f))
        # Then PK
        valuelist.append(pkvalue)
        cursor = self.db.cursor()
        self.db_exec_with_cursor(
            cursor,
            get_sql_update_by_first_field(table, fieldlist, self.get_delims()),
            *valuelist
        )
1184054
async def save(self):
        

        if hasattr(self, "before_save"):
            self.before_save()

        query = r.table(self.table_name)

        if self._state.get("id"):
            query = query \
                .get(self._state.get("id")) \
                .update(self.__db_repr, return_changes=True)
        else:
            query = query \
                .insert(self.__db_repr, return_changes=True)

        resp = await query.run(await conn.get())

        try:
            changes = resp["changes"]

            if len(changes) > 0:
                self.wrap(resp["changes"][0]["new_val"])
        except KeyError:
            raise UnexpectedDbResponse()

        if resp["skipped"] > 0:
            raise UnexpectedDbResponse(
                "Model with id `%s` not found in the database." %
                self._state.get("id"))

        return self
1199864
def save(options={:validate => true})
      context = self.new_record? ? :create : :update
      return false if options[:validate] && !valid?(context)
      
      run_callbacks(context) do
        if context == :create
          key = self.class.persistence.insert(self)
        else
          key = self.class.persistence.update(self)
        end
        self.persist!
        key
      end
    end
652006
def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        
        # Always create a new entry, instead of updating an existing model
        self.pk = None  # pylint: disable=invalid-name
        super(ConfigurationModel, self).save(
            force_insert,
            force_update,
            using,
            update_fields
        )
        cache.delete(self.cache_key_name(*[getattr(self, key) for key in self.KEY_FIELDS]))
        if self.KEY_FIELDS:
            cache.delete(self.key_values_cache_key_name())
1243031
def save(self, obj):
        """"""
        if not obj.id:
            obj.id = uuid()

        stored_data = {
            '_id': obj.id,
            'value': json.loads(obj.to_data())
        }

        index_vals = obj.indexes() or {}
        for key in obj.__class__.index_names() or []:
            val = index_vals.get(key, '')
            stored_data[key] = str(val)

        coll = self.get_collection(obj.__class__.get_table_name())
        coll.update({"_id": obj.id}, stored_data, upsert=True)
361980
function insert (model) {
    var insert = model.insertDelayed && model.engine === 'MyISAM' ? 'INSERT DELAYED' : 'INSERT'
    var columns = _.map(model.insertColumnNames, quoteName).join(', ')
    var values = _.map(model.insertColumnNames, columnName => placeholder(model, columnName, model.columns[columnName])).join(', ')
    return `${insert} INTO ${quoteName(model.name)} (${columns}) VALUES(${values})`
}