func PostUser(r render.Render, dbmap *gorp.DbMap, res http.ResponseWriter, u User, e binding.Errors) {
	if e != nil {
		r.JSON(http.StatusBadRequest, map[string]string{"message": e[0].Message})
		return
	}
	//check user exists yet or not?
	var count int64
	count, err := dbmap.SelectInt("SELECT count(*) FROM CUSTOMER WHERE CUS_TEL=?", u.PhoneNumber)
	if err != nil {
		glog.V(1).Infof("[DEBUG:] Search customer by tel:%v fail:%v", u.PhoneNumber, err)
		r.JSON(http.StatusConflict, map[string]string{"message": "DB ERROR"})
		return
	}

	if count > 0 {
		glog.V(1).Infof("Customer with tel:%v exists yet", u.PhoneNumber)
		r.JSON(http.StatusConflict, map[string]string{"message": "User with same Tel exists"})
		return
	}

	//insert new user info to db;
	err = dbmap.Insert(&u)
	if err != nil {
		glog.V(1).Infof("[DEBUG:] Insert customer %v fail:%v", u, err)
		r.JSON(http.StatusConflict, map[string]string{"message": "DB ERROR"})
		return
	}
	r.JSON(200, map[string]string{"message": "SUCCESS"})
}
Example #2
0
// Updates the common game information
func updateGameInfo(games <-chan GameInfo, db *gorp.DbMap) <-chan GameInfo {
	// TODO: Use insert/update query instead
	var gameInfoQuery string = `
                            INSERT IGNORE INTO game_info
                                (id, mode, type, subType, mapId, date)
                            VALUES
                                (?, ?, ?, ?, ?, FROM_UNIXTIME(?))`

	out := make(chan GameInfo)
	globalWg.Add(1)
	go func() {

		for gi := range games {
			_, infoErr := db.Exec(
				gameInfoQuery,
				gi.Game.GameID,
				gi.Game.GameMode,
				gi.Game.GameType,
				gi.Game.SubType,
				gi.Game.MapID,
				gi.Game.CreateDate/1000)
			checkErr(infoErr, "Unable to insert new game info")

			out <- gi
		}
		close(out)

		globalWg.Done()
	}()

	return out
}
Example #3
0
// Get list of available summoners
func getSummoners(dbmap *gorp.DbMap) (
	<-chan SummonerInfo, <-chan SummonerInfo) {

	summonerChan1 := make(chan SummonerInfo)
	summonerChan2 := make(chan SummonerInfo)

	// select summoners
	var summoners []SummonerInfo
	_, err := dbmap.Select(
		&summoners,
		"select id from summoners")
	checkErr(err, "Selecting summoner ids failed")

	globalWg.Add(1)
	go func() {
		for _, n := range summoners {
			summonerChan1 <- n
			summonerChan2 <- n
		}
		close(summonerChan1)
		close(summonerChan2)
		globalWg.Done()
	}()

	return summonerChan1, summonerChan2
}
Example #4
0
func SetForItem(db *gorp.DbMap, tagId, itemId int64, itemType string) error {
	t := Tags{}
	t.Id = tagId
	t.ItemId = itemId
	t.ItemType = itemType
	return db.Insert(&t)
}
Example #5
0
func createTag(db *gorp.DbMap, t Tag) (Tag, error) {
	var err error
	if !tagExist(db, t.Title) {
		err = db.Insert(&t)
	}
	return t, err
}
Example #6
0
func CreateOrder(db *gorp.DbMap, customer, storeid, deliveryid int64, phone,
	address string, products []OrderProduct, price float64) (Order, error) {
	t := time.Now().UnixNano()
	o := Order{
		CustomerId: customer,
		StoreId:    storeid,
		DeliveryId: deliveryid,
		Phone:      phone,
		Price:      price,
		Address:    address,
		Created:    t,
		Updated:    t,
	}
	tx, err := db.Begin()
	if err != nil {
		return o, err
	}
	err = tx.Insert(&o)
	if err != nil {
		tx.Rollback()
		return o, err
	}
	for _, v := range products {
		v.OrderId = o.Id
		err := tx.Insert(&v)
		if err != nil {
			tx.Rollback()
			return o, err
		}
	}
	tx.Commit()
	o.Products = products
	return o, err
}
Example #7
0
func getAllCats(dbmap *gorp.DbMap) []interface{} {
	tab, err := dbmap.Select(Category{}, "SELECT * FROM Category")
	if err != nil {
		fmt.Println("Problem z Category InitDb")
	}
	return tab
}
Example #8
0
func (c *Article) AddReadReceipts(dbmap *gorp.DbMap) {
	var delivered []string
	_, err := dbmap.Select(&delivered, `
        select readers.distinct_id
        from articles
           inner join read_receipts on read_receipts.article_id = articles.id
           inner join readers on read_receipts.reader_id = readers.id
        where articles.id = $1
				  and last_read_at > articles.updated_at`, c.Id)
	if err != nil {
		panic(err)
	}
	c.Delivered = delivered

	var pending []string
	_, err = dbmap.Select(&pending, `
        select readers.distinct_id
        from articles
           inner join read_receipts on read_receipts.article_id = articles.id
           inner join readers on read_receipts.reader_id = readers.id
        where articles.id = $1
				  and (last_read_at is null or
						   last_read_at < articles.updated_at)`, c.Id)
	if err != nil {
		panic(err)
	}
	c.Pending = pending
}
Example #9
0
func FindArticleWithReadReceipts(dbmap *gorp.DbMap, id int64) (*Article, error) {
	var a Article
	err := dbmap.SelectOne(&a, "select * from articles where id = $1", id)
	a.AddReadReceipts(dbmap)

	return &a, err
}
Example #10
0
func Transact(dbm *gorp.DbMap, f func(gorp.SqlExecutor) error) error {
	txn, err := dbm.Begin()
	if err != nil {
		return err
	}
	defer func() {
		if txn == nil {
			return
		}
		if err := txn.Rollback(); err != nil && err != sql.ErrTxDone {
			panic(err)
		}
	}()

	err = f(txn)
	if err != nil {
		return err
	}

	err = txn.Commit()
	if err != nil && err != sql.ErrTxDone {
		return err
	}
	txn = nil
	return nil
}
Example #11
0
func (r Rate) GetRateById(Db *gorp.DbMap, id int64) Rate {
	Db.SelectOne(&r, "select * from Rate where Id = ?", id)
	if r.Id != 0 {
		r.Votes = r.GetVotes(Db)
	}
	return r
}
func PrintTable(dbMap *gorp.DbMap) {
	var users []User

	dbMap.Select(&users, "SELECT * FROM users")

	fmt.Printf("%+v\n", users)
}
Example #13
0
func (r Rate) GetVotes(Db *gorp.DbMap) []Vote {
	if r.Id == 0 {
		return []Vote{}
	}
	Db.Select(&r.Votes, "select * from Vote where RateId = ?", r.Id)
	return r.Votes
}
Example #14
0
func GetGeoObjects(db *gorp.DbMap, tp string, offset, limit int64) ([]GeoObject,
	error) {
	o := []GeoObject{}
	_, err := db.Select(&o, "select * from GeoObject where Type = ? limit ?,?",
		tp, offset, limit)
	return o, err
}
Example #15
0
func UserGet(ren render.Render, params martini.Params, dbmap *gorp.DbMap, s sessions.Session) {
	var usr User
	log.Println(params)
	err := dbmap.SelectOne(&usr, "SELECT * from users WHERE id = $1", s.Get("userId"))
	PanicIf(err)
	ren.JSON(200, usr)
}
Example #16
0
func NewForStruct(dbmap *gorp.DbMap, i interface{}) (*builder, error) {
	table := dbmap.GetTable(i)
	if table == nil {
		return nil, TableNotDefined
	}
	return New(table.TableName), nil
}
Example #17
0
func (u *User) NewPassword(db *gorp.DbMap, password string) error {
	u.HashedPassword, _ = bcrypt.GenerateFromPassword(
		[]byte(password), bcrypt.DefaultCost)
	u.Updated = time.Now().UnixNano()
	_, err := db.Update(u)
	return err
}
Example #18
0
func (n New) AddImages(db *gorp.DbMap, iids []int64) error {
	n.GetImages(db)
	for _, v := range n.Images {
		for _, j := range iids {
			if v == j {
				return errors.New("Image already taken")
			}
		}
	}
	tx, err := db.Begin()
	if err != nil {
		return err
	}
	for _, v := range iids {
		NewImage := NewImages{
			NewId:   n.Id,
			ImageId: v,
		}
		err := tx.Insert(&NewImage)
		if err != nil {
			tx.Rollback()
			return err
		}
	}
	tx.Commit()
	return nil
}
Example #19
0
func (u *User) SignUp(db *gorp.DbMap, s SmsSender, firstname, lastname, phone,
	password string) error {
	u.FirstName = firstname
	u.LastName = lastname
	u.Phone = phone
	u.HashedPassword, _ = bcrypt.GenerateFromPassword(
		[]byte(password), bcrypt.DefaultCost)

	_, err := db.Update(u)
	if err != nil {
		return err
	}

	conf, err := generateConfirmation(db, u.Id)
	if err != nil {
		return err
	}

	message := fmt.Sprintf("You code %d. Session %d.", conf.Code, conf.Id)

	err = s.Send(phone, message)
	if err != nil {
		return err
	}

	return nil
}
Example #20
0
// Query generates a Query for a target model.  The target that is
// passed in must be a pointer to a struct, and will be used as a
// reference for query construction.
func Query(m *gorp.DbMap, exec gorp.SqlExecutor, target interface{}) interfaces.Query {
	// Handle non-standard dialects
	switch src := m.Dialect.(type) {
	case gorp.MySQLDialect:
		m.Dialect = dialects.MySQLDialect{src}
	case gorp.SqliteDialect:
		m.Dialect = dialects.SqliteDialect{src}
	default:
	}
	plan := &QueryPlan{
		dbMap:    m,
		executor: exec,
	}

	targetVal := reflect.ValueOf(target)
	if targetVal.Kind() != reflect.Ptr || targetVal.Elem().Kind() != reflect.Struct {
		plan.Errors = append(plan.Errors, errors.New("A query target must be a pointer to struct"))
	}
	targetTable, err := plan.mapTable(targetVal)
	if err != nil {
		plan.Errors = append(plan.Errors, err)
		return plan
	}
	plan.target = targetVal
	plan.table = targetTable
	return plan
}
Example #21
0
func AddPage(Db *gorp.DbMap, fullurl string) (SitePage, error) {
	fullurl = n(fullurl)
	u, _ := url.Parse(fullurl)
	res := SitePage{}
	if IsExistPage(Db, fullurl) {
		return res, errors.New("exist")
	}

	if !IsExistSite(Db, fullurl) {
		_, err := AddSite(Db, fullurl)
		if err != nil {
			return res, err
		}
	}

	site, err := GetSite(Db, fullurl)
	if err != nil {
		return res, errors.New("site not exist")
	}

	res.SiteId = site.Id
	res.Url = u.RequestURI()

	err = Db.Insert(&res)
	if err != nil {
		return res, err
	}

	return res, nil
}
Example #22
0
func tagExist(db *gorp.DbMap, name string) bool {
	id, _ := db.SelectInt("select Id from Tag where Title = ?", name)
	if id != 0 {
		return true
	}
	return false
}
Example #23
0
func hostState(msg Message, gameId string, playerId int, gs GameService, ws *websocket.Conn, db *gorp.DbMap, log *log.Logger) error {
	log.Printf("Got state change request from host: %v", msg["state"])

	game, _, err := gs.GetGame(db, gameId, playerId)
	if err != nil {
		log.Printf("%#v", err)
		return err
	}

	// TODO: check to make sure this is a valid state
	game.State = msg["state"].(string)
	var board *TicTacToe_Board
	if game.State == "start" {
		board = &TicTacToe_Board{Game: gameId}
		log.Printf("Setting up starting objects")
		// we are starting a game, so insert a new board
		err = board.setBoard([]int{0, 0, 0, 0, 0, 0, 0, 0, 0})
		if err != nil {
			log.Printf("Unable to set game board: %#v", err)
			return err
		}
		log.Printf("Inserting board: %#v", board)
		err = db.Insert(board)
		if err != nil {
			log.Printf("Couldn't insert board: %#v", err)
			return err
		}
	} else {
		board, err = getBoard(gameId, db)
		if err != nil {
			log.Printf("Unable to get board: %#v", err)
			return err
		}
	}
	log.Printf("Updating game state to %#v", game.State)
	count, err := db.Update(game)
	if err != nil || count == 0 {
		log.Printf("Unable to change game state: %v", err)
		return err
	}
	niceBoard, err := board.getBoard()
	if err != nil {
		log.Printf("Error getting board: %#v", board)
		return err
	}
	log.Printf("Sending state %v to all players", msg["state"])
	gs.Broadcast(gameId, Message{
		"type":  "update",
		"board": niceBoard,
		"state": "start",
	})
	log.Printf("Updating UI")
	ws.WriteJSON(Message{
		"type":  "update",
		"board": niceBoard,
		"state": "start",
	})
	return nil
}
Example #24
0
func runQueryPlanSuite(t *testing.T, dialect gorp.Dialect, connection *sql.DB) {
	dbMap := new(gorp.DbMap)
	dbMap.Dialect = dialect
	dbMap.Db = connection
	testSuite := new(QueryPlanTestSuite)
	testSuite.Map = dbMap
	suite.Run(t, testSuite)
}
Example #25
0
func (network *Network) Delete(db *gorp.DbMap) error {
	if len(network.UUID) > 0 {
		_, err := db.Delete(network)
		return err
	}

	return nil
}
Example #26
0
func AdminSetPublished(db *gorp.DbMap, id int64, published bool) error {
	p := 0
	if published {
		p = 1
	}
	_, err := db.Exec("update New set Published = ? where Id =?", p, id)
	return err
}
Example #27
0
func GetBySlug(db *gorp.DbMap, slug string) (WikiPage, bool) {
	w := WikiPage{}
	err := db.SelectOne(&w, "select * from WikiPage where Title = ?", slug)
	if err != nil {
		return w, false
	}
	return w, true
}
Example #28
0
func GetComments(db *gorp.DbMap, itemid int64, itemtype string) ([]Comment,
	error) {
	var cs []Comment
	_, err := db.Select(&cs, "select * from Comment where ItemId = ? and"+
		" ItemType = ? and Deleted = 0 order by Id desc",
		itemid, itemtype)
	return cs, err
}
Example #29
0
func getNeoId(dbMap *gorp.DbMap, code string) (int, error) {
	id, err := dbMap.SelectInt("SELECT id FROM neo_map WHERE code ='" + code + "'")
	if err != nil {
		fmt.Println(err)
		return 0, err
	}
	return int(id), nil
}
Example #30
0
func ProductsCreate(product models.Product, db *gorp.DbMap, render render.Render) {
	err := db.Insert(&product)
	if err == nil {
		render.JSON(201, &product)
	} else {
		render.JSON(422, map[string]string{"error": err.Error()})
	}
}