Esempio n. 1
0
func createRecord(input interface{}, session *xorm.Session) (statusCode int, err error) {
	_, err = session.Insert(input)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	return http.StatusOK, err
}
Esempio n. 2
0
func (f *searchADCFPagerFilter) GetPageQuery(tx *xorm.Session) *xorm.Session {
	tx = f.GetQuery(tx)

	offset := (f.Page - 1) * f.PageSize
	tx.Limit(f.PageSize, offset)
	return tx
}
Esempio n. 3
0
func updateRecordWithUserId(input interface{}, fieldNames map[string]bool, id, userId string, session *xorm.Session) (statusCode int, err error) {
	if _, err := uuid.FromString(id); err != nil {
		return http.StatusBadRequest, errUuidNotValid
	}
	if _, err := uuid.FromString(userId); err != nil {
		return http.StatusBadRequest, errUuidNotValid
	}

	//convert the fields set to array
	array := []string{}
	for k, _ := range fieldNames {
		array = append(array, k)
	}

	//update the database
	affected, err := session.Where("id = ? and user_id = ?", id, userId).Cols(array...).Update(input)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	if affected == 0 {
		return http.StatusNotFound, errors.New("The record is not found.")
	}

	return http.StatusNoContent, nil
}
Esempio n. 4
0
func (f searchADCFFilter) GetQuery(tx *xorm.Session) *xorm.Session {
	f.CheckUnscoped(tx)

	if f.HasField("AAA") && len(f.AAA) > 0 {
		name := fmt.Sprintf("%%%s%%", f.AAA)
		tx.And("a_a_a like ?", f.AAA)
	}

	if f.HasField("BBB") && len(f.BBB) > 0 {
		name := fmt.Sprintf("%%%s%%", f.BBB)
		tx.And("b_b_b like ?", f.BBB)
	}

	if f.HasField("CCC") {
		tx.And("c_c_c = ?", f.CCC)
	}
	if f.HasField("CCC_In") && len(f.CCC) > 0 {
		tx.In("c_c_c", f.CCC_In)
	}

	if f.HasField("UpdateTime") && f.UpdateTime > 0 {
		tx.And("update_at > ?", utils.UnixtimeToDate(f.UpdateTime, ""))
	}
	return tx
}
Esempio n. 5
0
// SearchUserByName takes keyword and part of user name to search,
// it returns results in given range and number of total results.
func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
	if len(opts.Keyword) == 0 {
		return users, 0, nil
	}
	opts.Keyword = strings.ToLower(opts.Keyword)

	if opts.PageSize <= 0 || opts.PageSize > setting.ExplorePagingNum {
		opts.PageSize = setting.ExplorePagingNum
	}
	if opts.Page <= 0 {
		opts.Page = 1
	}

	searchQuery := "%" + opts.Keyword + "%"
	users = make([]*User, 0, opts.PageSize)
	// Append conditions
	sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
		Or("LOWER(full_name) LIKE ?", searchQuery).
		And("type = ?", opts.Type)

	var countSess xorm.Session
	countSess = *sess
	count, err := countSess.Count(new(User))
	if err != nil {
		return nil, 0, fmt.Errorf("Count: %v", err)
	}

	if len(opts.OrderBy) > 0 {
		sess.OrderBy(opts.OrderBy)
	}
	return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
}
func (this *ContentPuzzleActivityComponentPuzzleDbModel) AddForTrans(sess *xorm.Session, data ContentPuzzleActivityComponentPuzzle) ContentPuzzleActivityComponentPuzzle {
	_, err := sess.Insert(&data)
	if err != nil {
		panic(err)
	}
	return data
}
Esempio n. 7
0
// Mark old articles read.
func MarkOldArticlesRead(session *xorm.Session) (affected int64, err error) {

	list, err := GetFeedListWithAmount(session)
	if err != nil {
		return
	}

	for _, item := range list {
		if int(*item.MaxUnread) > 0 && item.Unread > uint64(*item.MaxUnread) {
			n := int(item.Unread) - int(*item.MaxUnread)

			sql := "update Item set read=1 where id in (select id from Item where Fid = ? and Read = 0 order by Id asc limit ?)"
			result, e := session.Exec(sql, item.Id, n)
			if e != nil {
				err = e
				return
			}
			num, e := result.RowsAffected()
			if e != nil {
				err = e
				return
			}
			global.Logger.Infof("[TRIM DATA] in transaction: mark old articles read: feed id: %d, affected: %d", item.Id, num)
			affected += num
		}
	}

	return
}
Esempio n. 8
0
// Delete old articles which read=1.
func DeleteOldArticles(session *xorm.Session) (affected int64, err error) {

	list, err := GetFeedListWithAmount(session)
	if err != nil {
		return
	}

	for _, item := range list {
		if int(*item.MaxKeep) > 0 && (item.Amount-item.Unread > uint64(*item.MaxKeep)) {
			n := int(item.Amount - item.Unread - uint64(*item.MaxKeep))

			sql := "delete from Item where id in (select id from Item where Fid = ? and Read = 1 and starred = 0 order by Id asc limit ?)"
			result, e := session.Exec(sql, item.Id, n)
			if e != nil {
				err = e
				return
			}
			num, e := result.RowsAffected()
			if e != nil {
				err = e
				return
			}
			global.Logger.Infof("[TRIM DATA] in transaction: delete old articles which is read: feed id: %d, affected: %d", item.Id, num)
			affected += num
		}
	}

	return
}
Esempio n. 9
0
func deletePublicKey(e *xorm.Session, keyID int64) error {
	sshOpLocker.Lock()
	defer sshOpLocker.Unlock()

	key := &PublicKey{ID: keyID}
	has, err := e.Get(key)
	if err != nil {
		return err
	} else if !has {
		return nil
	}

	if _, err = e.Id(key.ID).Delete(new(PublicKey)); err != nil {
		return err
	}

	fpath := filepath.Join(SSHPath, "authorized_keys")
	tmpPath := filepath.Join(SSHPath, "authorized_keys.tmp")
	if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
		return err
	} else if err = os.Remove(fpath); err != nil {
		return err
	}
	return os.Rename(tmpPath, fpath)
}
Esempio n. 10
0
func deletePublicKey(e *xorm.Session, keyID int64) error {
	sshOpLocker.Lock()
	defer sshOpLocker.Unlock()

	key := &PublicKey{ID: keyID}
	has, err := e.Get(key)
	if err != nil {
		return err
	} else if !has {
		return nil
	}

	if _, err = e.Id(key.ID).Delete(new(PublicKey)); err != nil {
		return err
	}

	// Don't need to rewrite this file if builtin SSH server is enabled.
	if setting.StartSSHServer {
		return nil
	}

	fpath := filepath.Join(setting.SSHRootPath, "authorized_keys")
	tmpPath := filepath.Join(setting.SSHRootPath, "authorized_keys.tmp")
	if err = rewriteAuthorizedKeys(key, fpath, tmpPath); err != nil {
		return err
	} else if err = os.Remove(fpath); err != nil {
		return err
	}
	return os.Rename(tmpPath, fpath)
}
Esempio n. 11
0
// UpdateAccess updates access information with session for rolling back.
func UpdateAccessWithSession(sess *xorm.Session, access *Access) error {
	if _, err := sess.Id(access.Id).Update(access); err != nil {
		sess.Rollback()
		return err
	}
	return nil
}
Esempio n. 12
0
File: issue.go Progetto: chadoe/gogs
func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
	users, err := repo.GetAssignees()
	if err != nil {
		return err
	}

	iu := &IssueUser{
		IssueID: issue.ID,
		RepoID:  repo.ID,
	}

	// Poster can be anyone.
	isNeedAddPoster := true
	for _, u := range users {
		iu.ID = 0
		iu.UID = u.Id
		iu.IsPoster = iu.UID == issue.PosterID
		if isNeedAddPoster && iu.IsPoster {
			isNeedAddPoster = false
		}
		iu.IsAssigned = iu.UID == issue.AssigneeID
		if _, err = e.Insert(iu); err != nil {
			return err
		}
	}
	if isNeedAddPoster {
		iu.ID = 0
		iu.UID = issue.PosterID
		iu.IsPoster = true
		if _, err = e.Insert(iu); err != nil {
			return err
		}
	}
	return nil
}
Esempio n. 13
0
File: org.go Progetto: 0rax/gogs
func getOrgsByUserID(sess *xorm.Session, userID int64, showAll bool) ([]*User, error) {
	orgs := make([]*User, 0, 10)
	if !showAll {
		sess.And("`org_user`.is_public=?", true)
	}
	return orgs, sess.And("`org_user`.uid=?", userID).
		Join("INNER", "`org_user`", "`org_user`.org_id=`user`.id").Find(&orgs)
}
Esempio n. 14
0
// deletePublicKeys does the actual key deletion but does not update authorized_keys file.
func deletePublicKeys(e *xorm.Session, keyIDs ...int64) error {
	if len(keyIDs) == 0 {
		return nil
	}

	_, err := e.In("id", strings.Join(base.Int64sToStrings(keyIDs), ",")).Delete(new(PublicKey))
	return err
}
func (this *ContentPuzzleActivityComponentPuzzleDbModel) GetByComponentIdForTrans(sess *xorm.Session, componentId int) []ContentPuzzleActivityComponentPuzzle {
	result := []ContentPuzzleActivityComponentPuzzle{}
	err := sess.Sql("select * from t_content_puzzle_activity_component_puzzle where contentPuzzleActivityComponentId = ? for update", componentId).Find(&result)
	if err != nil {
		panic(err)
	}
	return result
}
func (this *PuzzleActivityComponentDbModel) SetStateForTrans(sess *xorm.Session, componentId int, state int) {
	data := ContentPuzzleActivityComponent{
		State: state,
	}
	_, err := sess.Where("contentPuzzleActivityComponentId=?", componentId).Update(&data)
	if err != nil {
		panic(err)
	}
}
Esempio n. 17
0
func updateIsDefaultFlag(ds *m.DataSource, sess *xorm.Session) error {
	// Handle is default flag
	if ds.IsDefault {
		rawSql := "UPDATE data_source SET is_default=? WHERE org_id=? AND id <> ?"
		if _, err := sess.Exec(rawSql, false, ds.OrgId, ds.Id); err != nil {
			return err
		}
	}
	return nil
}
Esempio n. 18
0
//获取系统参数表
func GetValueFromSysConfig(txn *xorm.Session, key string) (models.SystemConfig, error) {
	var val models.SystemConfig
	val.Ename = key
	has, err := txn.Get(&val)
	if !has || !CheckError(err, "取系统参数失败") {
		log.Error("取系统参数失败:", key)
		return val, errors.New("failed")
	}
	return val, nil
}
Esempio n. 19
0
func DeleteAlertDefinition(dashboardId int64, sess *xorm.Session) error {
	alerts := make([]*m.Alert, 0)
	sess.Where("dashboard_id = ?", dashboardId).Find(&alerts)

	for _, alert := range alerts {
		deleteAlertByIdInternal(alert.Id, "Dashboard deleted", sess)
	}

	return nil
}
Esempio n. 20
0
func GetAlertsByDashboardId2(dashboardId int64, sess *xorm.Session) ([]*m.Alert, error) {
	alerts := make([]*m.Alert, 0)
	err := sess.Where("dashboard_id = ?", dashboardId).Find(&alerts)

	if err != nil {
		return []*m.Alert{}, err
	}

	return alerts, nil
}
Esempio n. 21
0
// Get feed ids by tags.
func getFeedIdsByTags(session *xorm.Session, tags []string) (fids []int64, err error) {
	var t []*Tag
	err = session.Cols("Fid").In("Name", tags).Find(&t)
	if err != nil {
		return
	}
	for _, i := range t {
		fids = append(fids, i.Fid)
	}
	return
}
Esempio n. 22
0
func updateIssueUserByAssignee(e *xorm.Session, issueID, assigneeID int64) (err error) {
	if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE issue_id=?", false, issueID); err != nil {
		return err
	}

	// Assignee ID equals to 0 means clear assignee.
	if assigneeID == 0 {
		return nil
	}
	_, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE uid=? AND issue_id=?", true, assigneeID, issueID)
	return err
}
Esempio n. 23
0
func validateOneAdminLeftInOrg(orgId int64, sess *xorm.Session) error {
	// validate that there is an admin user left
	res, err := sess.Query("SELECT 1 from org_user WHERE org_id=? and role='Admin'", orgId)
	if err != nil {
		return err
	}

	if len(res) == 0 {
		return m.ErrLastOrgAdmin
	}

	return err
}
Esempio n. 24
0
// addDeployKey adds new key-repo relation.
func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string) (err error) {
	if err = checkDeployKey(e, keyID, repoID, name); err != nil {
		return err
	}

	_, err = e.Insert(&DeployKey{
		KeyID:       keyID,
		RepoID:      repoID,
		Name:        name,
		Fingerprint: fingerprint,
	})
	return err
}
Esempio n. 25
0
func deleteAlertByIdInternal(alertId int64, reason string, sess *xorm.Session) error {
	sqlog.Debug("Deleting alert", "id", alertId, "reason", reason)

	if _, err := sess.Exec("DELETE FROM alert WHERE id = ?", alertId); err != nil {
		return err
	}

	if _, err := sess.Exec("DELETE FROM annotation WHERE alert_id = ?", alertId); err != nil {
		return err
	}

	return nil
}
Esempio n. 26
0
File: issue.go Progetto: chadoe/gogs
func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
	if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE issue_id=?", false, issue.ID); err != nil {
		return err
	}

	// Assignee ID equals to 0 means clear assignee.
	if issue.AssigneeID > 0 {
		if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE uid=? AND issue_id=?", true, issue.AssigneeID, issue.ID); err != nil {
			return err
		}
	}

	return updateIssue(e, issue)
}
Esempio n. 27
0
File: issue.go Progetto: chadoe/gogs
func deleteIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
	if _, err = e.Delete(&IssueLabel{
		IssueID: issue.ID,
		LabelID: label.ID,
	}); err != nil {
		return err
	}

	label.NumIssues--
	if issue.IsClosed {
		label.NumClosedIssues--
	}
	return updateLabel(e, label)
}
Esempio n. 28
0
File: issue.go Progetto: chadoe/gogs
func newIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
	if _, err = e.Insert(&IssueLabel{
		IssueID: issue.ID,
		LabelID: label.ID,
	}); err != nil {
		return err
	}

	label.NumIssues++
	if issue.IsClosed {
		label.NumClosedIssues++
	}
	return updateLabel(e, label)
}
Esempio n. 29
0
// addDeployKey adds new key-repo relation.
func addDeployKey(e *xorm.Session, keyID, repoID int64, name, fingerprint string) (*DeployKey, error) {
	if err := checkDeployKey(e, keyID, repoID, name); err != nil {
		return nil, err
	}

	key := &DeployKey{
		KeyID:       keyID,
		RepoID:      repoID,
		Name:        name,
		Fingerprint: fingerprint,
	}
	_, err := e.Insert(key)
	return key, err
}
Esempio n. 30
0
func DeleteAlertDefinition(dashboardId int64, sess *xorm.Session) error {
	alerts := make([]*m.Alert, 0)
	sess.Where("dashboard_id = ?", dashboardId).Find(&alerts)

	for _, alert := range alerts {
		_, err := sess.Exec("DELETE FROM alert WHERE id = ? ", alert.Id)
		if err != nil {
			return err
		}

		sqlog.Debug("Alert deleted (due to dashboard deletion)", "name", alert.Name, "id", alert.Id)
	}

	return nil
}