Ejemplo n.º 1
0
func (l *Language) UpdateColumns(optsx ...go2sql.UpdateOption) (err error) {
	opts := go2sql.UpdateOptions(optsx)
	db, ok := opts.GetDB()
	if !ok {
		db = go2sql.DefaultDB.DB
	}
	if db == nil {
		err = errors.New("should specify *sql.DB by go2sql.DB or init go2sql.DefaultDB")
		return
	}

	if l.IsNewRow() {
		// return l.Insert(db)
		return errors.New("can't not update a new row")
	}

	var columns []string
	if sel, ok := opts.GetSelect(); ok {
		columns = []string(sel)
	} else {
		return errors.New("empty select/columns")
	}

	var args []interface{}
	var updates []string
	for _, c := range columns {
		updates = append(updates, c+" = ?")
		switch c {
		case LanguageColumnID:
			args = append(args, &l.ID)
		case LanguageColumnName:
			args = append(args, &l.Name)
		case LanguageColumnWordsCount:
			args = append(args, &l.WordsCount)
		default:
			err = fmt.Errorf("go2sql: unknown column %s", c)
			return
		}
	}

	_, err = db.Exec(fmt.Sprintf(`UPDATE languages SET %s where id = ?`, strings.Join(updates, ","), l.ID), args...)
	return
}
Ejemplo n.º 2
0
func (ls *Languages) Update(optsx ...go2sql.UpdateOption) (err error) {
	if l == nil {
		return
	}

	opts := go2sql.UpdateOptions(optsx)
	db, ok := opts.GetDB()
	if !ok {
		db = go2sql.DefaultDB.DB
	}
	if db == nil {
		err = errors.New("should specify *sql.DB by go2sql.DB or init go2sql.DefaultDB")
		return
	}

	tables, _ := opts.GetTables()

	for _, table := range tables {
		switch table.Name {
		case LanguageColumnAuthor:
			if l.Author.IsNewRow() {
				continue
			}
			if err = l.Author.Update(go2sql.DB(db), table.Tables); err != nil {
				return
			}
			l.AuthorID = l.Author.ID
		default:
			err = fmt.Errorf("go2sql: unknown column %s", table)
			return
		}
	}

	if l.IsNewRow() {
		err = l.Insert(go2sql.DB(db))
	} else {
		_, err = db.Exec(`UPDATE languages SET name = ?, words_stat = ? WHERE id = ?`, l.Name, l.WordsCount, l.ID)
	}
	if err != nil {
		return
	}

	for _, table := range tables {
		switch table.Name {
		case LanguageColumnKeywords:
			for index := range l.Keywords {
				l.Keywords[index].LanguageID = l.ID
			}
			keywords := Keywords(l.Keywords)
			if err = keywords.Update(go2sql.DB(db), table.Tables); err != nil {
				return
			}
		case LanguageColumnTeachers:
			teachers := Teachers(l.Teachers)
			if err = teachers.Update(go2sql.DB(db), table.Tables); err != nil {
				return
			}
		default:
			err = fmt.Errorf("go2sql: unknown column %s", table)
			return
		}
	}

	return
}