//----------------------------------------------- Store user struct into db func Store(ud *User) { fields, values := SQL_dump(ud) changes := SQL_set_clause(fields, values) stmt := []string{"UPDATE users SET ", strings.Join(changes, ","), " WHERE id=", fmt.Sprint(ud.Id)} db := <-DBCH defer func() { DBCH <- db }() _, _, err := db.Query(strings.Join(stmt, " ")) CheckErr(err) }
//----------------------------------------------- Store Building-List into db func Store(user_id int32, list []Building, grid *grid.Grid) { str_list := _pack(list) str_bitmap := _encode_map(grid.Bitset) stmt := "UPDATE buildings SET list='%v', bitmap='%v' WHERE user_id = %v" db := <-DBCH defer func() { DBCH <- db }() _, _, err := db.Query(stmt, str_list, str_bitmap, user_id) CheckErr(err) }
//----------------------------------------------- login with MAC addr func LoginMAC(mac string, ud *User) bool { stmt := "SELECT * FROM users where mac='%v'" db := <-DBCH defer func() { DBCH <- db }() rows, res, err := db.Query(stmt, mac) CheckErr(err) if len(rows) > 0 { SQL_load(ud, &rows[0], res) return true } return false }
//----------------------------------------------- login with (name, password) pair func Login(name string, password string, ud *User) bool { stmt := "select * from users where name = '%v' AND password = MD5('%v')" db := <-DBCH defer func() { DBCH <- db }() rows, res, err := db.Query(stmt, SQL_escape(name), SQL_escape(password)) CheckErr(err) if len(rows) > 0 { SQL_load(ud, &rows[0], res) return true } return false }
//----------------------------------------------- Load all users from db func LoadAll() (uds []User) { stmt := "SELECT * FROM users" db := <-DBCH defer func() { DBCH <- db }() rows, res, err := db.Query(stmt) CheckErr(err) for i := range rows { var ud User SQL_load(&ud, &rows[i], res) uds = append(uds, ud) } return }
//----------------------------------------------- Load a user from db func Load(id int32) (ud User, err error) { stmt := "SELECT * FROM users where id ='%v'" db := <-DBCH defer func() { DBCH <- db }() rows, res, err := db.Query(stmt, id) CheckErr(err) if len(rows) > 0 { SQL_load(&ud, &rows[0], res) return } err = errors.New(fmt.Sprint("cannot find user with id:%v", id)) return }
//----------------------------------------------- Loading Building-List from db func Load(user_id int32) (list []Building, grid *grid.Grid, err error) { stmt := "SELECT list, map FROM buildings where user_id ='%v' LIMIT 1" db := <-DBCH defer func() { DBCH <- db }() rows, _, err := db.Query(stmt, user_id) CheckErr(err) if len(rows) > 0 { list = _unpack(rows[0].Str(0)) grid.Bitset = _decode_map(rows[0].Str(1)) } err = errors.New(fmt.Sprint("cannot find building belongs to id:%v", user_id)) return }