Example #1
0
func CleanDB(x *xorm.Engine) {
	if x.DriverName() == "postgres" {
		sess := x.NewSession()
		defer sess.Close()

		if _, err := sess.Exec("DROP SCHEMA public CASCADE;"); err != nil {
			panic("Failed to drop schema public")
		}

		if _, err := sess.Exec("CREATE SCHEMA public;"); err != nil {
			panic("Failed to create schema public")
		}
	} else if x.DriverName() == "mysql" {
		tables, _ := x.DBMetas()
		sess := x.NewSession()
		defer sess.Close()

		for _, table := range tables {
			if _, err := sess.Exec("set foreign_key_checks = 0"); err != nil {
				panic("failed to disable foreign key checks")
			}
			if _, err := sess.Exec("drop table " + table.Name + " ;"); err != nil {
				panic(fmt.Sprintf("failed to delete table: %v, err: %v", table.Name, err))
			}
			if _, err := sess.Exec("set foreign_key_checks = 1"); err != nil {
				panic("failed to disable foreign key checks")
			}
		}
	}
}
Example #2
0
func createMultiTables(engine *xorm.Engine, t *testing.T) {
	session := engine.NewSession()
	defer session.Close()

	user := &Userinfo{}
	err := session.Begin()
	if err != nil {
		t.Error(err)
		panic(err)
	}
	for i := 0; i < 10; i++ {
		tableName := fmt.Sprintf("user_%v", i)

		err = session.DropTable(tableName)
		if err != nil {
			session.Rollback()
			t.Error(err)
			panic(err)
		}

		err = session.Table(tableName).CreateTable(user)
		if err != nil {
			session.Rollback()
			t.Error(err)
			panic(err)
		}
	}
	err = session.Commit()
	if err != nil {
		t.Error(err)
		panic(err)
	}
}
func GetCustomers(ctx *macaron.Context, x *xorm.Engine) {
	m, _ := url.ParseQuery(ctx.Req.URL.RawQuery)
	glog.V(1).Infof("Debug %#v", m)
	skip := 0
	limit := 0
	var err error

	if v, ok := m["skip"]; ok {
		skip, _ = strconv.Atoi(v[0])
	}

	if v, ok := m["limit"]; ok {
		limit, _ = strconv.Atoi(v[0])
	}

	cs := make([]Customer, 0)
	err = x.Limit(limit, skip).Find(&cs)
	if err != nil {
		glog.V(1).Infof("Get customer from db fail:%s", err.Error())
		ctx.JSON(http.StatusInternalServerError, map[string]string{"message": err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, cs)
}
Example #4
0
func DbTx(engine *xorm.Engine, f interface{}) bool {

	session := engine.NewSession()
	defer session.Close()

	err := session.Begin()
	if err != nil {
		log.Println(err)
		return false
	}

	err = Executor((f.(func(*xorm.Session) error))).Run(session)
	if err != nil {
		log.Println(err)
		session.Rollback()
		return false
	}

	err = session.Commit()
	if err != nil {
		log.Println(err)
		return false
	}

	return true
}
Example #5
0
func NewTestEngine(x *xorm.Engine) (err error) {
	switch DbCfg.Type {
	case "mysql":
		x, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
			DbCfg.User, DbCfg.Pwd, DbCfg.Host, DbCfg.Name))
	case "postgres":
		var host, port = "127.0.0.1", "5432"
		fields := strings.Split(DbCfg.Host, ":")
		if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
			host = fields[0]
		}
		if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
			port = fields[1]
		}
		cnnstr := fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s",
			DbCfg.User, DbCfg.Pwd, host, port, DbCfg.Name, DbCfg.SslMode)
		//fmt.Println(cnnstr)
		x, err = xorm.NewEngine("postgres", cnnstr)
	case "sqlite3":
		if !EnableSQLite3 {
			return fmt.Errorf("Unknown database type: %s", DbCfg.Type)
		}
		os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
		x, err = xorm.NewEngine("sqlite3", DbCfg.Path)
	default:
		return fmt.Errorf("Unknown database type: %s", DbCfg.Type)
	}
	if err != nil {
		return fmt.Errorf("models.init(fail to conntect database): %v", err)
	}
	return x.Sync(tables...)
}
func OrmRegModels(eng *xorm.Engine) {
	err := eng.Sync(new(WalletDbT))
	if err != nil {
		logmodels.Logger.Info(logmodels.SPrintError("Database Table", "XORM Engine Sync is err %v", err))
		panic(1)
	}
}
Example #7
0
func testIndexAndUnique(engine *xorm.Engine, t *testing.T) {
	err := engine.CreateTables(&IndexOrUnique{})
	if err != nil {
		t.Error(err)
		//panic(err)
	}

	err = engine.DropTables(&IndexOrUnique{})
	if err != nil {
		t.Error(err)
		//panic(err)
	}

	err = engine.CreateTables(&IndexOrUnique{})
	if err != nil {
		t.Error(err)
		//panic(err)
	}

	err = engine.CreateIndexes(&IndexOrUnique{})
	if err != nil {
		t.Error(err)
		//panic(err)
	}

	err = engine.CreateUniques(&IndexOrUnique{})
	if err != nil {
		t.Error(err)
		//panic(err)
	}
}
Example #8
0
func testDistinct(engine *xorm.Engine, t *testing.T) {
	users := make([]Userinfo, 0)
	departname := engine.TableMapper.Obj2Table("Departname")
	err := engine.Distinct(departname).Find(&users)
	if err != nil {
		t.Error(err)
		panic(err)
	}
	if len(users) != 1 {
		t.Error(err)
		panic(errors.New("should be one record"))
	}

	fmt.Println(users)

	type Depart struct {
		Departname string
	}

	users2 := make([]Depart, 0)
	err = engine.Distinct(departname).Table(new(Userinfo)).Find(&users2)
	if err != nil {
		t.Error(err)
		panic(err)
	}
	if len(users2) != 1 {
		t.Error(err)
		panic(errors.New("should be one record"))
	}
	fmt.Println(users2)
}
Example #9
0
func Login(w http.ResponseWriter, r *http.Request, urlValues map[string]string, db *xorm.Engine) {
	//handle the input
	var input struct {
		Email    string `json:"email" validate:"required"`
		Password string `json:"password" validate:"required"`
	}
	if err := httputil.Bind(r.Body, &input); err != nil {
		middleware.Send(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
		return
	}

	user := model.User{}
	found, err := db.Where("email = ?", input.Email).Get(&user)
	if err != nil {
		middleware.Send(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
		return
	}
	if found == false || bcrypt.CompareHashAndPassword([]byte(user.PasswordDigest), []byte(input.Password)) != nil {
		middleware.Send(w, http.StatusUnauthorized, map[string]string{"error": "Incorrect Email / Password"})
		return
	}

	if newToken, err := auth.Sign(user.Id); err != nil {
		middleware.Send(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
	} else {
		// update JWT Token
		w.Header().Add("Authorization", newToken)
		//allow CORS
		w.Header().Set("Access-Control-Expose-Headers", "Authorization")
		middleware.Send(w, http.StatusOK, map[string]string{"userId": user.Id})
	}
}
Example #10
0
func insertTwoTable(engine *xorm.Engine, t *testing.T) {
	userdetail := Userdetail{ /*Id: 1, */ Intro: "I'm a very beautiful women.", Profile: "sfsaf"}
	userinfo := Userinfo{Username: "******", Departname: "dev", Alias: "lunny4", Created: time.Now(), Detail: userdetail}

	cnt, err := engine.Insert(&userinfo, &userdetail)
	if err != nil {
		t.Error(err)
		panic(err)
	}

	if userinfo.Uid <= 0 {
		err = errors.New("not return id error")
		t.Error(err)
		panic(err)
	}

	if userdetail.Id <= 0 {
		err = errors.New("not return id error")
		t.Error(err)
		panic(err)
	}

	if cnt != 2 {
		err = errors.New("insert not returned 2")
		t.Error(err)
		panic(err)
		return
	}
}
Example #11
0
func join3(engine *xorm.Engine, t *testing.T) {
	_, err := engine.Join("LEFT", "userdetail", "userinfo.id=userdetail.id").Get(&Userinfo{Uid: 1})
	if err != nil {
		t.Error(err)
		panic(err)
	}
}
Example #12
0
func update(engines *xorm.Engine, File *xlsx.Sheet) {
	var num int = 0
	if len(File.Rows) < 1 {
		fmt.Println("检查更新列表.")
		return
	}
	for _, row := range File.Rows[1:] {
		var list []*xlsx.Cell
		for _, cell := range row.Cells {
			list = append(list, cell)
		}
		date := parse(list)
		if date != nil {
			n, err := engines.Where("IssuerId = ? and ServerID = ?", date.IssuerId,
				date.ServerID).MustCols("OnlineNum", "IsRuning", "ServerStyle",
				"IsStartIPWhile", "OrderBy").Update(date)
			if n == 0 || err != nil {
				fmt.Printf("更新:%s出错.\n", fmt.Sprint(*date))
				continue
			}
			engines.Query(fmt.Sprintf("UPDATE NxServerState SET ServerName=N'%s' where IssuerId = %d and ServerID = %d", date.ServerName, date.IssuerId, date.ServerID))
		}
		num++
	}
	fmt.Printf("一共更新%d条数据\n", num)
}
Example #13
0
func TestDropNullStructTable(engine *xorm.Engine, t *testing.T) {
	err := engine.DropTables(new(NullType))
	if err != nil {
		t.Error(err)
		panic(err)
	}
}
Example #14
0
func setEngine(engine *xorm.Engine, useCache bool) {
	if useCache {
		engine.SetDefaultCacher(newCache())
	}
	engine.Logger().ShowSQL(showTestSql)
	engine.Logger().SetLevel(core.LOG_DEBUG)
}
Example #15
0
func generateOrgRandsAndSalt(x *xorm.Engine) (err error) {
	type User struct {
		ID    int64  `xorm:"pk autoincr"`
		Rands string `xorm:"VARCHAR(10)"`
		Salt  string `xorm:"VARCHAR(10)"`
	}

	orgs := make([]*User, 0, 10)
	if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil {
		return fmt.Errorf("select all organizations: %v", err)
	}

	sess := x.NewSession()
	defer sessionRelease(sess)
	if err = sess.Begin(); err != nil {
		return err
	}

	for _, org := range orgs {
		org.Rands = base.GetRandomString(10)
		org.Salt = base.GetRandomString(10)
		if _, err = sess.Id(org.ID).Update(org); err != nil {
			return err
		}
	}

	return sess.Commit()
}
Example #16
0
func NewTestEngine(x *xorm.Engine) (err error) {
	x, err = getEngine()
	if err != nil {
		return fmt.Errorf("models.init(fail to conntect database): %v", err)
	}

	return x.Sync(tables...)
}
Example #17
0
// Update will update a coverpage stored in database.
func (c *TestTable) Update(db *xorm.Engine) error {

	_, err := db.Update(c)
	if err != nil {
		return err
	}
	return nil
}
Example #18
0
func joinCount(engine *xorm.Engine, t *testing.T) {
	count, err := engine.Join("LEFT", "userdetail", "userinfo.id=userdetail.id").Count(&Userinfo{Uid: 1})
	if err != nil {
		t.Error(err)
		panic(err)
	}
	fmt.Println(count)
}
Example #19
0
func NewXormAuth(orm *xorm.Engine, allowAnony bool, perm os.FileMode, encryptFunc func(string) string) (*XormAuth, error) {
	err := orm.Sync2(new(User))
	if err != nil {
		return nil, err
	}

	return &XormAuth{allowAnony, os.ModePerm, orm, encryptFunc}, nil
}
Example #20
0
func joinSameMapper(engine *xorm.Engine, t *testing.T) {
	users := make([]Userinfo, 0)
	err := engine.Join("LEFT", "`Userdetail`", "`Userinfo`.`(id)`=`Userdetail`.`Id`").Find(&users)
	if err != nil {
		t.Error(err)
		panic(err)
	}
}
func PostGood(ctx *macaron.Context, x *xorm.Engine, g Goods) {
	_, err := x.Insert(g)
	if err != nil {
		glog.V(1).Infof("Insert good %#v fail:%s", g, err.Error())
		ctx.JSON(http.StatusBadRequest, map[string]string{"message": err.Error()})
	}
	ctx.JSON(http.StatusCreated, "SUCCESS")
	return
}
func PostCustomer(ctx *macaron.Context, x *xorm.Engine, c Customer) {
	_, err := x.Insert(c)
	if err != nil {
		glog.V(1).Infof("Insert customer %#v fail:%s", c, err.Error())
		ctx.JSON(http.StatusBadRequest, map[string]string{"message": err.Error()})
	}
	ctx.JSON(http.StatusCreated, "SUCCESS")
	return
}
Example #23
0
func testQuery(engine *xorm.Engine, t *testing.T) {
	sql := "select * from userinfo"
	results, err := engine.Query(sql)
	if err != nil {
		t.Error(err)
		panic(err)
	}
	fmt.Println(results)
}
Example #24
0
func exec(engine *xorm.Engine, t *testing.T) {
	sql := "update userinfo set username=? where id=?"
	res, err := engine.Exec(sql, "xiaolun", 1)
	if err != nil {
		t.Error(err)
		panic(err)
	}
	fmt.Println(res)
}
Example #25
0
func execSameMapper(engine *xorm.Engine, t *testing.T) {
	sql := "update `Userinfo` set `Username`=? where (id)=?"
	res, err := engine.Exec(sql, "xiaolun", 1)
	if err != nil {
		t.Error(err)
		panic(err)
	}
	fmt.Println(res)
}
Example #26
0
func havingSameMapper(engine *xorm.Engine, t *testing.T) {
	users := make([]Userinfo, 0)
	err := engine.GroupBy("`Username`").Having("`Username`='xlw'").Find(&users)
	if err != nil {
		t.Error(err)
		panic(err)
	}
	fmt.Println(users)
}
Example #27
0
func join2(engine *xorm.Engine, t *testing.T) {
	users := make([]Userinfo, 0)
	err := engine.Join("LEFT", "userdetail", "userinfo.id=userdetail.id").Find(&users,
		&Userinfo{Uid: 1})
	if err != nil {
		t.Error(err)
		panic(err)
	}
}
Example #28
0
func testDump(engine *xorm.Engine, t *testing.T) {
	fp := engine.Dialect().URI().DbName + ".sql"
	os.Remove(fp)
	err := engine.DumpAllToFile(fp)
	if err != nil {
		t.Error(err)
		fmt.Println(err)
	}
}
Example #29
0
func NewTestEngine(x *xorm.Engine) (err error) {
	x, err = getEngine()
	if err != nil {
		return fmt.Errorf("Connect to database: %v", err)
	}

	x.SetMapper(core.GonicMapper{})
	return x.StoreEngine("InnoDB").Sync2(tables...)
}
Example #30
0
func count(engine *xorm.Engine, t *testing.T) {
	user := Userinfo{Departname: "dev"}
	total, err := engine.Count(&user)
	if err != nil {
		t.Error(err)
		panic(err)
	}
	fmt.Printf("Total %d records!!!\n", total)
}