// SaveDataIntoES save metrics and events to ES by using ES client
173067
func (esSvc *ElasticSearchService) SaveData(date time.Time, typeName string, sinkData []interface{}) error {
	if typeName == "" || len(sinkData) == 0 {
		return nil
	}

	indexName := esSvc.Index(date)

	// Use the IndexExists service to check if a specified index exists.
	exists, err := esSvc.EsClient.IndexExists(indexName)
	if err != nil {
		return err
	}

	if !exists {
		// Create a new index.
		createIndex, err := esSvc.EsClient.CreateIndex(indexName, mapping)
		if err != nil {
			return err
		}

		ack := false
		switch i := createIndex.(type) {
		case *elastic2.IndicesCreateResult:
			ack = i.Acknowledged
		case *elastic5.IndicesCreateResult:
			ack = i.Acknowledged
		}
		if !ack {
			return errors.New("Failed to acknoledge index creation")
		}
	}

	aliases, err := esSvc.EsClient.GetAliases(indexName)
	if err != nil {
		return err
	}
	aliasName := esSvc.IndexAlias(typeName)

	hasAlias := false
	switch a := aliases.(type) {
	case *elastic2.AliasesResult:
		hasAlias = a.Indices[indexName].HasAlias(aliasName)
	case *elastic5.AliasesResult:
		hasAlias = a.Indices[indexName].HasAlias(aliasName)
	}
	if !hasAlias {
		createAlias, err := esSvc.EsClient.AddAlias(indexName, esSvc.IndexAlias(typeName))
		if err != nil {
			return err
		}

		ack := false
		switch i := createAlias.(type) {
		case *elastic2.AliasResult:
			ack = i.Acknowledged
		case *elastic5.AliasResult:
			ack = i.Acknowledged
		}
		if !ack {
			return errors.New("Failed to acknoledge index alias creation")
		}
	}

	for _, data := range sinkData {
		esSvc.EsClient.AddBulkReq(indexName, typeName, data)
	}

	return nil
}
848845
func (i *Index) SaveObject(object interface{}, opts ...interface{}) (res SaveObjectRes, err error) {
	path := i.path("")
	err = i.transport.Request(&res, http.MethodPost, path, object, call.Write, opts...)
	res.wait = i.WaitTask
	return
}
812135
func SaveFileS(filePath string, s string) (int, error) {
	return SaveFile(filePath, []byte(s))
}
434983
func (h *Handle) SaveMetaToStorage(tableID, count, modifyCount int64) (err error) {
	h.mu.Lock()
	defer h.mu.Unlock()
	ctx := context.TODO()
	exec := h.mu.ctx.(sqlexec.SQLExecutor)
	_, err = exec.Execute(ctx, "begin")
	if err != nil {
		return errors.Trace(err)
	}
	defer func() {
		err = finishTransaction(ctx, exec, err)
	}()
	txn, err := h.mu.ctx.Txn(true)
	if err != nil {
		return errors.Trace(err)
	}
	var sql string
	version := txn.StartTS()
	sql = fmt.Sprintf("replace into mysql.stats_meta (version, table_id, count, modify_count) values (%d, %d, %d, %d)", version, tableID, count, modifyCount)
	_, err = exec.Execute(ctx, sql)
	return
}
847387
func (m *Manager) saveAuthorizationRequest(ar *authorizationRequest) (err error) {
	// TODO: Validation!

	err = m.getAuthorizationRequestCollection().Insert(ar)

	return
}
1106263
func (i *Index) SaveSynonym(synonym Synonym, opts ...interface{}) (res UpdateTaskRes, err error) {
	if synonym.ObjectID() == "" {
		err = errs.ErrMissingObjectID
		res.wait = noWait
		return
	}

	path := i.path("/synonyms/%s", url.QueryEscape(synonym.ObjectID()))
	err = i.transport.Request(&res, http.MethodPut, path, synonym, call.Write, opts...)
	res.wait = i.WaitTask
	return
}
992912
func (i *Index) SaveSynonyms(synonyms []Synonym, opts ...interface{}) (res UpdateTaskRes, err error) {
	if replaceExistingSynonyms := iopt.ExtractReplaceExistingSynonyms(opts...); replaceExistingSynonyms != nil {
		opts = opt.InsertExtraURLParam(opts, "replaceExistingSynonyms", replaceExistingSynonyms.Get())
	}
	path := i.path("/synonyms/batch")
	err = i.transport.Request(&res, http.MethodPost, path, synonyms, call.Write, opts...)
	res.wait = i.WaitTask
	return
}
843655
func (t *Transaction) saveFieldIndexesForFields(fieldNames []string, mr *modelRef) {
	for _, fs := range mr.spec.fields {
		// Skip fields whose names do not appear in fieldNames.
		if !stringSliceContains(fieldNames, fs.name) {
			continue
		}
		switch fs.indexKind {
		case noIndex:
			continue
		case numericIndex:
			t.saveNumericIndex(mr, fs)
		case booleanIndex:
			t.saveBooleanIndex(mr, fs)
		case stringIndex:
			t.saveStringIndex(mr, fs)
		}
	}
}
952406
func SaveMetrics(p *redis.Pool, name string, metrics MetricsRecord) error {
	for _, agg := range aggregationIntervals {
		if err := SaveMetricsForInterval(p, agg, name, metrics); err != nil {
			return errors.Wrap(err, "save metrics for interval error")
		}
	}

	log.WithFields(log.Fields{
		"name":        name,
		"aggregation": aggregationIntervals,
	}).Info("metrics saved")

	return nil
}
642496
func (p *Project) SaveAs(name string) error {
	log.Fine("Saving project as %s", name)
	if data, err := json.Marshal(p); err != nil {
		return err
	} else if err := ioutil.WriteFile(name, data, 0644); err != nil {
		return err
	}
	if abs, err := filepath.Abs(name); err != nil {
		p.SetName(name)
	} else {
		p.SetName(abs)
	}
	return nil
}
958611
func (s *OAuth2Storage) SaveAuthorize(data *osin.AuthorizeData) error {
	var clientID uint64
	var err error
	if clientID, err = strconv.ParseUint(data.Client.GetId(), 10, 64); err != nil {
		return err
	}

	if err = s.isValidScope(data.Scope); err != nil {
		return fmt.Errorf("Saving Authorize: " + err.Error())
	}

	d := &OAuth2AuthorizeData{
		ClientID: clientID,
		Code:     data.Code,
		// CreatedAt field is automatically filled by the dbms
		ExpiresIn:   uint64(data.ExpiresIn),
		RedirectURI: data.RedirectUri,
		Scope:       data.Scope,
		//State:       data.State,
		UserID: data.UserData.(uint64)}

	return Db().Create(d)
}
1289904
func (target *WebhookTarget) Save(eventData event.Event) error {
	return target.send(eventData)
}
1228160
func (c *Connection) ValidateAndSave(model interface{}, excludeColumns ...string) (*validate.Errors, error) {
	sm := &Model{Value: model}
	verrs, err := sm.validateSave(c)
	if err != nil {
		return verrs, err
	}
	if verrs.HasAny() {
		return verrs, nil
	}
	return verrs, c.Save(model, excludeColumns...)
}
575965
func (s *EventStore) Save(ctx context.Context, events []eh.Event, originalVersion int) error {
	if len(events) == 0 {
		return eh.EventStoreError{
			Err:       eh.ErrNoEventsToAppend,
			Namespace: eh.NamespaceFromContext(ctx),
		}
	}

	sess := s.session.Copy()
	defer sess.Close()

	// Build all event records, with incrementing versions starting from the
	// original aggregate version.
	dbEvents := make([]dbEvent, len(events))
	aggregateID := events[0].AggregateID()
	version := originalVersion
	for i, event := range events {
		// Only accept events belonging to the same aggregate.
		if event.AggregateID() != aggregateID {
			return eh.EventStoreError{
				Err:       eh.ErrInvalidEvent,
				Namespace: eh.NamespaceFromContext(ctx),
			}
		}

		// Only accept events that apply to the correct aggregate version.
		if event.Version() != version+1 {
			return eh.EventStoreError{
				Err:       eh.ErrIncorrectEventVersion,
				Namespace: eh.NamespaceFromContext(ctx),
			}
		}

		// Create the event record for the DB.
		e, err := newDBEvent(ctx, event)
		if err != nil {
			return err
		}
		dbEvents[i] = *e
		version++
	}

	// Either insert a new aggregate or append to an existing.
	if originalVersion == 0 {
		aggregate := aggregateRecord{
			AggregateID: aggregateID.String(),
			Version:     len(dbEvents),
			Events:      dbEvents,
		}

		if err := sess.DB(s.dbName(ctx)).C("events").Insert(aggregate); err != nil {
			return eh.EventStoreError{
				BaseErr:   err,
				Err:       ErrCouldNotSaveAggregate,
				Namespace: eh.NamespaceFromContext(ctx),
			}
		}
	} else {
		// Increment aggregate version on insert of new event record, and
		// only insert if version of aggregate is matching (ie not changed
		// since loading the aggregate).
		if err := sess.DB(s.dbName(ctx)).C("events").Update(
			bson.M{
				"_id":     aggregateID.String(),
				"version": originalVersion,
			},
			bson.M{
				"$push": bson.M{"events": bson.M{"$each": dbEvents}},
				"$inc":  bson.M{"version": len(dbEvents)},
			},
		); err != nil {
			return eh.EventStoreError{
				BaseErr:   err,
				Err:       ErrCouldNotSaveAggregate,
				Namespace: eh.NamespaceFromContext(ctx),
			}
		}
	}

	return nil
}
250357
func (s *OAuth2Storage) SaveAccess(accessData *osin.AccessData) error {
	var clientID uint64
	var err error
	if clientID, err = strconv.ParseUint(accessData.Client.GetId(), 10, 64); err != nil {
		return errors.New("Invalid Client ID")
	}

	if err = s.isValidScope(accessData.Scope); err != nil {
		return fmt.Errorf("Saving Access: " + err.Error())
	}

	var accessDataIDPtr sql.NullInt64
	if accessData.AccessData != nil {
		var father OAuth2AccessData
		if err = Db().Model(OAuth2AccessData{}).Where(&OAuth2AccessData{AccessToken: accessData.AccessData.AccessToken}).Scan(&father); err != nil {
			return errors.New("Error fetching parent Access Data ID")
		}

		accessDataIDPtr.Int64, accessDataIDPtr.Valid = int64(father.ID), true
	}

	// required to fill the foreign key
	var authorizeDataIDPtr sql.NullInt64
	if accessData.AuthorizeData != nil {
		var authorizeData OAuth2AuthorizeData
		if err = Db().Model(OAuth2AuthorizeData{}).Where(&OAuth2AuthorizeData{Code: accessData.AuthorizeData.Code}).Scan(&authorizeData); err != nil {
			return fmt.Errorf("SaveAccess: can't load authorize data with code: %s", accessData.AuthorizeData.Code)
		}

		authorizeDataIDPtr.Int64, authorizeDataIDPtr.Valid = int64(authorizeData.ID), true
	}

	tx := Db().Begin()

	var refreshTokenFK sql.NullInt64

	oauthAccessData := &OAuth2AccessData{
		AccessDataID:    accessDataIDPtr,
		AccessToken:     accessData.AccessToken,
		AuthorizeDataID: authorizeDataIDPtr,
		ClientID:        clientID,
		//CreatedAt:       accessData.CreatedAt, <- dbms handled
		ExpiresIn:   uint64(accessData.ExpiresIn),
		RedirectURI: accessData.RedirectUri,
		Scope:       accessData.Scope,
		UserID:      accessData.UserData.(uint64)}

	if accessData.RefreshToken != "" {
		// Create refresh token
		var newRefreshToken OAuth2RefreshToken
		newRefreshToken.Token = accessData.RefreshToken
		if err := tx.Create(&newRefreshToken); err != nil {
			tx.Rollback()
			return err
		}
		refreshTokenFK.Int64 = int64(newRefreshToken.ID)
		refreshTokenFK.Valid = true
	}

	// Put refresh token id, into OAuth2AccessData.refreshtoken fk
	oauthAccessData.RefreshTokenID = refreshTokenFK

	if err := tx.Create(oauthAccessData); err != nil {
		tx.Rollback()
		return err
	}

	if err := tx.Commit(); err != nil {
		return err
	}

	return nil
}
97339
func Save(st ImageMetadataInterface, metadata params.MetadataSaveParams) ([]params.ErrorResult, error) {
	all := make([]params.ErrorResult, len(metadata.Metadata))
	if len(metadata.Metadata) == 0 {
		return nil, nil
	}
	modelCfg, err := st.ModelConfig()
	if err != nil {
		return nil, errors.Annotatef(err, "getting model config")
	}
	for i, one := range metadata.Metadata {
		md := ParseMetadataListFromParams(one, modelCfg)
		err := st.SaveMetadata(md)
		all[i] = params.ErrorResult{Error: common.ServerError(err)}
	}
	return all, nil
}
412336
func (s *Storage) SaveAccess(data *osin.AccessData) (err error) {
	prev := ""
	authorizeData := &osin.AuthorizeData{}

	if data.AccessData != nil {
		prev = data.AccessData.AccessToken
	}

	if data.AuthorizeData != nil {
		authorizeData = data.AuthorizeData
	}

	extra, err := assertToString(data.UserData)
	if err != nil {
		return err
	}

	tx, err := s.db.Begin()
	if err != nil {
		return errors.New(err)
	}

	if data.RefreshToken != "" {
		if err := s.saveRefresh(tx, data.RefreshToken, data.AccessToken); err != nil {
			return err
		}
	}

	if data.Client == nil {
		return errors.New("data.Client must not be nil")
	}

	_, err = tx.Exec("INSERT INTO access (client, authorize, previous, access_token, refresh_token, expires_in, scope, redirect_uri, created_at, extra) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)", data.Client.GetId(), authorizeData.Code, prev, data.AccessToken, data.RefreshToken, data.ExpiresIn, data.Scope, data.RedirectUri, data.CreatedAt, extra)
	if err != nil {
		if rbe := tx.Rollback(); rbe != nil {
			return errors.New(rbe)
		}
		return errors.New(err)
	}

	if err = tx.Commit(); err != nil {
		return errors.New(err)
	}

	return nil
}