Example #1
0
File: init.go Project: grr89/hrkb
/**
 concate strings with defined operator between
 		concatCOnds("OR","a","b","c","d") returns a OR b OR c OR d
**/
func concatConds(op string, args ...string) (s string) {

	for _, v := range args {
		if v != "" {
			s += v + " " + op + " "
		}
	}

	if s != "" {
		s = utils.CutStr(s, len(op)+2)
	}

	return
}
Example #2
0
File: init.go Project: grr89/hrkb
/**
	generate and execute UPDATE SQL Query
	m model
	f updating fields
	returned affected_rows_count,error (if occured)
		update(&User{Login:"******",Id:10},Sf{"Login","Surname"}) result: UPDATE users SET login=new_login WHERE id=10
**/
func update(m Model, f Sf) (int64, error) {

	var pv pvalues

	if len(f) == 0 {
		return dbmap.Update(m)
	}

	fs, n, table := "", 0, m.Table()

	d := GetTableDic(table)

	r := reflect.ValueOf(m.GetSelf()) //collect cloned object values

	for _, v := range f {

		if val, ok := d[v]; ok {

			f := r.FieldByName(v)
			if f.IsValid() {
				n += 1
				pv = append(pv, f.Interface())
				fs += val + "=$" + strconv.Itoa(n) + ", " //include object value to query if it present in f (updating fields)
			}

		}
	}

	if fs == "" {
		return 0, errors.New("no fields to update")
	}

	if val, ok := d["Id"]; ok {
		n += 1
		pv = append(pv, m.GetId())
		sql := "UPDATE " + table + " SET " + utils.CutStr(fs, 2) + " WHERE " + val + "=$" + strconv.Itoa(n)

		r, err := dbmap.Exec(sql, pv...)

		if err != nil {
			return 0, err
		}

		return r.RowsAffected()
	}

	return 0, errors.New("id not found")

}
Example #3
0
File: init.go Project: grr89/hrkb
func insert(m Model, f Sf) error {

	var pv pvalues

	if len(f) == 0 {
		return dbmap.Insert(m)
	}

	fs, fv, n, table := "", "", 0, m.Table()

	d := GetTableDic(table)

	r := reflect.ValueOf(m.GetSelf())

	for _, v := range f {

		if val, ok := d[v]; ok {

			f := r.FieldByName(v)
			if f.IsValid() {
				n += 1
				pv = append(pv, f.Interface())
				fs += val + ", "
				fv += "$" + strconv.Itoa(n) + ", "
			}

		}
	}

	if fs == "" {
		return errors.New("no fields to insert")
	}

	sql := "INSERT INTO " + table + " (" + utils.CutStr(fs, 2) + ") VALUES (" + utils.CutStr(fv, 2) + ") RETURNING *"
	return dbmap.SelectOne(m, sql, pv...)
}