예제 #1
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)
}
예제 #2
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)
}
예제 #3
0
파일: v14.go 프로젝트: VoyTechnology/gogs
func setCommentUpdatedWithCreated(x *xorm.Engine) (err error) {
	type Comment struct {
		UpdatedUnix int64
	}

	if err = x.Sync2(new(Comment)); err != nil {
		return fmt.Errorf("Sync2: %v", err)
	} else if _, err = x.Exec("UPDATE comment SET updated_unix = created_unix"); err != nil {
		return fmt.Errorf("set update_unix: %v", err)
	}
	return nil
}
예제 #4
0
func trimSpace(x *xorm.Engine) error {
	results, e := x.Query("select id,body from site_feed")
	if e != nil {
		return e
	}
	for _, v := range results {
		body := strings.TrimSpace(com.StrTo(v["body"]).String())
		_, e := x.Exec("update site_feed set body = ? where id = ?", body, com.StrTo(v["id"]).MustInt64())
		if e != nil {
			return e
		}
	}
	return nil
}
예제 #5
0
func testCustomType2(engine *xorm.Engine, t *testing.T) {
	err := engine.CreateTables(&UserCus{})
	if err != nil {
		t.Fatal(err)
	}

	engine.Exec("TRUNCATE TABLE " + engine.TableMapper.Obj2Table("UserCus"))

	_, err = engine.Insert(&UserCus{1, "xlw", Registed})
	if err != nil {
		t.Fatal(err)
	}

	user := UserCus{}
	exist, err := engine.Id(1).Get(&user)
	if err != nil {
		t.Fatal(err)
	}

	if !exist {
		t.Fatal("user not exist")
	}

	fmt.Println(user)

	users := make([]UserCus, 0)
	err = engine.Where("`"+engine.ColumnMapper.Obj2Table("Status")+"` = ?", "Registed").Find(&users)
	if err != nil {
		t.Error(err)
		panic(err)
	}
	if len(users) != 1 {
		t.Error("users should has 1 record.")
		panic("")
	}

	fmt.Println(users)
}
예제 #6
0
파일: migrations.go 프로젝트: kx2015/gogs
func accessRefactor(x *xorm.Engine) (err error) {
	type (
		AccessMode int
		Access     struct {
			ID     int64 `xorm:"pk autoincr"`
			UserID int64 `xorm:"UNIQUE(s)"`
			RepoID int64 `xorm:"UNIQUE(s)"`
			Mode   AccessMode
		}
		UserRepo struct {
			UserID int64
			RepoID int64
		}
	)

	// We consiously don't start a session yet as we make only reads for now, no writes

	accessMap := make(map[UserRepo]AccessMode, 50)

	results, err := x.Query("SELECT r.id AS `repo_id`, r.is_private AS `is_private`, r.owner_id AS `owner_id`, u.type AS `owner_type` FROM `repository` r LEFT JOIN `user` u ON r.owner_id=u.id")
	if err != nil {
		return fmt.Errorf("select repositories: %v", err)
	}
	for _, repo := range results {
		repoID := com.StrTo(repo["repo_id"]).MustInt64()
		isPrivate := com.StrTo(repo["is_private"]).MustInt() > 0
		ownerID := com.StrTo(repo["owner_id"]).MustInt64()
		ownerIsOrganization := com.StrTo(repo["owner_type"]).MustInt() > 0

		results, err := x.Query("SELECT `user_id` FROM `collaboration` WHERE repo_id=?", repoID)
		if err != nil {
			return fmt.Errorf("select collaborators: %v", err)
		}
		for _, user := range results {
			userID := com.StrTo(user["user_id"]).MustInt64()
			accessMap[UserRepo{userID, repoID}] = 2 // WRITE ACCESS
		}

		if !ownerIsOrganization {
			continue
		}

		// The minimum level to add a new access record,
		// because public repository has implicit open access.
		minAccessLevel := AccessMode(0)
		if !isPrivate {
			minAccessLevel = 1
		}

		repoString := "$" + string(repo["repo_id"]) + "|"

		results, err = x.Query("SELECT `id`,`authorize`,`repo_ids` FROM `team` WHERE org_id=? AND authorize>? ORDER BY `authorize` ASC", ownerID, int(minAccessLevel))
		if err != nil {
			if strings.Contains(err.Error(), "no such column") {
				return nil
			}
			return fmt.Errorf("select teams from org: %v", err)
		}

		for _, team := range results {
			if !strings.Contains(string(team["repo_ids"]), repoString) {
				continue
			}
			teamID := com.StrTo(team["id"]).MustInt64()
			mode := AccessMode(com.StrTo(team["authorize"]).MustInt())

			results, err := x.Query("SELECT `uid` FROM `team_user` WHERE team_id=?", teamID)
			if err != nil {
				return fmt.Errorf("select users from team: %v", err)
			}
			for _, user := range results {
				userID := com.StrTo(user["uid"]).MustInt64()
				accessMap[UserRepo{userID, repoID}] = mode
			}
		}
	}

	// Drop table can't be in a session (at least not in sqlite)
	if _, err = x.Exec("DROP TABLE `access`"); err != nil {
		return fmt.Errorf("drop access table: %v", err)
	}

	// Now we start writing so we make a session
	sess := x.NewSession()
	defer sessionRelease(sess)
	if err = sess.Begin(); err != nil {
		return err
	}

	if err = sess.Sync2(new(Access)); err != nil {
		return fmt.Errorf("sync: %v", err)
	}

	accesses := make([]*Access, 0, len(accessMap))
	for ur, mode := range accessMap {
		accesses = append(accesses, &Access{UserID: ur.UserID, RepoID: ur.RepoID, Mode: mode})
	}

	if _, err = sess.Insert(accesses); err != nil {
		return fmt.Errorf("insert accesses: %v", err)
	}

	return sess.Commit()
}
예제 #7
0
파일: migrations.go 프로젝트: kx2015/gogs
func ownerTeamUpdate(x *xorm.Engine) (err error) {
	if _, err := x.Exec("UPDATE `team` SET authorize=4 WHERE lower_name=?", "owners"); err != nil {
		return fmt.Errorf("update owner team table: %v", err)
	}
	return nil
}
예제 #8
0
파일: migrations.go 프로젝트: jessezwd/gogs
func convertDateToUnix(x *xorm.Engine) (err error) {
	type Bean struct {
		ID         int64 `xorm:"pk autoincr"`
		Created    time.Time
		Updated    time.Time
		Merged     time.Time
		Deadline   time.Time
		ClosedDate time.Time
		NextUpdate time.Time
	}

	var tables = []struct {
		name string
		cols []string
		bean interface{}
	}{
		{"action", []string{"created"}, new(TAction)},
		{"notice", []string{"created"}, new(TNotice)},
		{"comment", []string{"created"}, new(TComment)},
		{"issue", []string{"deadline", "created", "updated"}, new(TIssue)},
		{"milestone", []string{"deadline", "closed_date"}, new(TMilestone)},
		{"attachment", []string{"created"}, new(TAttachment)},
		{"login_source", []string{"created", "updated"}, new(TLoginSource)},
		{"pull_request", []string{"merged"}, new(TPull)},
		{"release", []string{"created"}, new(TRelease)},
		{"repository", []string{"created", "updated"}, new(TRepo)},
		{"mirror", []string{"updated", "next_update"}, new(TMirror)},
		{"public_key", []string{"created", "updated"}, new(TPublicKey)},
		{"deploy_key", []string{"created", "updated"}, new(TDeployKey)},
		{"access_token", []string{"created", "updated"}, new(TAccessToken)},
		{"user", []string{"created", "updated"}, new(TUser)},
		{"webhook", []string{"created", "updated"}, new(TWebhook)},
	}

	for _, table := range tables {
		log.Info("Converting table: %s", table.name)
		if err = x.Sync2(table.bean); err != nil {
			return fmt.Errorf("Sync [table: %s]: %v", table.name, err)
		}

		offset := 0
		for {
			beans := make([]*Bean, 0, 100)
			if err = x.Sql(fmt.Sprintf("SELECT * FROM `%s` ORDER BY id ASC LIMIT 100 OFFSET %d",
				table.name, offset)).Find(&beans); err != nil {
				return fmt.Errorf("select beans [table: %s, offset: %d]: %v", table.name, offset, err)
			}
			log.Trace("Table [%s]: offset: %d, beans: %d", table.name, offset, len(beans))
			if len(beans) == 0 {
				break
			}
			offset += 100

			baseSQL := "UPDATE `" + table.name + "` SET "
			for _, bean := range beans {
				valSQLs := make([]string, 0, len(table.cols))
				for _, col := range table.cols {
					fieldSQL := ""
					fieldSQL += col + "_unix = "

					switch col {
					case "deadline":
						if bean.Deadline.IsZero() {
							continue
						}
						fieldSQL += com.ToStr(bean.Deadline.UTC().Unix())
					case "created":
						fieldSQL += com.ToStr(bean.Created.UTC().Unix())
					case "updated":
						fieldSQL += com.ToStr(bean.Updated.UTC().Unix())
					case "closed_date":
						fieldSQL += com.ToStr(bean.ClosedDate.UTC().Unix())
					case "merged":
						fieldSQL += com.ToStr(bean.Merged.UTC().Unix())
					case "next_update":
						fieldSQL += com.ToStr(bean.NextUpdate.UTC().Unix())
					}

					valSQLs = append(valSQLs, fieldSQL)
				}

				if len(valSQLs) == 0 {
					continue
				}

				if _, err = x.Exec(baseSQL + strings.Join(valSQLs, ",") + " WHERE id = " + com.ToStr(bean.ID)); err != nil {
					return fmt.Errorf("update bean [table: %s, id: %d]: %v", table.name, bean.ID, err)
				}
			}
		}
	}

	return nil
}