コード例 #1
0
ファイル: user.go プロジェクト: itsabot/abot
// Create a new user in the database.
func (u *User) Create(db *sqlx.DB, fidT FlexIDType, fid string) error {
	// Create the password hash
	hpw, err := bcrypt.GenerateFromPassword([]byte(u.Password), 10)
	if err != nil {
		return err
	}
	tx, err := db.Beginx()
	if err != nil {
		return err
	}
	q := `INSERT INTO users (name, email, password, locationid, admin)
	      VALUES ($1, $2, $3, 0, $4)
	      RETURNING id`
	var uid uint64
	err = tx.QueryRowx(q, u.Name, u.Email, hpw, u.Admin).Scan(&uid)
	if err != nil && err.Error() ==
		`pq: duplicate key value violates unique constraint "users_email_key"` {
		_ = tx.Rollback()
		return err
	}
	if uid == 0 {
		_ = tx.Rollback()
		return err
	}
	q = `INSERT INTO userflexids (userid, flexid, flexidtype)
	     VALUES ($1, $2, $3)`
	_, err = tx.Exec(q, uid, u.Email, 1)
	if err != nil {
		_ = tx.Rollback()
		return err
	}
	_, err = tx.Exec(q, uid, fid, 2)
	if err != nil {
		_ = tx.Rollback()
		return err
	}
	if err = tx.Commit(); err != nil {
		return err
	}
	u.ID = uid
	return nil
}
コード例 #2
0
ファイル: filldb.go プロジェクト: husio/bb
func upload(resource io.Reader, db *sqlx.DB, repeat int) {
	var feed Feed
	if err := xml.NewDecoder(resource).Decode(&feed); err != nil {
		log.Fatalf("cannot decode resource: %s", err)
	}

	tx, err := db.Beginx()
	if err != nil {
		log.Fatalf("cannot start transaction :%s", err)
	}
	defer tx.Rollback()

	for i := 0; i < repeat; i++ {
		for _, e := range feed.Entries {
			var tid uint
			err = tx.Get(&tid, `
			INSERT INTO topics (title, author_id, created, updated, category_id)
			VALUES ($1, $2, $3, $3, 1)
			RETURNING topic_id
		`, e.Title, 1, e.Updated)
			if err != nil {
				log.Fatalf("cannot insert topic: %s", err)
			}
			_, err = tx.Exec(`
			INSERT INTO messages (topic_id, author_id, content, created)
			VALUES ($1, $2, $3, $4)
		`, tid, 1, e.Summary, e.Updated)
			if err != nil {
				log.Fatalf("cannot insert message: %s", err)
			}
		}
	}

	if err := tx.Commit(); err != nil {
		log.Fatalf("cannot commit transaction: %s", err)
	}
}