Example #1
0
func saveReactionAndUpdatePost(transaction *gorp.Transaction, reaction *model.Reaction) error {
	if err := transaction.Insert(reaction); err != nil {
		return err
	}

	return updatePostForReactions(transaction, reaction.PostId)
}
Example #2
0
func CountRows(tableName, columnName string, txn *gorp.Transaction) (int64, error) {
	count, err := txn.SelectInt(fmt.Sprintf(SQL_MODEL_COUNT, columnName, tableName))
	if err != nil {
		return -1, err
	}

	return count, nil
}
func (as SqlOAuthStore) deleteOAuthTokens(transaction *gorp.Transaction, clientId string) StoreResult {
	result := StoreResult{}

	if _, err := transaction.Exec("DELETE FROM OAuthAccessData WHERE ClientId = :Id", map[string]interface{}{"Id": clientId}); err != nil {
		result.Err = model.NewLocAppError("SqlOAuthStore.DeleteApp", "store.sql_oauth.delete_app.app_error", nil, "id="+clientId+", err="+err.Error())
		return result
	}

	return as.deleteAppExtras(transaction, clientId)
}
func (s SqlPreferenceStore) update(transaction *gorp.Transaction, preference *model.Preference) StoreResult {
	result := StoreResult{}

	if _, err := transaction.Update(preference); err != nil {
		result.Err = model.NewAppError("SqlPreferenceStore.update", "We couldn't update the preference",
			"user_id="+preference.UserId+", category="+preference.Category+", name="+preference.Name+", "+err.Error())
	}

	return result
}
func (s SqlPreferenceStore) save(transaction *gorp.Transaction, preference *model.Preference) StoreResult {
	result := StoreResult{}

	preference.PreUpdate()

	if result.Err = preference.IsValid(); result.Err != nil {
		return result
	}

	params := map[string]interface{}{
		"UserId":   preference.UserId,
		"Category": preference.Category,
		"Name":     preference.Name,
		"Value":    preference.Value,
	}

	if utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_MYSQL {
		if _, err := transaction.Exec(
			`INSERT INTO
				Preferences
				(UserId, Category, Name, Value)
			VALUES
				(:UserId, :Category, :Name, :Value)
			ON DUPLICATE KEY UPDATE
				Value = :Value`, params); err != nil {
			result.Err = model.NewLocAppError("SqlPreferenceStore.save", "store.sql_preference.save.updating.app_error", nil, err.Error())
		}
	} else if utils.Cfg.SqlSettings.DriverName == model.DATABASE_DRIVER_POSTGRES {
		// postgres has no way to upsert values until version 9.5 and trying inserting and then updating causes transactions to abort
		count, err := transaction.SelectInt(
			`SELECT
				count(0)
			FROM
				Preferences
			WHERE
				UserId = :UserId
				AND Category = :Category
				AND Name = :Name`, params)
		if err != nil {
			result.Err = model.NewLocAppError("SqlPreferenceStore.save", "store.sql_preference.save.updating.app_error", nil, err.Error())
			return result
		}

		if count == 1 {
			s.update(transaction, preference)
		} else {
			s.insert(transaction, preference)
		}
	} else {
		result.Err = model.NewLocAppError("SqlPreferenceStore.save", "store.sql_preference.save.missing_driver.app_error", nil,
			"Failed to update preference because of missing driver")
	}

	return result
}
Example #6
0
func InitUtmstatusTable(txn *gorp.Transaction) {
	rows := []*UtmStatus{
		&UtmStatus{0, "passthrough"},
		&UtmStatus{0, "blocked"},
	}

	for _, r := range rows {
		if err := txn.Insert(r); err != nil {
			panic(err)
		}
	}
}
Example #7
0
func deleteReactionAndUpdatePost(transaction *gorp.Transaction, reaction *model.Reaction) error {
	if _, err := transaction.Exec(
		`DELETE FROM
			Reactions
		WHERE
			PostId = :PostId AND
			UserId = :UserId AND
			EmojiName = :EmojiName`,
		map[string]interface{}{"PostId": reaction.PostId, "UserId": reaction.UserId, "EmojiName": reaction.EmojiName}); err != nil {
		return err
	}

	return updatePostForReactions(transaction, reaction.PostId)
}
func (s SqlPreferenceStore) insert(transaction *gorp.Transaction, preference *model.Preference) StoreResult {
	result := StoreResult{}

	if err := transaction.Insert(preference); err != nil {
		if IsUniqueConstraintError(err.Error(), []string{"UserId", "preferences_pkey"}) {
			result.Err = model.NewLocAppError("SqlPreferenceStore.insert", "store.sql_preference.insert.exists.app_error", nil,
				"user_id="+preference.UserId+", category="+preference.Category+", name="+preference.Name+", "+err.Error())
		} else {
			result.Err = model.NewLocAppError("SqlPreferenceStore.insert", "store.sql_preference.insert.save.app_error", nil,
				"user_id="+preference.UserId+", category="+preference.Category+", name="+preference.Name+", "+err.Error())
		}
	}

	return result
}
Example #9
0
func GetUserByName(txn *gorp.Transaction, name string) (*models.User, error) {
	qrows := make([]models.User, 0)

	_, err := txn.Select(&qrows, SQL_USER_BYNAME, map[string]interface{}{
		"name": name,
	})
	if err != nil {
		return nil, err
	}
	if len(qrows) != 1 {
		return nil, nil
	}

	return &qrows[0], nil
}
Example #10
0
func (as SqlOAuthStore) deleteAppExtras(transaction *gorp.Transaction, clientId string) StoreResult {
	result := StoreResult{}

	if _, err := transaction.Exec(
		`DELETE FROM
			Preferences
		WHERE
			Category = :Category
			AND Name = :Name`, map[string]interface{}{"Category": model.PREFERENCE_CATEGORY_AUTHORIZED_OAUTH_APP, "Name": clientId}); err != nil {
		result.Err = model.NewLocAppError("SqlOAuthStore.DeleteApp", "store.sql_preference.delete.app_error", nil, err.Error())
		return result
	}

	return result
}
func (s SqlPreferenceStore) insert(transaction *gorp.Transaction, preference *model.Preference) StoreResult {
	result := StoreResult{}

	if err := transaction.Insert(preference); err != nil {
		if IsUniqueConstraintError(err.Error(), "UserId", "preferences_pkey") {
			result.Err = model.NewAppError("SqlPreferenceStore.insert", "A preference with that user id, category, and name already exists",
				"user_id="+preference.UserId+", category="+preference.Category+", name="+preference.Name+", "+err.Error())
		} else {
			result.Err = model.NewAppError("SqlPreferenceStore.insert", "We couldn't save the preference",
				"user_id="+preference.UserId+", category="+preference.Category+", name="+preference.Name+", "+err.Error())
		}
	}

	return result
}
Example #12
0
func GetDeviceBySerial(txn *gorp.Transaction, serial string) (*models.Device, error) {
	qrows := make([]models.Device, 0)

	_, err := txn.Select(&qrows, SQL_DEVICE_BYSERIAL, map[string]interface{}{
		"serial": serial,
	})
	if err != nil {
		return nil, err
	}

	if len(qrows) != 1 {
		return nil, nil
	}

	return &qrows[0], nil
}
Example #13
0
func GetCategoryByDescription(
	txn *gorp.Transaction,
	desc string) (*models.Category, error) {

	qrows := make([]models.Category, 0)

	_, err := txn.Select(&qrows, SQL_CATEGORY_BYNAME, map[string]interface{}{
		"desc": desc,
	})
	if err != nil {
		return nil, err
	}
	if len(qrows) != 1 {
		return nil, nil
	}

	return &qrows[0], nil
}
Example #14
0
func InitLoglevelTable(txn *gorp.Transaction) {
	rows := []*LogLevel{
		&LogLevel{0, "emergency"},
		&LogLevel{0, "alert"},
		&LogLevel{0, "critical"},
		&LogLevel{0, "error"},
		&LogLevel{0, "warning"},
		&LogLevel{0, "notice"},
		&LogLevel{0, "information"},
		&LogLevel{0, "debug"},
	}

	for _, r := range rows {
		if err := txn.Insert(r); err != nil {
			panic(err)
		}
	}
}
Example #15
0
func GetLoglevelByName(
	txn *gorp.Transaction,
	name string) (*models.LogLevel, error) {
	qrows := make([]models.LogLevel, 0)

	_, err := txn.Select(&qrows, SQL_LOGLEVEL_BYDESC, map[string]interface{}{
		"name": name,
	})
	if err != nil {
		return nil, err
	}

	if len(qrows) != 1 {
		return nil, nil
	}

	return &qrows[0], nil
}
Example #16
0
func GetRowByUnique(
	txn *gorp.Transaction,
	query string,
	qrows interface{},
	unique map[string]interface{}) (interface{}, error) {

	_, err := txn.Select(qrows, query, unique)
	if err != nil {
		return nil, err
	}

	rowsSlice := MakeGenericSlice(qrows)
	if len(rowsSlice) != 1 {
		return nil, nil
	}

	return rowsSlice[0], nil
}
Example #17
0
func GetLogtypeByNames(
	txn *gorp.Transaction,
	level1, level2 string) (*models.LogType, error) {
	qrows := make([]models.LogType, 0)

	_, err := txn.Select(&qrows, SQL_LOGTYPE_BYNAME, map[string]interface{}{
		"level1": level1,
		"level2": level2,
	})
	if err != nil {
		return nil, err
	}

	if len(qrows) != 1 {
		return nil, nil
	}

	return &qrows[0], nil
}
Example #18
0
func (s SqlChannelStore) saveChannelT(transaction *gorp.Transaction, channel *model.Channel) StoreResult {
	result := StoreResult{}

	if len(channel.Id) > 0 {
		result.Err = model.NewLocAppError("SqlChannelStore.Save", "store.sql_channel.save_channel.existing.app_error", nil, "id="+channel.Id)
		return result
	}

	channel.PreSave()
	if result.Err = channel.IsValid(); result.Err != nil {
		return result
	}

	if channel.Type != model.CHANNEL_DIRECT {
		if count, err := transaction.SelectInt("SELECT COUNT(0) FROM Channels WHERE TeamId = :TeamId AND DeleteAt = 0 AND (Type = 'O' OR Type = 'P')", map[string]interface{}{"TeamId": channel.TeamId}); err != nil {
			result.Err = model.NewLocAppError("SqlChannelStore.Save", "store.sql_channel.save_channel.current_count.app_error", nil, "teamId="+channel.TeamId+", "+err.Error())
			return result
		} else if count > 1000 {
			result.Err = model.NewLocAppError("SqlChannelStore.Save", "store.sql_channel.save_channel.limit.app_error", nil, "teamId="+channel.TeamId)
			return result
		}
	}

	if err := transaction.Insert(channel); err != nil {
		if IsUniqueConstraintError(err.Error(), []string{"Name", "channels_name_teamid_key"}) {
			dupChannel := model.Channel{}
			s.GetMaster().SelectOne(&dupChannel, "SELECT * FROM Channels WHERE TeamId = :TeamId AND Name = :Name AND DeleteAt > 0", map[string]interface{}{"TeamId": channel.TeamId, "Name": channel.Name})
			if dupChannel.DeleteAt > 0 {
				result.Err = model.NewLocAppError("SqlChannelStore.Save", "store.sql_channel.save_channel.previously.app_error", nil, "id="+channel.Id+", "+err.Error())
			} else {
				result.Err = model.NewLocAppError("SqlChannelStore.Save", CHANNEL_EXISTS_ERROR, nil, "id="+channel.Id+", "+err.Error())
				result.Data = &dupChannel
			}
		} else {
			result.Err = model.NewLocAppError("SqlChannelStore.Save", "store.sql_channel.save_channel.save.app_error", nil, "id="+channel.Id+", "+err.Error())
		}
	} else {
		result.Data = channel
	}

	return result
}
Example #19
0
func (s SqlChannelStore) saveMemberT(transaction *gorp.Transaction, member *model.ChannelMember, channel *model.Channel) StoreResult {
	result := StoreResult{}

	member.PreSave()
	if result.Err = member.IsValid(); result.Err != nil {
		return result
	}

	if err := transaction.Insert(member); err != nil {
		if IsUniqueConstraintError(err.Error(), []string{"ChannelId", "channelmembers_pkey"}) {
			result.Err = model.NewLocAppError("SqlChannelStore.SaveMember", "store.sql_channel.save_member.exists.app_error", nil, "channel_id="+member.ChannelId+", user_id="+member.UserId+", "+err.Error())
		} else {
			result.Err = model.NewLocAppError("SqlChannelStore.SaveMember", "store.sql_channel.save_member.save.app_error", nil, "channel_id="+member.ChannelId+", user_id="+member.UserId+", "+err.Error())
		}
	} else {
		result.Data = member
	}

	return result
}
func (s SqlChannelStore) saveMemberT(transaction *gorp.Transaction, member *model.ChannelMember, channel *model.Channel) StoreResult {
	result := StoreResult{}

	member.PreSave()
	if result.Err = member.IsValid(); result.Err != nil {
		return result
	}

	if err := transaction.Insert(member); err != nil {
		if IsUniqueConstraintError(err.Error(), "ChannelId", "channelmembers_pkey") {
			result.Err = model.NewAppError("SqlChannelStore.SaveMember", "A channel member with that id already exists", "channel_id="+member.ChannelId+", user_id="+member.UserId+", "+err.Error())
		} else {
			result.Err = model.NewAppError("SqlChannelStore.SaveMember", "We couldn't save the channel member", "channel_id="+member.ChannelId+", user_id="+member.UserId+", "+err.Error())
		}
	} else {
		result.Data = member
	}

	return result
}
func (s SqlChannelStore) saveChannelT(transaction *gorp.Transaction, channel *model.Channel) StoreResult {
	result := StoreResult{}

	if len(channel.Id) > 0 {
		result.Err = model.NewAppError("SqlChannelStore.Save", "Must call update for exisiting channel", "id="+channel.Id)
		return result
	}

	channel.PreSave()
	if result.Err = channel.IsValid(); result.Err != nil {
		return result
	}

	if channel.Type != model.CHANNEL_DIRECT {
		if count, err := transaction.SelectInt("SELECT COUNT(0) FROM Channels WHERE TeamId = :TeamId AND DeleteAt = 0 AND (Type = 'O' OR Type = 'P')", map[string]interface{}{"TeamId": channel.TeamId}); err != nil {
			result.Err = model.NewAppError("SqlChannelStore.Save", "Failed to get current channel count", "teamId="+channel.TeamId+", "+err.Error())
			return result
		} else if count > 1000 {
			result.Err = model.NewAppError("SqlChannelStore.Save", "You've reached the limit of the number of allowed channels.", "teamId="+channel.TeamId)
			return result
		}
	}

	if err := transaction.Insert(channel); err != nil {
		if IsUniqueConstraintError(err.Error(), "Name", "channels_name_teamid_key") {
			dupChannel := model.Channel{}
			s.GetMaster().SelectOne(&dupChannel, "SELECT * FROM Channels WHERE TeamId = :TeamId AND Name = :Name AND DeleteAt > 0", map[string]interface{}{"TeamId": channel.TeamId, "Name": channel.Name})
			if dupChannel.DeleteAt > 0 {
				result.Err = model.NewAppError("SqlChannelStore.Update", "A channel with that URL was previously created", "id="+channel.Id+", "+err.Error())
			} else {
				result.Err = model.NewAppError("SqlChannelStore.Update", "A channel with that URL already exists", "id="+channel.Id+", "+err.Error())
			}
		} else {
			result.Err = model.NewAppError("SqlChannelStore.Save", "We couldn't save the channel", "id="+channel.Id+", "+err.Error())
		}
	} else {
		result.Data = channel
	}

	return result
}
Example #22
0
func (edb *EntriesDatabase) getOrInsertName(txn *gorp.Transaction, fqdn string) (uint64, error) {
	var nameId uint64
	err := txn.SelectOne(&nameId, "SELECT nameID FROM fqdn WHERE name = ? LIMIT 1", fqdn)
	if err != nil {
		// Didn't exist, so let's insert it
		fqdnObj := &FQDN{
			Name: fqdn,
		}
		err = txn.Insert(fqdnObj)
		if err != nil {
			return 0, err
		}

		nameId = fqdnObj.NameID

		// Add to netscan queue
		queueObj := &NetscanQueue{
			NameID:    nameId,
			TimeAdded: time.Now(),
		}
		err = txn.Insert(queueObj)
		if err != nil {
			return 0, err
		}
	}

	if nameId == 0 {
		err = fmt.Errorf("Failed to obtain NameID")
	}

	return nameId, err
}
Example #23
0
func GetOrInsertByUnique(
	txn *gorp.Transaction,
	query string,
	qrows interface{},
	unique map[string]interface{},
	insert func() interface{}) (interface{}, error) {

	row, err := GetRowByUnique(txn, query, qrows, unique)
	if err != nil {
		return nil, err
	}

	if row == nil {
		row = insert()
		err = txn.Insert(row)
		if err != nil {
			return nil, err
		}
	}

	return row, nil
}
Example #24
0
func (edb *EntriesDatabase) insertRegisteredDomains(txn *gorp.Transaction, certId uint64, names map[string]struct{}) error {
	domains := make(map[string]struct{})
	for name, _ := range names {
		domain, err := publicsuffix.EffectiveTLDPlusOne(name)
		if err != nil {
			// This is non-critical. We'd rather have the cert with an incomplete
			// eTLD, so mask this error
			if edb.Verbose {
				fmt.Printf("%s\n", err)
			}
			continue
		}
		domains[domain] = struct{}{}
	}
	for domain, _ := range domains {
		etld, _ := publicsuffix.PublicSuffix(domain)
		label := strings.Replace(domain, "."+etld, "", 1)

		var regdomId uint64
		err := txn.SelectOne(&regdomId, "SELECT regdomID FROM registereddomain WHERE domain = ? LIMIT 1", domain)
		if err != nil {
			domainObj := &RegisteredDomain{
				Domain: domain,
				ETLD:   etld,
				Label:  label,
			}
			// Ignore errors on insert
			err := txn.Insert(domainObj)
			if errorIsNotDuplicate(err) {
				return fmt.Errorf("DB error on Registered Domain: %s: %s", domain, err)
			}
			regdomId = domainObj.RegDomID
		}

		certRegDomObj := &CertToRegisteredDomain{
			RegDomID: regdomId,
			CertID:   certId,
		}
		// Ignore errors on insert
		err = txn.Insert(certRegDomObj)
		if errorIsNotDuplicate(err) {
			return fmt.Errorf("DB error on Registered Domain: %s: %s", domain, err)
		}
	}
	return nil
}
Example #25
0
func executeSql(trans *gorp.Transaction, tableName string, status Store, tableCtx Store) {
	for k, v := range status {
		switch v.(int) {
		case STATUS_UPDATE:
			fmt.Println("STATUS_UPDATE: ", reflect.ValueOf(tableCtx[k]).Elem().FieldByName("Data").Interface())
			_, err := trans.Update(reflect.ValueOf(tableCtx[k]).Elem().FieldByName("Data").Interface())
			if err != nil {
				panic(err.Error())
			}
		case STATUS_DELETE:
			_, err := trans.Exec(fmt.Sprintf("DELETE FROM `%s` WHERE `uuid`='%s'", tableName, k))
			if err != nil {
				panic(err.Error())
			}
		case STATUS_CREATE:
			err := trans.Insert(reflect.ValueOf(tableCtx[k]).Elem().FieldByName("Data").Interface())
			if err != nil {
				panic(err.Error())
			}
		}
	}
}
Example #26
0
func updatePostForReactions(transaction *gorp.Transaction, postId string) error {
	_, err := transaction.Exec(UPDATE_POST_HAS_REACTIONS_QUERY, map[string]interface{}{"PostId": postId, "UpdateAt": model.GetMillis()})

	return err
}
Example #27
0
func rollback(tx *gorp.Transaction) {
	err := tx.Rollback()
	if err != nil {
		log.Errorf("unable to rollback: %v", err)
	}
}